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

#[tokio::test]
async fn test_from_config() {
    let agent = Agent::from_config(test_config()).await;
    assert!(agent.is_ok());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn agent_scheduler_prioritizes_interactive_work_across_sessions() {
    let workspace = tempfile::tempdir().unwrap();
    let (started_tx, mut started_rx) = tokio::sync::mpsc::unbounded_channel();
    let release = Arc::new(tokio::sync::Semaphore::new(0));
    let client = Arc::new(TaskSchedulerProbeClient {
        started: started_tx,
        release: Arc::clone(&release),
    });
    let mut config = test_config();
    config.task_scheduler = crate::task_scheduler::TaskSchedulerConfig {
        max_active: 1,
        aging_interval_ms: 60_000,
    };
    config.memory = Some(crate::memory::MemoryConfig {
        llm_extraction: false,
        ..Default::default()
    });
    let agent = Agent::from_config(config).await.unwrap();

    let make_session = |id: &str, priority| {
        SessionOptions::new()
            .with_session_id(id)
            .with_llm_client(client.clone())
            .with_planning_mode(crate::prompts::PlanningMode::Disabled)
            .with_continuation(false)
            .with_task_priority(priority)
    };
    let blocker = Arc::new(
        agent
            .session_async(
                workspace.path().to_string_lossy(),
                Some(make_session(
                    "scheduler-blocker",
                    crate::task_scheduler::TaskPriority::Foreground,
                )),
            )
            .await
            .unwrap(),
    );
    let background = Arc::new(
        agent
            .session_async(
                workspace.path().to_string_lossy(),
                Some(make_session(
                    "scheduler-background",
                    crate::task_scheduler::TaskPriority::Background,
                )),
            )
            .await
            .unwrap(),
    );
    let interactive = Arc::new(
        agent
            .session_async(
                workspace.path().to_string_lossy(),
                Some(make_session(
                    "scheduler-interactive",
                    crate::task_scheduler::TaskPriority::Interactive,
                )),
            )
            .await
            .unwrap(),
    );

    let blocker_run = tokio::spawn({
        let blocker = Arc::clone(&blocker);
        async move { blocker.send("blocker", None).await }
    });
    assert_eq!(started_rx.recv().await.as_deref(), Some("blocker"));

    let background_run = tokio::spawn({
        let background = Arc::clone(&background);
        async move { background.send("background", None).await }
    });
    while agent.task_scheduler_stats().await.unwrap().pending < 1 {
        tokio::task::yield_now().await;
    }
    let interactive_run = tokio::spawn({
        let interactive = Arc::clone(&interactive);
        async move { interactive.send("interactive", None).await }
    });
    while agent.task_scheduler_stats().await.unwrap().pending < 2 {
        tokio::task::yield_now().await;
    }
    let queued = agent.task_scheduler_stats().await.unwrap();
    assert_eq!(queued.pending_by_priority.background, 1);
    assert_eq!(queued.pending_by_priority.interactive, 1);

    release.add_permits(1);
    assert_eq!(started_rx.recv().await.as_deref(), Some("interactive"));
    release.add_permits(1);
    assert_eq!(started_rx.recv().await.as_deref(), Some("background"));
    release.add_permits(1);

    blocker_run.await.unwrap().unwrap();
    interactive_run.await.unwrap().unwrap();
    background_run.await.unwrap().unwrap();
    assert_eq!(agent.task_scheduler_stats().await.unwrap().active, 0);
    agent.close().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn host_direct_tools_share_the_agent_scheduler_with_conversation_runs() {
    let workspace = tempfile::tempdir().unwrap();
    let (started_tx, mut started_rx) = tokio::sync::mpsc::unbounded_channel();
    let release = Arc::new(tokio::sync::Semaphore::new(0));
    let client = Arc::new(TaskSchedulerProbeClient {
        started: started_tx,
        release: Arc::clone(&release),
    });
    let mut config = test_config();
    config.task_scheduler = crate::task_scheduler::TaskSchedulerConfig {
        max_active: 1,
        aging_interval_ms: 60_000,
    };
    config.memory = Some(crate::memory::MemoryConfig {
        llm_extraction: false,
        ..Default::default()
    });
    let agent = Agent::from_config(config).await.unwrap();
    let base_options = |id: &str| {
        SessionOptions::new()
            .with_session_id(id)
            .with_llm_client(client.clone())
            .with_planning_mode(crate::prompts::PlanningMode::Disabled)
            .with_continuation(false)
    };
    let conversation = Arc::new(
        agent
            .session_async(
                workspace.path().to_string_lossy(),
                Some(base_options("direct-scheduler-conversation")),
            )
            .await
            .unwrap(),
    );
    let direct = Arc::new(
        agent
            .session_async(
                workspace.path().to_string_lossy(),
                Some(base_options("direct-scheduler-tool")),
            )
            .await
            .unwrap(),
    );
    direct
        .register_dynamic_tool(Arc::new(NamedSessionTool("scheduled-direct".to_string())))
        .unwrap();

    let conversation_run = tokio::spawn({
        let conversation = Arc::clone(&conversation);
        async move { conversation.send("hold-global-slot", None).await }
    });
    assert_eq!(started_rx.recv().await.as_deref(), Some("hold-global-slot"));
    let direct_run = tokio::spawn({
        let direct = Arc::clone(&direct);
        async move { direct.tool("scheduled-direct", serde_json::json!({})).await }
    });
    while agent.task_scheduler_stats().await.unwrap().pending < 1 {
        tokio::task::yield_now().await;
    }
    assert!(!direct_run.is_finished());

    release.add_permits(1);
    conversation_run.await.unwrap().unwrap();
    assert_eq!(direct_run.await.unwrap().unwrap().output, "ok");
    assert_eq!(agent.task_scheduler_stats().await.unwrap().active, 0);
    agent.close().await;
}

#[tokio::test]
async fn test_session_default() {
    let agent = Agent::from_config(test_config()).await.unwrap();
    let session = agent.session_async("/tmp/test-workspace", None).await;
    assert!(session.is_ok());
    let session = session.unwrap();
    let debug = format!("{:?}", session);
    assert!(debug.contains("AgentSession"));
    let health = session.model_middleware_health();
    assert_eq!(health.trust_admitted, 0);
    assert_eq!(health.trust_rejected, 0);
    let encoded = serde_json::to_value(&health).expect("middleware health must serialize");
    assert_eq!(encoded["trustAdmitted"], 0);
    assert!(encoded.get("prompt").is_none());
    assert!(encoded.get("toolResult").is_none());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn concurrent_session_direct_generations_share_provider_admission() {
    let dir = tempfile::tempdir().unwrap();
    let client = Arc::new(SessionAdmissionClient::default());
    let agent = Agent::from_config(test_config()).await.unwrap();
    let session = agent
        .session_async(
            dir.path().to_string_lossy().to_string(),
            Some(SessionOptions::new().with_llm_client(client.clone())),
        )
        .await
        .unwrap();
    let args = serde_json::json!({
        "schema": {
            "type": "object",
            "additionalProperties": false,
            "properties": {
                "ok": {"type": "boolean"}
            },
            "required": ["ok"]
        },
        "schema_name": "session_admission",
        "prompt": "Return an object whose ok field is true.",
        "mode": "prompt",
        "max_repair_attempts": 0,
        "timeout_ms": 2_000
    });

    let (first, second) = tokio::join!(
        session.tool("generate_object", args.clone()),
        session.tool("generate_object", args)
    );
    let results = [first.unwrap(), second.unwrap()];

    assert!(results
        .iter()
        .all(|result| result.exit_code == 0 && result.output.contains(r#""ok":true"#)));
    assert_eq!(
        client.max_active.load(std::sync::atomic::Ordering::SeqCst),
        1,
        "all host-direct loops in one session must share the provider gate"
    );
    let mut queue_waits = results
        .iter()
        .map(|result| {
            result
                .metadata
                .as_ref()
                .and_then(|metadata| metadata.pointer("/generation_admission/queue_wait_ms"))
                .and_then(serde_json::Value::as_u64)
                .expect("generation admission metadata")
        })
        .collect::<Vec<_>>();
    queue_waits.sort_unstable();
    assert!(
        queue_waits[1] >= 80,
        "the second direct generation should wait for session capacity: {queue_waits:?}"
    );
    let pool_health = session
        .model_generation_pool_health()
        .await
        .unwrap()
        .expect("the test client publishes a provider pool");
    let scheduler_health = pool_health
        .scheduler
        .expect("session provider admission is scheduler-bound");
    assert!(scheduler_health.observed);
    assert!(!scheduler_health.live);
    assert_eq!(scheduler_health.active, 0);
    assert_eq!(scheduler_health.pending, 0);
    assert_eq!(scheduler_health.admitted, 2);
    assert_eq!(scheduler_health.released, 2);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn independent_sessions_share_scheduler_backed_provider_generation_capacity() {
    let dir = tempfile::tempdir().unwrap();
    let client = Arc::new(SessionAdmissionClient::default());
    let agent = Agent::from_config(test_config()).await.unwrap();
    let options = |id: &str| {
        SessionOptions::new()
            .with_session_id(id)
            .with_llm_client(client.clone())
            .with_planning_mode(crate::prompts::PlanningMode::Disabled)
            .with_continuation(false)
    };
    let first = Arc::new(
        agent
            .session_async(dir.path().to_string_lossy(), Some(options("provider-a")))
            .await
            .unwrap(),
    );
    let second = Arc::new(
        agent
            .session_async(dir.path().to_string_lossy(), Some(options("provider-b")))
            .await
            .unwrap(),
    );
    let args = serde_json::json!({
        "schema": {
            "type": "object",
            "additionalProperties": false,
            "properties": {"ok": {"type": "boolean"}},
            "required": ["ok"]
        },
        "schema_name": "shared_provider",
        "prompt": "Return an object whose ok field is true.",
        "mode": "prompt",
        "max_repair_attempts": 0,
        "timeout_ms": 2_000
    });
    let (first_result, second_result) = tokio::join!(
        first.tool("generate_object", args.clone()),
        second.tool("generate_object", args)
    );
    assert!(first_result.unwrap().exit_code == 0);
    assert!(second_result.unwrap().exit_code == 0);
    assert_eq!(
        client.max_active.load(std::sync::atomic::Ordering::SeqCst),
        1,
        "sessions sharing one provider pool must not exceed its capacity"
    );
    let pool_health = first
        .model_generation_pool_health()
        .await
        .unwrap()
        .expect("the test client publishes a provider pool");
    let scheduler_health = pool_health
        .scheduler
        .expect("session provider admission is scheduler-bound");
    assert!(scheduler_health.observed);
    assert!(scheduler_health.admitted >= 2);
    assert!(scheduler_health.released >= 2);
    agent.close().await;
}

#[tokio::test]
async fn task_and_generate_object_reject_the_same_invalid_object() {
    let dir = tempfile::tempdir().unwrap();
    let agent = Agent::from_config(test_config()).await.unwrap();
    let session = agent
        .session_async(
            dir.path().to_string_lossy().to_string(),
            Some(
                SessionOptions::new().with_llm_client(Arc::new(StaticStreamingClient::new("nope"))),
            ),
        )
        .await
        .unwrap();
    let schema = serde_json::json!({
        "type": "object",
        "additionalProperties": false,
        "properties": { "n": { "type": "number" } },
        "required": ["n"]
    });

    let generated = session
        .tool(
            "generate_object",
            serde_json::json!({
                "schema": schema,
                "schema_name": "same_validator",
                "prompt": "Return n.",
                "mode": "prompt",
                "max_repair_attempts": 2
            }),
        )
        .await
        .unwrap();
    let tasked = session
        .tool(
            "task",
            serde_json::json!({
                "agent": "loop-planner",
                "description": "schema",
                "prompt": "Return n.",
                "output_schema": schema
            }),
        )
        .await
        .unwrap();

    assert_ne!(generated.exit_code, 0, "{}", generated.output);
    assert_ne!(tasked.exit_code, 0, "{}", tasked.output);
    for output in [&generated.output, &tasked.output] {
        assert!(
            output.contains("schema validation") || output.contains("no JSON object"),
            "validator decision diverged: {output}"
        );
        assert!(
            !output.contains("\"n\""),
            "invalid object was accepted: {output}"
        );
    }

    let accepted = agent
        .session_async(
            dir.path().to_string_lossy().to_string(),
            Some(
                SessionOptions::new()
                    .with_llm_client(Arc::new(StaticStreamingClient::new(r#"{"n":1}"#))),
            ),
        )
        .await
        .unwrap();
    let generated = accepted
        .tool(
            "generate_object",
            serde_json::json!({
                "schema": schema,
                "schema_name": "same_validator",
                "prompt": "Return n.",
                "mode": "prompt",
                "max_repair_attempts": 0
            }),
        )
        .await
        .unwrap();
    let tasked = accepted
        .tool(
            "task",
            serde_json::json!({
                "agent": "loop-planner",
                "description": "schema",
                "prompt": "Return n.",
                "output_schema": schema
            }),
        )
        .await
        .unwrap();
    assert_eq!(generated.exit_code, 0, "{}", generated.output);
    assert_eq!(tasked.exit_code, 0, "{}", tasked.output);
    let send_object = serde_json::from_str::<serde_json::Value>(&generated.output)
        .expect("generate_object output")
        .get("object")
        .cloned()
        .expect("generate_object object");
    let task_object = tasked
        .metadata
        .as_ref()
        .and_then(|metadata| metadata.get("structured"))
        .cloned()
        .expect("task structured object");
    assert_eq!(send_object, serde_json::json!({"n": 1}));
    assert_eq!(send_object, task_object);
    agent.close().await;
}