a3s-code-core 2.0.1

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
//! SubAgent wrapper — executes a real AgentSession and forwards events to the
//! Orchestrator event bus, with pause/resume/cancel control signal support.

use crate::agent::AgentEvent;
use crate::error::Result;
use crate::orchestrator::{
    ControlSignal, OrchestratorEvent, SubAgentActivity, SubAgentConfig, SubAgentState,
};
use std::sync::Arc;
use tokio::sync::{broadcast, mpsc, RwLock};

struct PendingToolCall {
    id: String,
    name: String,
    args_buffer: String,
    started_at: std::time::Instant,
    emitted: bool,
}

fn parse_tool_args(raw: &str) -> serde_json::Value {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        serde_json::Value::Null
    } else {
        serde_json::from_str(trimmed)
            .unwrap_or_else(|_| serde_json::Value::String(trimmed.to_string()))
    }
}

fn tool_duration_ms(started_at: std::time::Instant) -> u64 {
    std::cmp::max(1, started_at.elapsed().as_millis() as u64)
}

pub(crate) struct SubAgentWrapper {
    id: String,
    config: SubAgentConfig,
    agent: Arc<crate::Agent>,
    event_tx: broadcast::Sender<OrchestratorEvent>,
    subagent_event_tx: broadcast::Sender<OrchestratorEvent>,
    event_history: Arc<RwLock<std::collections::VecDeque<OrchestratorEvent>>>,
    control_rx: mpsc::Receiver<ControlSignal>,
    state: Arc<RwLock<SubAgentState>>,
    activity: Arc<RwLock<SubAgentActivity>>,
}

impl SubAgentWrapper {
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        id: String,
        config: SubAgentConfig,
        agent: Arc<crate::Agent>,
        event_tx: broadcast::Sender<OrchestratorEvent>,
        subagent_event_tx: broadcast::Sender<OrchestratorEvent>,
        event_history: Arc<RwLock<std::collections::VecDeque<OrchestratorEvent>>>,
        control_rx: mpsc::Receiver<ControlSignal>,
        state: Arc<RwLock<SubAgentState>>,
        activity: Arc<RwLock<SubAgentActivity>>,
    ) -> Self {
        Self {
            id,
            config,
            agent,
            event_tx,
            subagent_event_tx,
            event_history,
            control_rx,
            state,
            activity,
        }
    }

    async fn emit(&self, event: OrchestratorEvent) {
        let _ = self.event_tx.send(event.clone());
        let _ = self.subagent_event_tx.send(event.clone());

        let mut history = self.event_history.write().await;
        history.push_back(event);
        while history.len() > 1024 {
            history.pop_front();
        }
    }

    async fn flush_tool_start(
        &self,
        pending_tool: &mut Option<PendingToolCall>,
    ) -> std::time::Instant {
        let pending = pending_tool
            .as_mut()
            .expect("flush_tool_start called without a pending tool");
        if pending.emitted {
            return pending.started_at;
        }

        let args = parse_tool_args(&pending.args_buffer);
        self.emit(OrchestratorEvent::ToolExecutionStarted {
            id: self.id.clone(),
            tool_id: pending.id.clone(),
            tool_name: pending.name.clone(),
            args: args.clone(),
        })
        .await;

        *self.activity.write().await = SubAgentActivity::CallingTool {
            tool_name: pending.name.clone(),
            args,
        };
        pending.emitted = true;
        pending.started_at
    }

    /// Run the SubAgent against the configured real Agent.
    pub(crate) async fn execute(mut self) -> Result<String> {
        self.update_state(SubAgentState::Running).await;
        let start = std::time::Instant::now();

        let agent = Arc::clone(&self.agent);
        let result = self.execute_with_agent(agent).await;

        let duration_ms = start.elapsed().as_millis() as u64;

        match &result {
            Ok(output) => {
                self.update_state(SubAgentState::Completed {
                    success: true,
                    output: output.clone(),
                })
                .await;
                self.emit(OrchestratorEvent::SubAgentCompleted {
                    id: self.id.clone(),
                    success: true,
                    output: output.clone(),
                    duration_ms,
                    token_usage: None,
                })
                .await;
            }
            Err(e) => {
                let current = self.state.read().await.clone();
                if !matches!(current, SubAgentState::Cancelled) {
                    self.update_state(SubAgentState::Error {
                        message: e.to_string(),
                    })
                    .await;
                }
                self.emit(OrchestratorEvent::SubAgentCompleted {
                    id: self.id.clone(),
                    success: false,
                    output: e.to_string(),
                    duration_ms,
                    token_usage: None,
                })
                .await;
            }
        }

        result
    }

    // -------------------------------------------------------------------------
    // Real execution via AgentSession
    // -------------------------------------------------------------------------

    async fn execute_with_agent(&mut self, agent: Arc<crate::Agent>) -> Result<String> {
        // Build an AgentRegistry from built-ins + extra agent_dirs.
        let registry = crate::subagent::AgentRegistry::new();
        for dir in &self.config.agent_dirs {
            let agents = crate::subagent::load_agents_from_dir(std::path::Path::new(dir));
            for def in agents {
                registry.register(def);
            }
        }

        // Build session options from SubAgentConfig fields.
        let mut opts = crate::SessionOptions::new();

        // Pass agent_dirs and skill_dirs to session options
        for dir in &self.config.agent_dirs {
            opts = opts.with_agent_dir(dir.as_str());
        }
        if !self.config.skill_dirs.is_empty() {
            opts = opts.with_skill_dirs(self.config.skill_dirs.iter().map(|s| s.as_str()));
        }

        if let Some(steps) = self.config.max_steps {
            opts = opts.with_max_tool_rounds(steps);
        }
        // Create session: use the named agent definition if found, otherwise
        // fall back to a plain session so unknown agent_types still work.
        let session = Arc::new(if let Some(def) = registry.get(&self.config.agent_type) {
            agent.session_for_agent(&self.config.workspace, &def, Some(opts))?
        } else {
            agent.session(&self.config.workspace, Some(opts))?
        });

        // Stream execution.
        let (mut rx, _task) = session.stream(&self.config.prompt, None).await?;

        let mut output = String::new();
        let mut step: usize = 0;
        let mut pending_tool: Option<PendingToolCall> = None;

        loop {
            // Drain pending control signals before each event.
            while let Ok(signal) = self.control_rx.try_recv() {
                self.handle_control_signal(signal).await?;
            }

            // Abort if cancelled.
            if matches!(*self.state.read().await, SubAgentState::Cancelled) {
                // Drop rx to signal the background streaming task to stop.
                drop(rx);
                return Err(anyhow::anyhow!("Cancelled by orchestrator").into());
            }

            // Wait while paused (backpressure on rx naturally slows the agent).
            while matches!(*self.state.read().await, SubAgentState::Paused) {
                *self.activity.write().await = SubAgentActivity::WaitingForControl {
                    reason: "Paused by orchestrator".to_string(),
                };
                tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
                while let Ok(signal) = self.control_rx.try_recv() {
                    self.handle_control_signal(signal).await?;
                }
                if matches!(*self.state.read().await, SubAgentState::Cancelled) {
                    drop(rx);
                    return Err(anyhow::anyhow!("Cancelled by orchestrator").into());
                }
            }

            // Consume the next agent event.
            match rx.recv().await {
                Some(AgentEvent::TurnStart { turn }) => {
                    *self.activity.write().await =
                        SubAgentActivity::RequestingLlm { message_count: 0 };
                    self.emit(OrchestratorEvent::SubAgentInternalEvent {
                        id: self.id.clone(),
                        event: AgentEvent::TurnStart { turn },
                    })
                    .await;
                }
                Some(AgentEvent::ToolStart { id, name }) => {
                    pending_tool = Some(PendingToolCall {
                        id,
                        name,
                        args_buffer: String::new(),
                        started_at: std::time::Instant::now(),
                        emitted: false,
                    });
                }
                Some(AgentEvent::ToolInputDelta { delta }) => {
                    if let Some(pending) = pending_tool.as_mut() {
                        pending.args_buffer.push_str(&delta);
                    }
                    self.emit(OrchestratorEvent::SubAgentInternalEvent {
                        id: self.id.clone(),
                        event: AgentEvent::ToolInputDelta { delta },
                    })
                    .await;
                }
                Some(AgentEvent::ToolEnd {
                    id,
                    name,
                    output: tool_out,
                    exit_code,
                    ..
                }) => {
                    step += 1;
                    let started_at =
                        if pending_tool.as_ref().map(|p| p.id.as_str()) == Some(id.as_str()) {
                            self.flush_tool_start(&mut pending_tool).await
                        } else {
                            std::time::Instant::now()
                        };
                    *self.activity.write().await = SubAgentActivity::Idle;
                    self.emit(OrchestratorEvent::ToolExecutionCompleted {
                        id: self.id.clone(),
                        tool_id: id,
                        tool_name: name,
                        result: tool_out,
                        exit_code,
                        duration_ms: tool_duration_ms(started_at),
                    })
                    .await;
                    pending_tool = None;
                    self.emit(OrchestratorEvent::SubAgentProgress {
                        id: self.id.clone(),
                        step,
                        total_steps: self.config.max_steps.unwrap_or(0),
                        message: format!("Completed tool call {step}"),
                    })
                    .await;
                }
                Some(AgentEvent::TextDelta { text }) => {
                    if pending_tool.is_some() {
                        self.flush_tool_start(&mut pending_tool).await;
                    }
                    output.push_str(&text);
                    self.emit(OrchestratorEvent::SubAgentInternalEvent {
                        id: self.id.clone(),
                        event: AgentEvent::TextDelta { text },
                    })
                    .await;
                }
                Some(AgentEvent::End { text, .. }) => {
                    if pending_tool.is_some() {
                        self.flush_tool_start(&mut pending_tool).await;
                    }
                    output = text;
                    break;
                }
                Some(AgentEvent::Error { message }) => {
                    return Err(anyhow::anyhow!("Agent error: {message}").into());
                }
                // Forward all other events as internal events for observability.
                Some(event) => {
                    if pending_tool.is_some() {
                        self.flush_tool_start(&mut pending_tool).await;
                    }
                    self.emit(OrchestratorEvent::SubAgentInternalEvent {
                        id: self.id.clone(),
                        event,
                    })
                    .await;
                }
                None => break, // stream closed
            }
        }

        Ok(output)
    }

    async fn handle_control_signal(&mut self, signal: ControlSignal) -> Result<()> {
        self.emit(OrchestratorEvent::ControlSignalReceived {
            id: self.id.clone(),
            signal: signal.clone(),
        })
        .await;

        let result = match signal {
            ControlSignal::Pause => {
                self.update_state(SubAgentState::Paused).await;
                Ok(())
            }
            ControlSignal::Resume => {
                self.update_state(SubAgentState::Running).await;
                Ok(())
            }
            ControlSignal::Cancel => {
                self.update_state(SubAgentState::Cancelled).await;
                Err(anyhow::anyhow!("Cancelled by orchestrator").into())
            }
            ControlSignal::AdjustParams { max_steps, .. } => {
                if let Some(steps) = max_steps {
                    self.config.max_steps = Some(steps);
                }
                Ok(())
            }
            ControlSignal::InjectPrompt { ref prompt } => {
                // Append the injected prompt so the next LLM turn sees it.
                self.config.prompt.push('\n');
                self.config.prompt.push_str(prompt);
                Ok(())
            }
        };

        self.emit(OrchestratorEvent::ControlSignalApplied {
            id: self.id.clone(),
            signal,
            success: result.is_ok(),
            error: result.as_ref().err().map(|e| format!("{e}")),
        })
        .await;

        result
    }

    async fn update_state(&self, new_state: SubAgentState) {
        let old_state = {
            let mut state = self.state.write().await;
            let old = state.clone();
            *state = new_state.clone();
            old
        };

        self.emit(OrchestratorEvent::SubAgentStateChanged {
            id: self.id.clone(),
            old_state,
            new_state,
        })
        .await;
    }
}

#[cfg(test)]
mod tests {
    use super::{parse_tool_args, tool_duration_ms};
    use serde_json::json;
    use std::time::{Duration, Instant};

    #[test]
    fn parse_tool_args_parses_json_object() {
        assert_eq!(
            parse_tool_args(r#"{"path":"README.md"}"#),
            json!({"path": "README.md"})
        );
    }

    #[test]
    fn parse_tool_args_returns_null_for_empty_input() {
        assert_eq!(parse_tool_args("   "), serde_json::Value::Null);
    }

    #[test]
    fn parse_tool_args_preserves_non_json_input_as_string() {
        assert_eq!(
            parse_tool_args(r#"{"path":"README.md""#),
            serde_json::Value::String(r#"{"path":"README.md""#.to_string())
        );
    }

    #[test]
    fn tool_duration_ms_has_one_millisecond_floor() {
        let started_at = Instant::now();
        assert_eq!(tool_duration_ms(started_at), 1);
    }

    #[test]
    fn tool_duration_ms_preserves_elapsed_milliseconds() {
        let started_at = Instant::now() - Duration::from_millis(12);
        assert!(tool_duration_ms(started_at) >= 12);
    }
}