a3s-code-core 9.0.0

A3S Code Core - Embeddable AI agent library with tool execution
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
use super::*;
use crate::config::{HeadlessConfig, SearchConfig};
use crate::tools::types::{Tool, ToolOutputKind};
use crate::workspace::{LocalWorkspaceAccessPolicy, ManifestWorkspaceBackend, WorkspaceServices};
use serde_json::json;
use std::collections::HashMap;
use std::sync::Arc;
use tempfile::TempDir;
use tokio::sync::Notify;
use wiremock::matchers::method;
use wiremock::{Mock, MockServer, Request, ResponseTemplate};

fn context(workspace: &TempDir, server: &MockServer) -> ToolContext {
    ToolContext::new(workspace.path().to_path_buf())
        .with_session_id("download-test")
        .with_search_config(SearchConfig {
            timeout: 30,
            cascade_order: None,
            health: None,
            engines: HashMap::new(),
            headless: Some(HeadlessConfig {
                proxy_url: Some(server.uri()),
                ..HeadlessConfig::default()
            }),
        })
}

async fn execute(workspace: &TempDir, server: &MockServer, args: serde_json::Value) -> ToolOutput {
    DownloadTool
        .execute(&args, &context(workspace, server))
        .await
        .expect("download tool execution")
}

fn request_range(request: &Request) -> Option<(u64, u64)> {
    let value = request.headers.get("range")?.to_str().ok()?;
    let value = value.strip_prefix("bytes=")?;
    let (start, end) = value.split_once('-')?;
    Some((start.parse().ok()?, end.parse().ok()?))
}

fn range_response(payload: &[u8], start: u64, end: u64) -> ResponseTemplate {
    let total = payload.len() as u64;
    ResponseTemplate::new(206)
        .insert_header("content-range", format!("bytes {start}-{end}/{total}"))
        .insert_header("content-length", (end - start + 1).to_string())
        .insert_header("etag", "\"download-v1\"")
        .set_body_bytes(payload[start as usize..=end as usize].to_vec())
}

fn deterministic_payload(size: usize) -> Vec<u8> {
    (0..size).map(|index| (index % 251) as u8).collect()
}

fn assert_no_download_temps(path: &Path) {
    if !path.exists() {
        return;
    }
    for entry in std::fs::read_dir(path).expect("read test workspace") {
        let entry = entry.expect("workspace entry");
        let file_type = entry.file_type().expect("workspace file type");
        if file_type.is_dir() {
            assert_no_download_temps(&entry.path());
        } else {
            assert!(
                !entry
                    .file_name()
                    .to_string_lossy()
                    .starts_with(".a3s-download-"),
                "temporary download leaked at {}",
                entry.path().display()
            );
        }
    }
}

#[test]
fn definition_is_bounded_and_binary_safe() {
    let parameters = DownloadTool.parameters();
    assert_eq!(parameters["additionalProperties"], false);
    assert_eq!(parameters["required"], json!(["url"]));
    assert_eq!(parameters["properties"]["connections"]["maximum"], 4);
    assert_eq!(
        parameters["properties"]["expected_sha256"]["pattern"],
        "^[A-Fa-f0-9]{64}$"
    );

    let capabilities = DownloadTool.capabilities(&json!({}));
    assert!(!capabilities.read_only);
    assert!(!capabilities.idempotent);
    assert!(capabilities.cancellation_safe);
    assert_eq!(capabilities.max_parallelism, 1);
    assert_eq!(capabilities.output_kind, ToolOutputKind::Mixed);
}

#[tokio::test]
async fn private_literal_urls_are_rejected_before_network_access() {
    let workspace = tempfile::tempdir().unwrap();
    let output = DownloadTool
        .execute(
            &json!({"url": "http://127.0.0.1/private.bin"}),
            &ToolContext::new(workspace.path().to_path_buf()),
        )
        .await
        .unwrap();

    assert!(!output.success);
    assert!(output.content.contains("non-public"));
    assert!(matches!(
        output.error_kind,
        Some(ToolErrorKind::InvalidArgument { .. })
    ));
    assert!(std::fs::read_dir(workspace.path())
        .unwrap()
        .next()
        .is_none());
}

#[tokio::test]
async fn download_without_a_session_does_not_write() {
    let workspace = tempfile::tempdir().unwrap();
    let output = DownloadTool
        .execute(
            &json!({
                "url": "http://example.test/payload.bin",
                "file_path": "payload.bin"
            }),
            &ToolContext::new(workspace.path().to_path_buf()),
        )
        .await
        .unwrap();

    assert!(!output.success);
    assert!(output.content.contains("session id"));
    assert!(!workspace.path().join("payload.bin").exists());
}

#[tokio::test]
async fn sequential_download_is_binary_exact_and_infers_safe_filename() {
    let server = MockServer::start().await;
    let workspace = tempfile::tempdir().unwrap();
    let payload = vec![0, 1, 2, 0, 255, 128, b'\n'];
    Mock::given(method("GET"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header(
                    "content-disposition",
                    "attachment; ignored; filename*=UTF-8''payload%20%E4%B8%AD.bin",
                )
                .insert_header("content-type", "application/octet-stream")
                .set_body_bytes(payload.clone()),
        )
        .mount(&server)
        .await;

    let output = execute(
        &workspace,
        &server,
        json!({"url": "http://example.test/file?signature=top-secret"}),
    )
    .await;

    assert!(output.success, "{}", output.content);
    assert_eq!(
        std::fs::read(workspace.path().join("payload 中.bin")).unwrap(),
        payload
    );
    let metadata = output.metadata.unwrap();
    assert_eq!(metadata["file_path"], "payload 中.bin");
    assert_eq!(metadata["strategy"], "sequential");
    assert_eq!(metadata["bytes"], 7);
    assert_eq!(
        metadata["source_anchors"],
        json!(["http://example.test/file"])
    );
    assert_no_download_temps(workspace.path());
}

#[tokio::test]
async fn parallel_ranges_reconstruct_the_exact_file() {
    let server = MockServer::start().await;
    let workspace = tempfile::tempdir().unwrap();
    let payload = Arc::new(deterministic_payload(7 * 1024 * 1024 + 123));
    let responder_payload = Arc::clone(&payload);
    Mock::given(method("GET"))
        .respond_with(move |request: &Request| {
            let (start, end) = request_range(request).expect("range request");
            range_response(&responder_payload, start, end)
        })
        .mount(&server)
        .await;

    let output = execute(
        &workspace,
        &server,
        json!({
            "url": "http://example.test/release.bin",
            "file_path": "artifacts/release.bin",
            "connections": 3
        }),
    )
    .await;

    assert!(output.success, "{}", output.content);
    assert_eq!(
        std::fs::read(workspace.path().join("artifacts/release.bin")).unwrap(),
        payload.as_slice()
    );
    let metadata = output.metadata.unwrap();
    assert_eq!(metadata["strategy"], "parallel_range");
    assert_eq!(metadata["connections"], 3);
    assert_eq!(metadata["range_supported"], true);

    let requests = server.received_requests().await.unwrap();
    assert!(requests.len() >= 4);
    assert!(requests.iter().all(|request| {
        request
            .headers
            .get("accept-encoding")
            .and_then(|value| value.to_str().ok())
            == Some("identity")
    }));
    assert!(requests
        .iter()
        .filter(|request| request_range(request).is_some_and(|(_, end)| end > 0))
        .all(|request| request.headers.get("if-range").is_some()));
    assert_no_download_temps(workspace.path());
}

#[tokio::test]
async fn range_support_without_a_validator_uses_one_coherent_response() {
    let server = MockServer::start().await;
    let workspace = tempfile::tempdir().unwrap();
    let payload = Arc::new(deterministic_payload(5 * 1024 * 1024 + 9));
    let responder_payload = Arc::clone(&payload);
    Mock::given(method("GET"))
        .respond_with(move |request: &Request| match request_range(request) {
            Some((0, 0)) => {
                let total = responder_payload.len();
                ResponseTemplate::new(206)
                    .insert_header("content-range", format!("bytes 0-0/{total}"))
                    .set_body_bytes(vec![responder_payload[0]])
            }
            Some(_) => panic!("unvalidated parallel ranges must not be requested"),
            None => ResponseTemplate::new(200).set_body_bytes((*responder_payload).clone()),
        })
        .mount(&server)
        .await;

    let output = execute(
        &workspace,
        &server,
        json!({
            "url": "http://example.test/coherent.bin",
            "file_path": "coherent.bin",
            "connections": 4
        }),
    )
    .await;

    assert!(output.success, "{}", output.content);
    assert_eq!(
        std::fs::read(workspace.path().join("coherent.bin")).unwrap(),
        payload.as_slice()
    );
    let metadata = output.metadata.unwrap();
    assert_eq!(metadata["strategy"], "sequential");
    assert_eq!(metadata["connections"], 1);
    assert_eq!(server.received_requests().await.unwrap().len(), 2);
}

#[tokio::test]
async fn invalid_range_responses_fall_back_to_a_full_download() {
    let server = MockServer::start().await;
    let workspace = tempfile::tempdir().unwrap();
    let payload = Arc::new(deterministic_payload(4 * 1024 * 1024 + 17));
    let responder_payload = Arc::clone(&payload);
    Mock::given(method("GET"))
        .respond_with(move |request: &Request| match request_range(request) {
            Some((0, 0)) => range_response(&responder_payload, 0, 0),
            Some((start, end)) => ResponseTemplate::new(206)
                .insert_header(
                    "content-range",
                    format!("bytes {}-{end}/{}", start + 1, responder_payload.len()),
                )
                .set_body_bytes(responder_payload[start as usize..=end as usize].to_vec()),
            None => ResponseTemplate::new(200).set_body_bytes((*responder_payload).clone()),
        })
        .mount(&server)
        .await;

    let output = execute(
        &workspace,
        &server,
        json!({
            "url": "http://example.test/fallback.bin",
            "file_path": "fallback.bin",
            "connections": 2
        }),
    )
    .await;

    assert!(output.success, "{}", output.content);
    assert_eq!(
        std::fs::read(workspace.path().join("fallback.bin")).unwrap(),
        payload.as_slice()
    );
    assert_eq!(output.metadata.unwrap()["strategy"], "sequential_fallback");
    assert_no_download_temps(workspace.path());
}

#[tokio::test]
async fn max_bytes_rejects_before_creating_a_temporary_file() {
    let server = MockServer::start().await;
    let workspace = tempfile::tempdir().unwrap();
    Mock::given(method("GET"))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(vec![42; 32]))
        .mount(&server)
        .await;

    let output = execute(
        &workspace,
        &server,
        json!({
            "url": "http://example.test/too-large.bin",
            "file_path": "too-large.bin",
            "max_bytes": 8
        }),
    )
    .await;

    assert!(!output.success);
    assert!(output.content.contains("exceeds max_bytes"));
    assert!(matches!(
        output.error_kind,
        Some(ToolErrorKind::InvalidArgument { .. })
    ));
    assert!(!workspace.path().join("too-large.bin").exists());
    assert_no_download_temps(workspace.path());
    assert!(
        crate::external_observation::claim_bound_write(
            Some("download-other"),
            workspace.path(),
            "too-large.bin",
        )
        .is_ok(),
        "a download that did not land must not own the destination"
    );
    crate::external_observation::release_session("download-test");
    crate::external_observation::release_session("download-other");
}

#[tokio::test]
async fn checksum_failure_preserves_an_existing_destination() {
    let server = MockServer::start().await;
    let workspace = tempfile::tempdir().unwrap();
    std::fs::write(workspace.path().join("existing.bin"), b"original").unwrap();
    Mock::given(method("GET"))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(b"replacement".to_vec()))
        .mount(&server)
        .await;

    let output = execute(
        &workspace,
        &server,
        json!({
            "url": "http://example.test/existing.bin",
            "file_path": "existing.bin",
            "overwrite": true,
            "expected_sha256": "0000000000000000000000000000000000000000000000000000000000000000"
        }),
    )
    .await;

    assert!(!output.success);
    assert!(output.content.contains("SHA-256 mismatch"));
    assert_eq!(
        std::fs::read(workspace.path().join("existing.bin")).unwrap(),
        b"original"
    );
    assert_no_download_temps(workspace.path());
    assert!(
        crate::external_observation::claim_bound_write(
            Some("download-other"),
            workspace.path(),
            "existing.bin",
        )
        .is_ok(),
        "a checksum mismatch must not own a destination it did not change"
    );
    crate::external_observation::release_session("download-test");
    crate::external_observation::release_session("download-other");
}

fn credential_context(workspace: &TempDir) -> ToolContext {
    let services = WorkspaceServices::local_with_manifest_backend(
        ManifestWorkspaceBackend::new_with_access_policy(
            workspace.path(),
            LocalWorkspaceAccessPolicy::CredentialBoundary,
        ),
    );
    ToolContext::new(workspace.path().to_path_buf())
        .with_session_id("download-boundary")
        .with_workspace_services(services)
}

#[tokio::test]
async fn credential_boundary_download_does_not_overwrite_a_credential_file() {
    let workspace = tempfile::tempdir().unwrap();
    std::fs::write(
        workspace.path().join(".env"),
        "TOKEN=download-secret-5b22\n",
    )
    .unwrap();

    let output = DownloadTool
        .execute(
            &json!({
                "url": "http://example.test/env",
                "file_path": ".env",
                "overwrite": true
            }),
            &credential_context(&workspace),
        )
        .await
        .unwrap();

    assert!(!output.success);
    assert!(
        output.content.contains("credential boundary"),
        "{}",
        output.content
    );
    assert_eq!(
        std::fs::read_to_string(workspace.path().join(".env")).unwrap(),
        "TOKEN=download-secret-5b22\n"
    );
}

#[cfg(any(unix, windows))]
#[tokio::test]
async fn credential_boundary_download_does_not_replace_a_source_hardlink() {
    let workspace = tempfile::tempdir().unwrap();
    let source = workspace.path().join("source.bin");
    let alias = workspace.path().join("alias.bin");
    std::fs::write(&source, b"download-hardlink-token-9d04").unwrap();
    std::fs::hard_link(&source, &alias).unwrap();

    let output = DownloadTool
        .execute(
            &json!({
                "url": "http://example.test/alias.bin",
                "file_path": "alias.bin",
                "overwrite": true
            }),
            &credential_context(&workspace),
        )
        .await
        .unwrap();

    assert!(!output.success);
    assert!(
        output.content.contains("credential boundary"),
        "{}",
        output.content
    );
    assert_eq!(
        std::fs::read(&source).unwrap(),
        b"download-hardlink-token-9d04"
    );
    assert_eq!(
        std::fs::read(&alias).unwrap(),
        b"download-hardlink-token-9d04"
    );
}

#[tokio::test]
async fn credential_boundary_download_still_writes_an_ordinary_file() {
    let server = MockServer::start().await;
    let workspace = tempfile::tempdir().unwrap();
    let payload = b"ordinary download".to_vec();
    Mock::given(method("GET"))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(payload.clone()))
        .mount(&server)
        .await;
    let ctx = credential_context(&workspace).with_search_config(SearchConfig {
        timeout: 30,
        cascade_order: None,
        health: None,
        engines: HashMap::new(),
        headless: Some(HeadlessConfig {
            proxy_url: Some(server.uri()),
            ..HeadlessConfig::default()
        }),
    });

    let output = DownloadTool
        .execute(
            &json!({
                "url": "http://example.test/notes.bin",
                "file_path": "notes.bin"
            }),
            &ctx,
        )
        .await
        .unwrap();

    assert!(output.success, "{}", output.content);
    assert_eq!(
        std::fs::read(workspace.path().join("notes.bin")).unwrap(),
        payload
    );
    assert_no_download_temps(workspace.path());
}

#[tokio::test]
async fn verified_overwrite_replaces_the_destination_after_validation() {
    let server = MockServer::start().await;
    let workspace = tempfile::tempdir().unwrap();
    let payload = b"verified replacement".to_vec();
    let expected = format!(
        "{:x}",
        <sha2::Sha256 as sha2::Digest>::digest(payload.as_slice())
    );
    std::fs::write(workspace.path().join("existing.bin"), b"original").unwrap();
    Mock::given(method("GET"))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(payload.clone()))
        .mount(&server)
        .await;

    let output = execute(
        &workspace,
        &server,
        json!({
            "url": "http://example.test/existing.bin",
            "file_path": "existing.bin",
            "overwrite": true,
            "expected_sha256": expected
        }),
    )
    .await;

    assert!(output.success, "{}", output.content);
    assert_eq!(
        std::fs::read(workspace.path().join("existing.bin")).unwrap(),
        payload
    );
    let metadata = output.metadata.unwrap();
    assert_eq!(metadata["overwritten"], true);
    assert_eq!(metadata["sha256"], expected);
    assert_no_download_temps(workspace.path());
}

#[tokio::test]
async fn cancellation_removes_the_partial_file() {
    let server = MockServer::start().await;
    let workspace = tempfile::tempdir().unwrap();
    let started = Arc::new(Notify::new());
    let responder_started = Arc::clone(&started);
    let payload = Arc::new(vec![7_u8; 1024]);
    let responder_payload = Arc::clone(&payload);
    Mock::given(method("GET"))
        .respond_with(move |request: &Request| match request_range(request) {
            Some((0, 0)) => range_response(&responder_payload, 0, 0),
            Some(_) => unreachable!("one connection must use a full request"),
            None => {
                responder_started.notify_one();
                ResponseTemplate::new(200)
                    .set_delay(Duration::from_secs(5))
                    .set_body_bytes((*responder_payload).clone())
            }
        })
        .mount(&server)
        .await;

    let cancellation = CancellationToken::new();
    let ctx = context(&workspace, &server).with_cancellation(cancellation.clone());
    let task = tokio::spawn(async move {
        DownloadTool
            .execute(
                &json!({
                    "url": "http://example.test/cancel.bin",
                    "file_path": "cancel.bin",
                    "connections": 1
                }),
                &ctx,
            )
            .await
            .unwrap()
    });
    tokio::time::timeout(Duration::from_secs(2), started.notified())
        .await
        .expect("full request started");
    cancellation.cancel();
    let output = tokio::time::timeout(Duration::from_secs(2), task)
        .await
        .expect("download cancelled promptly")
        .unwrap();

    assert!(!output.success);
    assert!(matches!(
        output.error_kind,
        Some(ToolErrorKind::Cancelled { .. })
    ));
    assert!(!workspace.path().join("cancel.bin").exists());
    assert_no_download_temps(workspace.path());
}