agent-workspace-contract 0.5.1

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
use super::*;

pub const WORKSPACE_SERVICE_NAME: &str = "agent-workspace";
/// Resource-scoped file API used by leftover managed callers. `filePath` is an axum
/// catch-all and therefore may contain workspace-relative `/` separators.
pub const WORKSPACE_RESOURCE_FILE_PATH: &str =
    "/internal/v1/workspaces/{workspaceId}/files/{*filePath}";
pub const WORKSPACE_RESOURCE_SEARCH_PATH: &str =
    "/internal/v1/workspaces/{workspaceId}/files:search";

pub const WORKSPACE_MAX_FILE_BYTES: usize = 16 * 1024 * 1024;
pub const WORKSPACE_MAX_RESULTS: usize = 10_000;
pub const WORKSPACE_MAX_SEARCH_OUTPUT_BYTES: usize = 4 * 1024 * 1024;
pub const WORKSPACE_MAX_COMMAND_OUTPUT_BYTES: usize = 1024 * 1024;
pub const WORKSPACE_MAX_COMMAND_BYTES: usize = 64 * 1024;
pub const WORKSPACE_MAX_PATH_BYTES: usize = 4096;

/// Return the capability required by both the public Gateway alias and the
/// internal Workspace service route. Keeping this decision in the contract
/// prevents the Gateway-issued downstream credential from drifting away from
/// the capability independently enforced by the Workspace server.
#[allow(clippy::if_same_then_else)] // Branch order preserves more-specific file/snapshot capabilities.
pub fn required_workspace_capability(path: &str, method: &str) -> &'static str {
    let path = strip_environment_api_prefix(path);
    if method == "GET"
        && (path == "/delegations"
            || path.ends_with("/binding")
            || path.ends_with("/grants")
            || path.ends_with("/sessions")
            || path.ends_with("/leases")
            || path.ends_with("/change-sets"))
    {
        "workspace:manage"
    } else if path.starts_with("/spaces/")
        && path.contains("/files/")
        && matches!(method, "PUT" | "DELETE")
    {
        "files:write"
    } else if path.starts_with("/spaces/") && path.contains("/files/") {
        "files:read"
    } else if path.contains("/snapshots") || path.starts_with("/templates") {
        "snapshot:manage"
    } else if path.contains("/commands") || path.ends_with("/exec") {
        "commands:exec"
    } else if method != "GET"
        && (path.starts_with("/computers")
            || path.starts_with("/spaces")
            || path.starts_with("/space-")
            || path.starts_with("/sandboxes")
            || path.starts_with("/delegations")
            || path.starts_with("/templates"))
    {
        "workspace:manage"
    } else if (path.contains("/workspace-operations/") && method != "GET")
        || path == "/workspaces" && method == "POST"
        || path.starts_with("/workspaces/")
            && (method == "DELETE"
                || path.ends_with("/suspend")
                || path.ends_with("/resume")
                || path.ends_with("/reconcile")
                || path.ends_with("/lease"))
    {
        "workspace:manage"
    } else if path.contains("/uploads")
        || (path.contains("/files/") && matches!(method, "PUT" | "DELETE"))
    {
        "files:write"
    } else if path.ends_with("/clone") || path.ends_with("/migrate") {
        "snapshot:manage"
    } else if path.ends_with("/lease") || path.ends_with("/suspend") || path.ends_with("/resume") {
        "workspace:manage"
    } else if path.ends_with("/port-url") || path.contains("/previews") {
        "preview:manage"
    } else if (path.contains("change-sets") && method != "GET")
        || path.contains("write-file")
        || path.contains("create-dir")
        || path.contains("remove-file")
    {
        "files:write"
    } else if path == "/skills:search" {
        "files:read"
    } else {
        "files:read"
    }
}

/// Strip `/internal/v1` or `/v1`, then the Environment domain prefix `/workspace`
/// when it is a full path segment. `/workspaces` (plural managed API) is left intact.
pub fn strip_environment_api_prefix(path: &str) -> &str {
    let path = path
        .strip_prefix("/internal/v1")
        .or_else(|| path.strip_prefix("/v1"))
        .unwrap_or(path);
    match path.strip_prefix("/workspace") {
        Some(rest) if rest.is_empty() || rest.starts_with('/') => {
            if rest.is_empty() {
                "/"
            } else {
                rest
            }
        }
        _ => path,
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceCapabilities {
    pub schema_version: String,
    pub files: bool,
    pub search: bool,
    pub commands: bool,
    pub previews: bool,
    pub atomic_writes: bool,
    pub compare_and_swap: bool,
    pub max_file_bytes: usize,
    pub max_results: usize,
    pub max_search_output_bytes: usize,
    pub max_command_output_bytes: usize,
}

impl Default for WorkspaceCapabilities {
    fn default() -> Self {
        Self {
            schema_version: "v1".into(),
            files: true,
            search: true,
            commands: false,
            previews: false,
            atomic_writes: false,
            compare_and_swap: false,
            max_file_bytes: WORKSPACE_MAX_FILE_BYTES,
            max_results: WORKSPACE_MAX_RESULTS,
            max_search_output_bytes: WORKSPACE_MAX_SEARCH_OUTPUT_BYTES,
            max_command_output_bytes: WORKSPACE_MAX_COMMAND_OUTPUT_BYTES,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceApiError {
    pub status: u16,
    pub code: String,
    #[serde(default = "default_error_category")]
    pub category: String,
    pub message: String,
    pub retryable: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,
}

fn default_error_category() -> String {
    "internal".into()
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PathRequest {
    pub path: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RemoveFileRequest {
    pub path: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub if_match: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReadFileTailRequest {
    pub path: String,
    #[serde(default = "default_read_tail_bytes")]
    pub max_bytes: usize,
}

fn default_read_tail_bytes() -> usize {
    4096
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WriteFileRequest {
    pub path: String,
    pub content: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub if_match: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WriteFileBytesRequest {
    pub path: String,
    pub content_base64: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub if_match: Option<String>,
}

/// Body for the resource-scoped `PUT .../files/{path}` API. The path belongs
/// to the URL so it cannot disagree with a second body field.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct PutWorkspaceFileRequest {
    pub content_base64: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub if_match: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkspaceSearchKind {
    Walk,
    Find,
    Grep,
}

/// One bounded typed search entry point. Fields that do not apply to the
/// selected kind are rejected by the service rather than guessed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct WorkspaceSearchRequest {
    pub kind: WorkspaceSearchKind,
    #[serde(default)]
    pub path: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub include: Option<String>,
    #[serde(default = "default_search_depth")]
    pub max_depth: usize,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
    #[serde(default = "default_search_page_limit")]
    pub limit: usize,
}

fn default_search_depth() -> usize {
    32
}

fn default_search_page_limit() -> usize {
    100
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceSearchResponse {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub paths: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub matches: Vec<GrepMatch>,
    pub truncated: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListDirRequest {
    pub path: String,
    #[serde(default)]
    pub include_hidden: bool,
    #[serde(default)]
    pub include_ignored: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WalkTreeRequest {
    pub path: String,
    pub max_depth: usize,
    #[serde(default)]
    pub include_hidden: bool,
    #[serde(default)]
    pub include_ignored: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FindFilesRequest {
    pub pattern: String,
    pub path: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GrepRequest {
    pub pattern: String,
    pub path: String,
    #[serde(default)]
    pub include: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExecRequest {
    pub command: String,
    #[serde(default)]
    pub cwd: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PortUrlRequest {
    pub port: u16,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ContentResponse {
    pub content: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revision: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BytesResponse {
    pub content_base64: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revision: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AckResponse {
    pub ok: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revision: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExistsResponse {
    pub exists: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IsDirResponse {
    pub is_dir: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EntriesResponse {
    pub entries: Vec<DirEntry>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PathsResponse {
    pub paths: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GrepResponse {
    pub matches: Vec<GrepMatch>,
}

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

    #[test]
    fn wire_contract_uses_camel_case_and_keeps_legacy_optional_fields() {
        let request = WriteFileRequest {
            path: "src/lib.rs".into(),
            content: "fn main() {}".into(),
            if_match: Some("sha256:abc".into()),
        };
        assert_eq!(
            serde_json::to_string(&request).unwrap(),
            r#"{"path":"src/lib.rs","content":"fn main() {}","ifMatch":"sha256:abc"}"#
        );
        let legacy: AckResponse = serde_json::from_str(r#"{"ok":true}"#).unwrap();
        assert_eq!(legacy.revision, None);
    }

    #[test]
    fn public_and_internal_workspace_routes_share_one_capability_contract() {
        let cases = [
            ("POST", "/computers", "workspace:manage"),
            ("GET", "/computers", "files:read"),
            ("POST", "/spaces/s/files/read", "files:read"),
            ("POST", "/spaces/s/files/list", "files:read"),
            ("PUT", "/spaces/s/files/a", "files:write"),
            ("DELETE", "/spaces/s/files/a", "files:write"),
            ("POST", "/spaces/s/change-sets", "workspace:manage"),
            ("POST", "/snapshots", "snapshot:manage"),
            ("GET", "/templates", "snapshot:manage"),
            ("POST", "/sandboxes", "workspace:manage"),
            ("POST", "/sandboxes/s/skills", "workspace:manage"),
            ("GET", "/skills:search", "files:read"),
            ("GET", "/delegations", "workspace:manage"),
            ("POST", "/computers/c/commands", "commands:exec"),
        ];
        for (method, suffix, expected) in cases {
            assert_eq!(
                required_workspace_capability(&format!("/v1{suffix}"), method),
                expected
            );
            assert_eq!(
                required_workspace_capability(&format!("/internal/v1{suffix}"), method),
                expected
            );
            assert_eq!(
                required_workspace_capability(&format!("/v1/workspace{suffix}"), method),
                expected,
                "{method} /v1/workspace{suffix}"
            );
            assert_eq!(
                required_workspace_capability(&format!("/internal/v1/workspace{suffix}"), method),
                expected,
                "{method} /internal/v1/workspace{suffix}"
            );
        }
    }
}