agent-workspace-contract 0.7.0

Transport-neutral contracts for Agent Infra workspace APIs
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
//! Skill Hub installation contracts include executable dependencies and owned file lifecycle.
use super::*;
use agent_secret_contract::SecretRef;
use std::collections::BTreeMap;

/// Product path for installing a Skills Hub package into a running Sandbox.
pub const SANDBOX_SKILLS_PATH: &str = "/internal/v1/workspace/sandboxes/{sandboxId}/skills";

/// Product path for installing a Skills Hub package into a Runtime-bound Space.
pub const SPACE_SKILLS_PATH: &str = "/internal/v1/workspace/spaces/{spaceId}/skills";

/// Product path for searching published Skills Hub packages.
pub const SKILLS_SEARCH_PATH: &str = "/internal/v1/workspace/skills:search";

/// Sandbox-root directory that receives unpacked skill packages.
pub const SANDBOX_SKILL_INSTALL_ROOT: &str = "skills";

/// Space-relative directory that Runtime workspace tools expose to the agent.
pub const SPACE_SKILL_INSTALL_ROOT: &str = "skills";

pub const SPACE_CLI_INSTALL_ROOT: &str = ".local/bin";
/// One shared budget bounds both a downloaded CLI and all CLI dependencies of a Skill.
/// Standalone runtimes (for example Ignis) can exceed 64 MiB.
pub const SKILL_CLI_MAX_BYTES: usize = 128 * 1024 * 1024;

/// POSIX export file written next to installed skill packages so later execs
/// can inject `os.environ` values.
pub const SKILL_ENV_FILE: &str = "skills/.env";

/// Default Skills Hub version selector when the caller omits `version`.
pub const SANDBOX_SKILL_DEFAULT_VERSION: &str = "latest";

/// Default sandbox provider when the caller omits `provider`.
pub const SANDBOX_SKILL_DEFAULT_PROVIDER: &str = "local";

/// Maximum number of environment variables accepted on one skill install.
pub const SKILL_ENV_MAX_ENTRIES: usize = 64;

/// Maximum UTF-8 bytes allowed for one skill environment value.
pub const SKILL_ENV_MAX_VALUE_BYTES: usize = 8 * 1024;

fn default_sandbox_skill_provider() -> String {
    SANDBOX_SKILL_DEFAULT_PROVIDER.to_string()
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct InstallSandboxSkillRequest {
    pub group: String,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    /// Sandbox provider to write into: `local`, `e2b`, or `moulin`.
    #[serde(default = "default_sandbox_skill_provider")]
    pub provider: String,
    /// Plaintext process environment injected for later skill script execution.
    /// Prefer `env_refs` for secrets; both are merged, with `env_refs` resolved
    /// server-side.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub env: BTreeMap<String, String>,
    /// Secret references (`secret://…`) resolved by the workspace secret store at
    /// install time and merged into the injected environment. Values are never
    /// plaintext on the wire; the resolved plaintext is written only into the
    /// sandbox `.env` file.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub env_refs: BTreeMap<String, SecretRef>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct InstallSandboxSkillResource {
    pub sandbox_id: String,
    pub provider: String,
    pub group: String,
    pub name: String,
    pub version: String,
    pub install_path: String,
    pub files: Vec<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub env: BTreeMap<String, String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct InstallSpaceSkillRequest {
    pub group: String,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    /// Computer provider that owns the Space: `local`, `e2b`, or `moulin`.
    #[serde(default = "default_sandbox_skill_provider")]
    pub provider: String,
    /// Plaintext process environment injected for later skill script execution.
    /// Prefer `env_refs` for secrets; both are merged, with `env_refs` resolved
    /// server-side.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub env: BTreeMap<String, String>,
    /// Secret references (`secret://…`) resolved by the workspace secret store at
    /// install time and merged into the injected environment. Values are never
    /// plaintext on the wire; the resolved plaintext is written only into the
    /// Space `.env` file.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub env_refs: BTreeMap<String, SecretRef>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct InstallSpaceSkillResource {
    pub space_id: String,
    pub computer_id: String,
    pub provider: String,
    pub group: String,
    pub name: String,
    pub version: String,
    pub install_path: String,
    pub files: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub clis: Vec<InstalledSpaceCli>,
    pub revision: u64,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub env: BTreeMap<String, String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct InstalledSpaceCli {
    pub full_name: String,
    pub version: String,
    pub entrypoint: String,
    pub install_path: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkillPackageFile {
    pub path: String,
    pub content: Vec<u8>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkillPackage {
    pub group: String,
    pub name: String,
    pub version: String,
    pub files: Vec<SkillPackageFile>,
    pub cli: BTreeMap<String, String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkillCliPackage {
    pub full_name: String,
    pub version: String,
    pub entrypoint: String,
    pub bytes: Vec<u8>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SkillSearchQuery {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub q: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub page: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SkillSearchItem {
    pub group: String,
    pub name: String,
    pub full_name: String,
    #[serde(default)]
    pub description: String,
    #[serde(default)]
    pub latest_version: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub skill_type: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SkillSearchPage {
    pub items: Vec<SkillSearchItem>,
    #[serde(default)]
    pub page: u32,
    #[serde(default)]
    pub limit: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub total: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub has_more: Option<bool>,
}

/// Downloads a published skill archive. Implementations live in adapter crates.
#[async_trait]
pub trait SkillHubClient: Send + Sync + Debug {
    async fn download_skill(
        &self,
        group: &str,
        name: &str,
        version: &str,
        user_authorization: &str,
    ) -> Result<SkillPackage>;

    async fn download_cli(
        &self,
        full_name: &str,
        version: &str,
        os: &str,
        arch: &str,
        user_authorization: &str,
    ) -> Result<SkillCliPackage> {
        let _ = (full_name, version, os, arch, user_authorization);
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "Skills Hub client does not support CLI distributions",
        )
        .into())
    }

    async fn search_skills(
        &self,
        query: &SkillSearchQuery,
        user_authorization: &str,
    ) -> Result<SkillSearchPage>;
}

/// Validate skill-install environment names and values.
pub fn validate_skill_env(env: &BTreeMap<String, String>) -> Result<()> {
    if env.len() > SKILL_ENV_MAX_ENTRIES {
        anyhow::bail!("skill env cannot contain more than {SKILL_ENV_MAX_ENTRIES} entries");
    }
    let mut total = 0_usize;
    for (name, value) in env {
        if !valid_skill_env_name(name) {
            anyhow::bail!("skill env name {name:?} is invalid");
        }
        if value.contains('\0') {
            anyhow::bail!("skill env value for {name} contains a NUL byte");
        }
        if value.len() > SKILL_ENV_MAX_VALUE_BYTES {
            anyhow::bail!("skill env value for {name} exceeds size policy");
        }
        total = total
            .checked_add(name.len())
            .and_then(|bytes| bytes.checked_add(value.len()))
            .ok_or_else(|| anyhow::anyhow!("skill env exceeds size policy"))?;
        if total > SKILL_ENV_MAX_ENTRIES * SKILL_ENV_MAX_VALUE_BYTES {
            anyhow::bail!("skill env exceeds size policy");
        }
    }
    Ok(())
}

/// POSIX identifier: `[A-Za-z_][A-Za-z0-9_]*`.
pub fn valid_skill_env_name(name: &str) -> bool {
    let mut bytes = name.bytes();
    matches!(bytes.next(), Some(byte) if byte == b'_' || byte.is_ascii_alphabetic())
        && bytes.all(|byte| byte == b'_' || byte.is_ascii_alphanumeric())
        && name.len() <= 191
}

/// Absolute path providers source before executing a command in a Space.
pub fn space_skill_env_abs_path(space_root: &str) -> String {
    let root = space_root.trim_end_matches('/');
    if root.is_empty() {
        format!("/{SKILL_ENV_FILE}")
    } else {
        format!("{root}/{SKILL_ENV_FILE}")
    }
}

/// Absolute path providers source before executing a command in a Sandbox.
pub fn sandbox_skill_env_abs_path() -> String {
    format!("/{SKILL_ENV_FILE}")
}

/// `export NAME='value'` file that login/non-login shells can source.
pub fn encode_skill_env_file(env: &BTreeMap<String, String>) -> String {
    env.iter()
        .map(|(name, value)| format!("export {name}={}\n", posix_single_quote(value)))
        .collect()
}

/// Parse the file produced by [`encode_skill_env_file`].
pub fn parse_skill_env_file(content: &str) -> BTreeMap<String, String> {
    let mut env = BTreeMap::new();
    for line in content.lines() {
        let line = line.trim();
        let Some(rest) = line.strip_prefix("export ") else {
            continue;
        };
        let Some((name, quoted)) = rest.split_once('=') else {
            continue;
        };
        if !valid_skill_env_name(name) {
            continue;
        }
        if let Some(value) = unquote_posix_single(quoted) {
            env.insert(name.to_string(), value);
        }
    }
    env
}

/// Prefix that no-ops when the skill env file is absent.
pub fn skill_env_source_prefix(env_file: &str) -> String {
    let file = posix_single_quote(env_file);
    format!("if [ -f {file} ]; then set -a; . {file}; set +a; fi; ")
}

/// `export NAME='value'; ` prefix so a later command can override a sourced
/// skill `.env` file. Invalid names are skipped; callers should validate first.
pub fn command_env_export_prefix(env: &BTreeMap<String, String>) -> String {
    env.iter()
        .filter(|(name, _)| valid_skill_env_name(name))
        .map(|(name, value)| format!("export {name}={}; ", posix_single_quote(value)))
        .collect()
}

pub fn posix_single_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', "'\\''"))
}

fn unquote_posix_single(value: &str) -> Option<String> {
    let mut chars = value.chars().peekable();
    let mut out = String::new();
    let mut in_quote = false;
    while let Some(ch) = chars.next() {
        match ch {
            '\'' => in_quote = !in_quote,
            '\\' if !in_quote => out.push(chars.next()?),
            other => out.push(other),
        }
    }
    (!in_quote).then_some(out)
}

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

    #[test]
    fn skill_env_round_trips_quotes_and_rejects_invalid_names() {
        let mut env = BTreeMap::new();
        env.insert("SKYWORKS_AGENT_PLUGIN_ROUTER".into(), "agent-xxx".into());
        env.insert("NOTE".into(), "it's a value".into());
        let encoded = encode_skill_env_file(&env);
        assert_eq!(parse_skill_env_file(&encoded), env);
        assert!(validate_skill_env(&env).is_ok());
        assert!(!valid_skill_env_name("1BAD"));
        assert!(!valid_skill_env_name("HAS-DASH"));
        assert_eq!(
            command_env_export_prefix(&env),
            "export NOTE='it'\\''s a value'; export SKYWORKS_AGENT_PLUGIN_ROUTER='agent-xxx'; "
        );
        assert!(validate_skill_env(&BTreeMap::from([("HAS-DASH".into(), "x".into())])).is_err());
        assert_eq!(
            skill_env_source_prefix("/skills/.env"),
            "if [ -f '/skills/.env' ]; then set -a; . '/skills/.env'; set +a; fi; "
        );
        assert_eq!(
            space_skill_env_abs_path("/home/user/spaces/spc_1"),
            "/home/user/spaces/spc_1/skills/.env"
        );
        assert_eq!(sandbox_skill_env_abs_path(), "/skills/.env");
    }
}

/// Install code only at a Computer-owned, Agent/version-isolated location.
pub const COMPUTER_SKILLS_PATH: &str = "/internal/v1/workspace/computers/{computerId}/skills";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct InstallComputerSkillRequest {
    #[serde(default)]
    pub space_id: Option<String>,
    pub agent_id: String,
    pub group: String,
    pub name: String,
    pub version: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct InstallComputerSkillResource {
    pub computer_id: String,
    pub agent_id: String,
    pub group: String,
    pub name: String,
    pub version: String,
    pub install_path: String,
    pub files: Vec<String>,
    pub clis: Vec<InstalledSpaceCli>,
}

/// Installation metadata contains no environment values or credentials.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SpaceSkillInstallationState {
    Preparing,
    Ready,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct SpaceSkillInstallation {
    pub group: String,
    pub name: String,
    pub version: String,
    pub state: SpaceSkillInstallationState,
    pub files: Vec<String>,
    pub clis: Vec<InstalledSpaceCli>,
    /// Accepted previous/current contents permit interrupted upgrades to resume.
    pub file_digests: BTreeMap<String, Vec<String>>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct UninstallSpaceSkillRequest {
    pub group: String,
    pub name: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct UninstallSpaceSkillResource {
    pub space_id: String,
    pub group: String,
    pub name: String,
    pub removed_paths: Vec<String>,
    pub retained_paths: Vec<String>,
    pub revision: u64,
}

pub const SPACE_SKILL_UNINSTALL_PATH: &str =
    "/internal/v1/workspace/spaces/{spaceId}/skills/uninstall";