a3s-code-core 5.2.3

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
use super::*;
use crate::trace::{InMemoryTraceSink, TraceEventKind};
use async_trait::async_trait;

struct MockTool {
    name: String,
}

#[async_trait]
impl Tool for MockTool {
    fn name(&self) -> &str {
        &self.name
    }

    fn description(&self) -> &str {
        "A mock tool for testing"
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "additionalProperties": false,
            "properties": {},
            "required": []
        })
    }

    async fn execute(&self, _args: &serde_json::Value, _ctx: &ToolContext) -> Result<ToolOutput> {
        Ok(ToolOutput::success("mock output"))
    }
}

#[test]
fn governed_argument_validation_enforces_required_types_and_unknown_fields() {
    struct ValidatedTool;

    #[async_trait]
    impl Tool for ValidatedTool {
        fn name(&self) -> &str {
            "validated"
        }

        fn description(&self) -> &str {
            "validated test tool"
        }

        fn parameters(&self) -> serde_json::Value {
            serde_json::json!({
                "type": "object",
                "additionalProperties": false,
                "properties": {
                    "count": {"type": "integer", "minimum": 1}
                },
                "required": ["count"]
            })
        }

        async fn execute(
            &self,
            _args: &serde_json::Value,
            _ctx: &ToolContext,
        ) -> Result<ToolOutput> {
            Ok(ToolOutput::success("ok"))
        }
    }

    let registry = ToolRegistry::new(std::env::temp_dir());
    registry.register(Arc::new(ValidatedTool));
    assert!(registry
        .validate_arguments("validated", &serde_json::json!({"count": 2}))
        .is_ok());
    let missing = registry
        .validate_arguments("validated", &serde_json::json!({}))
        .unwrap_err();
    assert!(missing.contains("count"));
    let unknown = registry
        .validate_arguments(
            "validated",
            &serde_json::json!({"count": 2, "surprise": true}),
        )
        .unwrap_err();
    assert!(unknown.contains("surprise"));
}

#[tokio::test]
async fn large_change_metadata_is_bounded_hashed_and_artifact_backed() {
    struct LargeChangeTool;

    #[async_trait]
    impl Tool for LargeChangeTool {
        fn name(&self) -> &str {
            "large_change"
        }

        fn description(&self) -> &str {
            "returns large before and after metadata"
        }

        fn parameters(&self) -> serde_json::Value {
            serde_json::json!({"type": "object"})
        }

        async fn execute(
            &self,
            _args: &serde_json::Value,
            _ctx: &ToolContext,
        ) -> Result<ToolOutput> {
            Ok(
                ToolOutput::success("changed").with_metadata(serde_json::json!({
                    "file_path": "large.txt",
                    "before": format!("before\n{}", "a".repeat(40 * 1024)),
                    "after": format!("after\n{}", "b".repeat(40 * 1024)),
                })),
            )
        }
    }

    let registry = ToolRegistry::new(std::env::temp_dir());
    registry.register(Arc::new(LargeChangeTool));
    let output = registry
        .execute_raw("large_change", &serde_json::json!({}))
        .await
        .unwrap()
        .unwrap();
    let metadata = output.metadata.unwrap();

    assert_eq!(metadata["change"]["compacted"], true);
    assert!(metadata["before"].as_str().unwrap().len() < 9 * 1024);
    assert!(metadata["after"].as_str().unwrap().len() < 9 * 1024);
    assert_eq!(
        metadata["change"]["before"]["sha256"]
            .as_str()
            .unwrap()
            .len(),
        64
    );
    let before_uri = metadata["change"]["before"]["artifact"]["artifact_uri"]
        .as_str()
        .unwrap();
    let artifact = registry.get_artifact(before_uri).unwrap();
    assert!(artifact.content.starts_with("before\n"));
    assert!(metadata["change"]["unified_diff"]
        .as_str()
        .is_some_and(|diff| diff.contains("--- before")));
}

#[test]
fn test_registry_register_and_get() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));

    let tool = Arc::new(MockTool {
        name: "test".to_string(),
    });
    registry.register(tool);

    assert!(registry.contains("test"));
    assert!(!registry.contains("nonexistent"));

    let retrieved = registry.get("test");
    assert!(retrieved.is_some());
    assert_eq!(retrieved.unwrap().name(), "test");
}

#[test]
fn test_registry_unregister() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));

    let tool = Arc::new(MockTool {
        name: "test".to_string(),
    });
    registry.register(tool);

    assert!(registry.contains("test"));
    assert!(registry.unregister("test"));
    assert!(!registry.contains("test"));
    assert!(!registry.unregister("test")); // Already removed
}

#[test]
fn test_registry_unregister_preserves_builtins() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));
    registry.register_builtin(Arc::new(MockTool {
        name: "read".to_string(),
    }));

    assert!(!registry.unregister("read"));
    assert!(registry.contains("read"));
}

#[test]
fn test_registry_unregister_by_prefix_preserves_builtins() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));
    registry.register_builtin(Arc::new(MockTool {
        name: "mcp__builtin".to_string(),
    }));
    registry.register(Arc::new(MockTool {
        name: "mcp__dynamic".to_string(),
    }));

    registry.unregister_by_prefix("mcp__");

    assert!(registry.contains("mcp__builtin"));
    assert!(!registry.contains("mcp__dynamic"));
}

#[test]
fn concurrent_owned_registration_cannot_overwrite_builtin() {
    for iteration in 0..32 {
        let registry = Arc::new(ToolRegistry::new(PathBuf::from("/tmp")));
        let name = format!("atomic_builtin_{iteration}");
        let builtin: Arc<dyn Tool> = Arc::new(MockTool { name: name.clone() });
        let dynamic: Arc<dyn Tool> = Arc::new(MockTool { name: name.clone() });
        let barrier = Arc::new(std::sync::Barrier::new(3));

        let builtin_registry = Arc::clone(&registry);
        let builtin_tool = Arc::clone(&builtin);
        let builtin_barrier = Arc::clone(&barrier);
        let builtin_thread = std::thread::spawn(move || {
            builtin_barrier.wait();
            builtin_registry.register_builtin(builtin_tool);
        });

        let dynamic_registry = Arc::clone(&registry);
        let dynamic_barrier = Arc::clone(&barrier);
        let dynamic_thread = std::thread::spawn(move || {
            dynamic_barrier.wait();
            dynamic_registry.register_with_shadow(dynamic);
        });

        barrier.wait();
        builtin_thread.join().unwrap();
        dynamic_thread.join().unwrap();

        let current = registry.get(&name).unwrap();
        assert!(Arc::ptr_eq(&current, &builtin));
        assert!(!registry.unregister(&name));
    }
}

#[test]
fn test_registry_definitions() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));

    registry.register(Arc::new(MockTool {
        name: "tool2".to_string(),
    }));
    registry.register(Arc::new(MockTool {
        name: "tool1".to_string(),
    }));

    let definitions = registry.definitions();
    assert_eq!(definitions.len(), 2);
    let names: Vec<&str> = definitions
        .iter()
        .map(|definition| definition.name.as_str())
        .collect();
    assert_eq!(names, vec!["tool1", "tool2"]);
}

#[tokio::test]
async fn test_registry_execute() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));

    registry.register(Arc::new(MockTool {
        name: "test".to_string(),
    }));

    let result = registry
        .execute("test", &serde_json::json!({}))
        .await
        .unwrap();
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.output, "mock output");
}

#[tokio::test]
async fn test_registry_execute_unknown() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));

    let result = registry
        .execute("unknown", &serde_json::json!({}))
        .await
        .unwrap();
    assert_eq!(result.exit_code, 1);
    assert!(result.output.contains("Unknown tool"));
}

#[tokio::test]
async fn test_registry_execute_with_context_success() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));
    let ctx = ToolContext::new(PathBuf::from("/tmp"));
    let trace_sink = InMemoryTraceSink::default();
    registry.set_trace_sink(Arc::new(trace_sink.clone()));

    registry.register(Arc::new(MockTool {
        name: "my_tool".to_string(),
    }));

    let result = registry
        .execute_with_context("my_tool", &serde_json::json!({}), &ctx)
        .await
        .unwrap();
    assert_eq!(result.name, "my_tool");
    assert_eq!(result.exit_code, 0);
    assert_eq!(result.output, "mock output");

    let events = trace_sink.events();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].kind, TraceEventKind::ToolExecution);
    assert_eq!(events[0].name, "my_tool");
    assert!(events[0].success);
    assert_eq!(events[0].output_bytes, "mock output".len());
}

#[tokio::test]
async fn test_registry_execute_with_context_unknown_tool() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));
    let ctx = ToolContext::new(PathBuf::from("/tmp"));

    let result = registry
        .execute_with_context("nonexistent", &serde_json::json!({}), &ctx)
        .await
        .unwrap();
    assert_eq!(result.exit_code, 1);
    assert!(result.output.contains("Unknown tool: nonexistent"));
}

struct FailingTool;

#[async_trait]
impl Tool for FailingTool {
    fn name(&self) -> &str {
        "failing"
    }

    fn description(&self) -> &str {
        "A tool that returns failure"
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "additionalProperties": false,
            "properties": {},
            "required": []
        })
    }

    async fn execute(&self, _args: &serde_json::Value, _ctx: &ToolContext) -> Result<ToolOutput> {
        Ok(ToolOutput::error("something went wrong"))
    }
}

#[tokio::test]
async fn test_registry_execute_failing_tool() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));
    registry.register(Arc::new(FailingTool));

    let result = registry
        .execute("failing", &serde_json::json!({}))
        .await
        .unwrap();
    assert_eq!(result.exit_code, 1);
    assert_eq!(result.output, "something went wrong");
}

struct LargeOutputTool;

#[async_trait]
impl Tool for LargeOutputTool {
    fn name(&self) -> &str {
        "large_output"
    }

    fn description(&self) -> &str {
        "A tool that returns more than the maximum output size"
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "additionalProperties": false,
            "properties": {},
            "required": []
        })
    }

    async fn execute(&self, _args: &serde_json::Value, _ctx: &ToolContext) -> Result<ToolOutput> {
        Ok(ToolOutput::success(
            "x".repeat(super::super::MAX_OUTPUT_SIZE + 1),
        ))
    }
}

#[tokio::test]
async fn test_registry_truncates_large_tool_output() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));
    let trace_sink = InMemoryTraceSink::default();
    registry.set_trace_sink(Arc::new(trace_sink.clone()));
    registry.register(Arc::new(LargeOutputTool));

    let result = registry
        .execute("large_output", &serde_json::json!({}))
        .await
        .unwrap();

    assert_eq!(result.exit_code, 0);
    assert!(result.output.contains("[tool output truncated:"));
    assert!(result
        .output
        .contains("Full output artifact: a3s://tool-output/large_output/"));
    assert!(result.output.len() < super::super::MAX_OUTPUT_SIZE + 512);
    let metadata = result.metadata.expect("artifact metadata");
    assert_eq!(
        metadata["artifact"]["original_bytes"],
        serde_json::json!(super::super::MAX_OUTPUT_SIZE + 1)
    );
    assert_eq!(
        metadata["artifact"]["shown_bytes"],
        serde_json::json!(super::super::MAX_OUTPUT_SIZE)
    );
    assert!(metadata["artifact"]["artifact_id"]
        .as_str()
        .unwrap()
        .starts_with("tool-output:large_output:"));
    assert!(metadata["artifact"]["artifact_uri"]
        .as_str()
        .unwrap()
        .starts_with("a3s://tool-output/large_output/"));

    let artifact_uri = metadata["artifact"]["artifact_uri"].as_str().unwrap();
    let artifact = registry
        .get_artifact(artifact_uri)
        .expect("full output artifact");
    assert_eq!(artifact.tool_name, "large_output");
    assert_eq!(artifact.original_bytes, super::super::MAX_OUTPUT_SIZE + 1);
    assert_eq!(artifact.shown_bytes, super::super::MAX_OUTPUT_SIZE);
    assert_eq!(
        artifact.content,
        "x".repeat(super::super::MAX_OUTPUT_SIZE + 1)
    );

    let events = trace_sink.events();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].artifact_uris, vec![artifact_uri]);
}

#[tokio::test]
async fn test_registry_execute_raw_success() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));
    registry.register(Arc::new(MockTool {
        name: "raw_test".to_string(),
    }));

    let output = registry
        .execute_raw("raw_test", &serde_json::json!({}))
        .await
        .unwrap();
    assert!(output.is_some());
    let output = output.unwrap();
    assert!(output.success);
    assert_eq!(output.content, "mock output");
}

#[tokio::test]
async fn test_registry_execute_raw_stores_truncated_artifact() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));
    registry.register(Arc::new(LargeOutputTool));

    let output = registry
        .execute_raw("large_output", &serde_json::json!({}))
        .await
        .unwrap()
        .expect("raw output");

    assert!(output.content.contains("[tool output truncated:"));
    let metadata = output.metadata.expect("artifact metadata");
    let artifact_uri = metadata["artifact"]["artifact_uri"].as_str().unwrap();
    let artifact = registry
        .get_artifact(artifact_uri)
        .expect("full output artifact");
    assert_eq!(artifact.tool_name, "large_output");
    assert_eq!(artifact.content.len(), super::super::MAX_OUTPUT_SIZE + 1);
}

#[tokio::test]
async fn test_registry_execute_raw_unknown() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));

    let output = registry
        .execute_raw("missing", &serde_json::json!({}))
        .await
        .unwrap();
    assert!(output.is_none());
}

#[test]
fn test_registry_list() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));
    registry.register(Arc::new(MockTool {
        name: "beta".to_string(),
    }));
    registry.register(Arc::new(MockTool {
        name: "alpha".to_string(),
    }));

    let names = registry.list();
    assert_eq!(names, vec!["alpha".to_string(), "beta".to_string()]);
}

#[test]
fn test_registry_len_and_is_empty() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));
    assert!(registry.is_empty());
    assert_eq!(registry.len(), 0);

    registry.register(Arc::new(MockTool {
        name: "t".to_string(),
    }));
    assert!(!registry.is_empty());
    assert_eq!(registry.len(), 1);
}

#[test]
fn test_registry_replace_tool() {
    let registry = ToolRegistry::new(PathBuf::from("/tmp"));
    registry.register(Arc::new(MockTool {
        name: "dup".to_string(),
    }));
    registry.register(Arc::new(MockTool {
        name: "dup".to_string(),
    }));
    // Should still have only 1 tool (replaced)
    assert_eq!(registry.len(), 1);
}