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
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! Repository-native agent packages.
//!
//! An agent package is deliberately data, not executable plugin code:
//! `.supercode/package.toml` describes an `agent/` folder, capability
//! requirements, workspace storage, and frontend-neutral JSON contributions.
//! This lets a repository deepen its integration with any Supercode frontend
//! without shipping another agent loop, CLI, MCP server, or UI bundle.

use std::fs;
use std::path::{Component, Path, PathBuf};

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

use crate::error::{Error, Result};

/// Repository-relative location of an agent package manifest.
pub const AGENT_PACKAGE_MANIFEST: &str = ".supercode/package.toml";
/// Current manifest schema version.
pub const AGENT_PACKAGE_SCHEMA_VERSION: u32 = 1;
/// Stable contribution envelope understood by Supercode frontends.
pub const CONTRIBUTION_SCHEMA: &str = "supercode/contribution-v1";
/// Stable envelope for one resolved contribution resource.
pub const RESOURCE_SCHEMA: &str = "supercode/package-resource-v1";

const MAX_MANIFEST_BYTES: u64 = 64 * 1024;
const MAX_CONTRIBUTION_BYTES: u64 = 256 * 1024;
const MAX_CONTRIBUTIONS: usize = 128;
const MAX_RESOURCE_BYTES: u64 = 512 * 1024;

/// A fully resolved, validated repository agent package.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentPackage {
    /// Manifest schema version.
    pub schema_version: u32,
    /// Stable package identifier.
    pub id: String,
    /// Human-readable package name.
    pub name: String,
    /// Descriptive package version.
    pub version: String,
    /// Optional package description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Canonical workspace that owns this package.
    pub workspace: PathBuf,
    /// Canonical `.supercode` package root.
    pub package_root: PathBuf,
    /// Canonical manifest path.
    pub manifest_path: PathBuf,
    /// Resolved portable agent folder.
    pub agent: AgentFolder,
    /// Capabilities the package requires or can optionally use.
    pub capabilities: AgentPackageCapabilities,
    /// Workspace-owned durable data location. Supercode does not create it.
    pub storage: AgentPackageStorage,
    /// Declarative frontend contributions, sorted by source filename.
    pub contributions: Vec<AgentContribution>,
}

/// The resolved instruction and skill roots of an agent package.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentFolder {
    /// Canonical root of the agent folder.
    pub root: PathBuf,
    /// Canonical instruction files, in manifest order.
    pub instructions: Vec<PathBuf>,
    /// Canonical skills directory when one exists.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub skills_root: Option<PathBuf>,
}

/// Capability requirements declared by an agent package.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentPackageCapabilities {
    /// Capabilities without which the package cannot perform its core role.
    pub required: Vec<String>,
    /// Capabilities that enhance the package when a host provides them.
    pub optional: Vec<String>,
}

/// Durable workspace storage requested by an agent package.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentPackageStorage {
    /// Workspace-relative storage path as declared by the package.
    pub relative_path: PathBuf,
    /// Resolved path. It may not exist yet and is never created while loading.
    pub path: PathBuf,
}

/// A portable, inert contribution a frontend may choose to render.
///
/// Unknown `kind` values remain available to newer frontends and are ignored
/// by older ones. `placement` and `data` are declarative JSON; loading a
/// contribution never evaluates code or imports a module.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentContribution {
    /// Must be [`CONTRIBUTION_SCHEMA`].
    pub schema: String,
    /// Stable package-scoped contribution id.
    pub id: String,
    /// Host-neutral kind such as `panel`, `tool-result`, `action`, or `status`.
    pub kind: String,
    /// Optional display title.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Frontend-neutral placement hints.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub placement: Option<Value>,
    /// Kind-specific inert data interpreted by the rendering host.
    #[serde(default)]
    pub data: Value,
    /// Canonical JSON source file, supplied by the loader.
    #[serde(default, skip_deserializing)]
    pub source: PathBuf,
}

/// Browser-safe content loaded for a contribution's declared storage resource.
///
/// The resolved filesystem path is deliberately absent. Consumers address the
/// content by contribution id and receive only bounded JSON or UTF-8 text.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AgentPackageResource {
    /// Must be [`RESOURCE_SCHEMA`].
    pub schema: String,
    /// Contribution that declared this resource.
    pub contribution_id: String,
    /// `json` or `text`.
    pub format: String,
    /// Best-effort media type for presentation.
    pub media_type: String,
    /// Parsed JSON or a JSON string containing bounded UTF-8 text.
    pub data: Value,
}

#[derive(Debug, Deserialize)]
struct RawManifest {
    schema_version: u32,
    id: String,
    name: Option<String>,
    #[serde(default)]
    version: String,
    description: Option<String>,
    agent: RawAgentFolder,
    #[serde(default)]
    capabilities: RawCapabilities,
    storage: RawStorage,
    #[serde(default)]
    contributions: RawContributions,
}

#[derive(Debug, Deserialize)]
struct RawAgentFolder {
    #[serde(default = "default_agent_root")]
    root: PathBuf,
    #[serde(default = "default_instructions")]
    instructions: Vec<PathBuf>,
    #[serde(default = "default_skills_root")]
    skills: PathBuf,
}

#[derive(Debug, Default, Deserialize)]
struct RawCapabilities {
    #[serde(default)]
    required: Vec<String>,
    #[serde(default)]
    optional: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct RawStorage {
    path: PathBuf,
}

#[derive(Debug, Deserialize)]
struct RawContributions {
    #[serde(default = "default_contributions_root")]
    root: PathBuf,
}

impl Default for RawContributions {
    fn default() -> Self {
        Self {
            root: default_contributions_root(),
        }
    }
}

fn default_agent_root() -> PathBuf {
    PathBuf::from("agent")
}

fn default_instructions() -> Vec<PathBuf> {
    vec![PathBuf::from("AGENTS.md")]
}

fn default_skills_root() -> PathBuf {
    PathBuf::from("skills")
}

fn default_contributions_root() -> PathBuf {
    PathBuf::from("contributions")
}

fn package_error(message: impl Into<String>) -> Error {
    Error::tool("agent_package", message)
}

fn validate_id(value: &str, field: &str) -> Result<()> {
    let valid = !value.is_empty()
        && value.len() <= 128
        && value
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'));
    if valid {
        Ok(())
    } else {
        Err(package_error(format!(
            "{field} must contain only ASCII letters, digits, `.`, `-`, or `_`"
        )))
    }
}

fn validate_capabilities(values: Vec<String>, field: &str) -> Result<Vec<String>> {
    let mut out = Vec::with_capacity(values.len());
    for value in values {
        validate_id(&value, field)?;
        if !out.contains(&value) {
            out.push(value);
        }
    }
    Ok(out)
}

fn safe_relative(path: &Path, field: &str) -> Result<()> {
    if path.as_os_str().is_empty()
        || path.is_absolute()
        || path
            .components()
            .any(|component| !matches!(component, Component::Normal(_)))
    {
        return Err(package_error(format!(
            "{field} must be a non-empty relative path without `.` or `..`: {}",
            path.display()
        )));
    }
    Ok(())
}

fn read_bounded(path: &Path, max_bytes: u64, label: &str) -> Result<String> {
    let metadata = fs::metadata(path)
        .map_err(|error| package_error(format!("reading {label} {}: {error}", path.display())))?;
    if !metadata.is_file() {
        return Err(package_error(format!(
            "{label} is not a regular file: {}",
            path.display()
        )));
    }
    if metadata.len() > max_bytes {
        return Err(package_error(format!(
            "{label} exceeds the {max_bytes}-byte limit: {}",
            path.display()
        )));
    }
    fs::read_to_string(path)
        .map_err(|error| package_error(format!("reading {label} {}: {error}", path.display())))
}

fn contained_existing(root: &Path, relative: &Path, field: &str) -> Result<PathBuf> {
    safe_relative(relative, field)?;
    let candidate = root.join(relative);
    let canonical = fs::canonicalize(&candidate).map_err(|error| {
        package_error(format!(
            "resolving {field} {}: {error}",
            candidate.display()
        ))
    })?;
    if !canonical.starts_with(root) {
        return Err(package_error(format!(
            "{field} resolves outside the package root: {}",
            candidate.display()
        )));
    }
    Ok(canonical)
}

/// Load the agent package rooted at `workspace`.
///
/// `Ok(None)` means this is an ordinary repository with no
/// `.supercode/package.toml`. Loading is read-only and never executes package
/// content or creates its requested storage directory.
pub fn load_workspace_agent_package(workspace: &Path) -> Result<Option<AgentPackage>> {
    let workspace = fs::canonicalize(workspace).map_err(|error| {
        package_error(format!(
            "resolving workspace {}: {error}",
            workspace.display()
        ))
    })?;
    let manifest_path = workspace.join(AGENT_PACKAGE_MANIFEST);
    if !manifest_path.exists() {
        return Ok(None);
    }
    let manifest_path = fs::canonicalize(&manifest_path).map_err(|error| {
        package_error(format!("resolving {}: {error}", manifest_path.display()))
    })?;
    let package_root = manifest_path
        .parent()
        .expect("the manifest always has a .supercode parent")
        .to_path_buf();
    if !package_root.starts_with(&workspace) {
        return Err(package_error(
            "agent package manifest resolves outside workspace",
        ));
    }

    let text = read_bounded(&manifest_path, MAX_MANIFEST_BYTES, "agent package manifest")?;
    let raw: RawManifest = toml::from_str(&text)
        .map_err(|error| package_error(format!("parsing {}: {error}", manifest_path.display())))?;
    if raw.schema_version != AGENT_PACKAGE_SCHEMA_VERSION {
        return Err(package_error(format!(
            "unsupported agent package schema_version {}; expected {}",
            raw.schema_version, AGENT_PACKAGE_SCHEMA_VERSION
        )));
    }
    validate_id(&raw.id, "package id")?;
    let name = raw.name.unwrap_or_else(|| raw.id.clone());
    if name.trim().is_empty() {
        return Err(package_error("package name cannot be empty"));
    }

    let agent_root = contained_existing(&package_root, &raw.agent.root, "agent.root")?;
    if !agent_root.is_dir() {
        return Err(package_error(format!(
            "agent.root is not a directory: {}",
            agent_root.display()
        )));
    }
    let mut instructions = Vec::with_capacity(raw.agent.instructions.len());
    for relative in raw.agent.instructions {
        let path = contained_existing(&agent_root, &relative, "agent.instructions")?;
        if !path.is_file() {
            return Err(package_error(format!(
                "agent instruction is not a file: {}",
                path.display()
            )));
        }
        instructions.push(path);
    }
    let skills_candidate = agent_root.join(&raw.agent.skills);
    safe_relative(&raw.agent.skills, "agent.skills")?;
    let skills_root = if skills_candidate.exists() {
        let path = contained_existing(&agent_root, &raw.agent.skills, "agent.skills")?;
        if !path.is_dir() {
            return Err(package_error(format!(
                "agent.skills is not a directory: {}",
                path.display()
            )));
        }
        Some(path)
    } else {
        None
    };

    safe_relative(&raw.storage.path, "storage.path")?;
    let storage_path = workspace.join(&raw.storage.path);
    if storage_path.exists() {
        let canonical_storage = fs::canonicalize(&storage_path).map_err(|error| {
            package_error(format!(
                "resolving storage.path {}: {error}",
                storage_path.display()
            ))
        })?;
        if !canonical_storage.starts_with(&workspace) {
            return Err(package_error(format!(
                "storage.path resolves outside the workspace: {}",
                storage_path.display()
            )));
        }
        if !canonical_storage.is_dir() {
            return Err(package_error(format!(
                "storage.path is not a directory: {}",
                storage_path.display()
            )));
        }
    }
    let storage = AgentPackageStorage {
        path: storage_path,
        relative_path: raw.storage.path,
    };

    let contributions_root = package_root.join(&raw.contributions.root);
    safe_relative(&raw.contributions.root, "contributions.root")?;
    let contributions = if contributions_root.exists() {
        let contributions_root =
            contained_existing(&package_root, &raw.contributions.root, "contributions.root")?;
        if !contributions_root.is_dir() {
            return Err(package_error(format!(
                "contributions.root is not a directory: {}",
                contributions_root.display()
            )));
        }
        load_contributions(&contributions_root, &raw.id)?
    } else {
        Vec::new()
    };

    Ok(Some(AgentPackage {
        schema_version: raw.schema_version,
        id: raw.id,
        name,
        version: if raw.version.trim().is_empty() {
            "0.0.0".to_string()
        } else {
            raw.version
        },
        description: raw.description.filter(|value| !value.trim().is_empty()),
        workspace,
        package_root,
        manifest_path,
        agent: AgentFolder {
            root: agent_root,
            instructions,
            skills_root,
        },
        capabilities: AgentPackageCapabilities {
            required: validate_capabilities(raw.capabilities.required, "required capability")?,
            optional: validate_capabilities(raw.capabilities.optional, "optional capability")?,
        },
        storage,
        contributions,
    }))
}

fn load_contributions(root: &Path, package_id: &str) -> Result<Vec<AgentContribution>> {
    let mut files = fs::read_dir(root)
        .map_err(|error| package_error(format!("reading {}: {error}", root.display())))?
        .filter_map(std::result::Result::ok)
        .map(|entry| entry.path())
        .filter(|path| path.extension().and_then(|value| value.to_str()) == Some("json"))
        .collect::<Vec<_>>();
    files.sort();
    if files.len() > MAX_CONTRIBUTIONS {
        return Err(package_error(format!(
            "contributions.root contains {} JSON files; limit is {MAX_CONTRIBUTIONS}",
            files.len()
        )));
    }

    let mut contributions = Vec::with_capacity(files.len());
    let mut ids = std::collections::HashSet::new();
    for path in files {
        let canonical = fs::canonicalize(&path).map_err(|error| {
            package_error(format!(
                "resolving contribution {}: {error}",
                path.display()
            ))
        })?;
        if !canonical.starts_with(root) {
            return Err(package_error(format!(
                "contribution resolves outside contributions.root: {}",
                path.display()
            )));
        }
        let text = read_bounded(&canonical, MAX_CONTRIBUTION_BYTES, "contribution")?;
        let mut contribution: AgentContribution = serde_json::from_str(&text).map_err(|error| {
            package_error(format!(
                "parsing contribution {}: {error}",
                canonical.display()
            ))
        })?;
        if contribution.schema != CONTRIBUTION_SCHEMA {
            return Err(package_error(format!(
                "contribution {} has unsupported schema `{}`",
                canonical.display(),
                contribution.schema
            )));
        }
        validate_id(&contribution.id, "contribution id")?;
        if contribution.id != package_id && !contribution.id.starts_with(&format!("{package_id}."))
        {
            return Err(package_error(format!(
                "contribution id `{}` must be `{package_id}` or start with `{package_id}.`",
                contribution.id
            )));
        }
        validate_id(&contribution.kind, "contribution kind")?;
        contribution_resource_relative(&contribution)?;
        if !ids.insert(contribution.id.clone()) {
            return Err(package_error(format!(
                "duplicate contribution id `{}`",
                contribution.id
            )));
        }
        contribution.source = canonical;
        contributions.push(contribution);
    }
    Ok(contributions)
}

fn contribution_resource_relative(contribution: &AgentContribution) -> Result<Option<PathBuf>> {
    let Some(resource) = contribution.data.get("resource") else {
        return Ok(None);
    };
    let resource = resource.as_str().ok_or_else(|| {
        package_error(format!(
            "contribution `{}` data.resource must be a string",
            contribution.id
        ))
    })?;
    let relative = PathBuf::from(resource);
    safe_relative(
        &relative,
        &format!("contribution `{}` data.resource", contribution.id),
    )?;
    Ok(Some(relative))
}

/// Contribution ids that declare a storage-scoped resource, in source order.
pub fn declared_resource_contribution_ids(package: &AgentPackage) -> Vec<&str> {
    package
        .contributions
        .iter()
        .filter(|contribution| contribution.data.get("resource").is_some())
        .map(|contribution| contribution.id.as_str())
        .collect()
}

/// Read one contribution's declared resource from inside package storage.
///
/// `Ok(None)` means either the contribution has no resource declaration or
/// the agent has not created the declared file yet. Existing resources must be
/// regular bounded UTF-8 files whose canonical path remains under the package
/// storage directory. This function is read-only and never creates storage.
pub fn read_contribution_resource(
    package: &AgentPackage,
    contribution_id: &str,
) -> Result<Option<AgentPackageResource>> {
    let contribution = package
        .contributions
        .iter()
        .find(|contribution| contribution.id == contribution_id)
        .ok_or_else(|| package_error(format!("unknown contribution id `{contribution_id}`")))?;
    let Some(relative) = contribution_resource_relative(contribution)? else {
        return Ok(None);
    };
    if !package.storage.path.exists() {
        return Ok(None);
    }
    let storage = fs::canonicalize(&package.storage.path).map_err(|error| {
        package_error(format!(
            "resolving storage.path {}: {error}",
            package.storage.path.display()
        ))
    })?;
    if !storage.starts_with(&package.workspace) || !storage.is_dir() {
        return Err(package_error("package storage is unavailable"));
    }
    let candidate = storage.join(&relative);
    if !candidate.exists() {
        return Ok(None);
    }
    let resource = fs::canonicalize(&candidate).map_err(|error| {
        package_error(format!(
            "resolving contribution resource {}: {error}",
            candidate.display()
        ))
    })?;
    if !resource.starts_with(&storage) {
        return Err(package_error(format!(
            "contribution `{contribution_id}` resource resolves outside package storage"
        )));
    }
    let text = read_bounded(&resource, MAX_RESOURCE_BYTES, "contribution resource")?;
    let extension = resource.extension().and_then(|value| value.to_str());
    let (format, media_type, data) = if extension == Some("json") {
        let data = serde_json::from_str(&text).map_err(|error| {
            package_error(format!(
                "parsing contribution `{contribution_id}` JSON resource: {error}"
            ))
        })?;
        ("json", "application/json", data)
    } else {
        let media_type = match extension {
            Some("md" | "markdown") => "text/markdown",
            Some("yaml" | "yml") => "application/yaml",
            _ => "text/plain",
        };
        ("text", media_type, Value::String(text))
    };
    Ok(Some(AgentPackageResource {
        schema: RESOURCE_SCHEMA.to_string(),
        contribution_id: contribution_id.to_string(),
        format: format.to_string(),
        media_type: media_type.to_string(),
        data,
    }))
}

/// Resolve package instruction files for prompt assembly. Invalid packages
/// fail closed by contributing nothing; callers that need diagnostics should
/// use [`load_workspace_agent_package`] directly.
pub(crate) fn workspace_package_instruction_files(workspace: &Path) -> Vec<PathBuf> {
    match load_workspace_agent_package(workspace) {
        Ok(Some(package)) => package.agent.instructions,
        Ok(None) => Vec::new(),
        Err(error) => {
            eprintln!(
                "warning: ignoring invalid Supercode agent package in {}: {error}",
                workspace.display()
            );
            Vec::new()
        }
    }
}