swink-agent 0.9.0

Core scaffolding for running LLM-powered agentic loops
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
//! Pre-process phase: pre-dispatch policies, approval gate, argument rewriting.

use std::collections::HashMap;
use std::sync::Arc;

use futures::FutureExt;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use tracing::error;

use crate::agent_options::ApproveToolFn;
use crate::policy::{PreDispatchVerdict, ToolDispatchContext, run_pre_dispatch_policies};
use crate::tool::{AgentTool, AgentToolResult, ApprovalMode, ToolApproval, ToolApprovalRequest};
use crate::types::{AgentMessage, ContentBlock};

use super::shared::{emit_batch_stop_results, emit_error_result, panic_payload_message};
use super::{
    AgentEvent, AgentLoopConfig, PreparedToolCall, ToolCallInfo, ToolExecOutcome, collect, emit,
    order_results_by_tool_calls,
};

// ─── Pre-process result ─────────────────────────────────────────────────────

/// Result of the pre-processing phase for a tool batch.
pub(super) struct PreprocessResult {
    /// Tool calls that passed all gates and are ready for dispatch.
    pub prepared: Vec<PreparedToolCall>,
    /// Messages injected by `PreDispatch` policies (Inject verdict).
    pub injected_messages: Vec<AgentMessage>,
}

/// Result of the batch-wide pre-dispatch policy pass for a single tool call.
enum PreDispatchPassResult {
    Ready {
        idx: usize,
        effective_arguments: serde_json::Value,
    },
    Skip {
        idx: usize,
        error_text: String,
    },
}

async fn aborted_preprocess_outcome(
    tool_calls: &[ToolCallInfo],
    results: &Arc<tokio::sync::Mutex<Vec<(usize, crate::types::ToolResultMessage)>>>,
    tool_timings: &Arc<tokio::sync::Mutex<Vec<crate::metrics::ToolExecMetrics>>>,
    injected_messages: Vec<AgentMessage>,
) -> ToolExecOutcome {
    collect::build_aborted_outcome(
        tool_calls,
        Arc::clone(results),
        Arc::clone(tool_timings),
        injected_messages,
    )
    .await
}

async fn stopped_preprocess_outcome(
    tool_calls: &[ToolCallInfo],
    reason: String,
    results: &Arc<tokio::sync::Mutex<Vec<(usize, crate::types::ToolResultMessage)>>>,
    tool_timings: &Arc<tokio::sync::Mutex<Vec<crate::metrics::ToolExecMetrics>>>,
    injected_messages: Vec<AgentMessage>,
    tx: &mpsc::Sender<AgentEvent>,
) -> ToolExecOutcome {
    emit_batch_stop_results(tool_calls, &reason, results, tx).await;
    let all_results = std::mem::take(&mut *results.lock().await);
    let ordered = order_results_by_tool_calls(tool_calls, &all_results);
    let collected_timings = std::mem::take(&mut *tool_timings.lock().await);
    ToolExecOutcome::Stopped {
        results: ordered,
        tool_metrics: collected_timings,
        reason,
        injected_messages,
    }
}

/// Result of checking the approval gate for a single tool call.
enum ApprovalOutcome {
    Approved,
    /// Approved with modified parameters.
    ApprovedWith(serde_json::Value),
    Rejected,
    Cancelled,
    ChannelClosed,
}

// ─── Pre-process entry point ────────────────────────────────────────────────

/// Run pre-dispatch policies and the approval gate for every tool call.
///
/// Returns `Ok(PreprocessResult)` when pre-processing completes (even if some
/// calls were skipped/rejected). Returns `Err(ToolExecOutcome)` for early
/// exits (policy Stop, channel closed).
#[allow(clippy::too_many_lines)]
pub(super) async fn preprocess_tool_calls(
    config: &Arc<AgentLoopConfig>,
    tool_calls: &[ToolCallInfo],
    cancellation_token: &CancellationToken,
    tool_map: &HashMap<&str, &Arc<dyn AgentTool>>,
    results: &Arc<tokio::sync::Mutex<Vec<(usize, crate::types::ToolResultMessage)>>>,
    tool_timings: &Arc<tokio::sync::Mutex<Vec<crate::metrics::ToolExecMetrics>>>,
    tx: &mpsc::Sender<AgentEvent>,
) -> Result<PreprocessResult, ToolExecOutcome> {
    let mut prepared: Vec<PreparedToolCall> = Vec::new();
    let mut injected_messages: Vec<AgentMessage> = Vec::new();
    let mut pre_dispatch_results: Vec<PreDispatchPassResult> = Vec::with_capacity(tool_calls.len());
    let mut batch_stop_reason: Option<String> = None;

    let state_snapshot = {
        let guard = config
            .session_state
            .read()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        guard.clone()
    };

    for (idx, tc) in tool_calls.iter().enumerate() {
        if cancellation_token.is_cancelled() {
            return Err(aborted_preprocess_outcome(
                tool_calls,
                results,
                tool_timings,
                injected_messages,
            )
            .await);
        }

        // ── PreDispatch policies ──
        let mut effective_arguments = tc.arguments.clone();
        let execution_root = tool_map
            .get(tc.name.as_str())
            .and_then(|tool| tool.execution_root());
        let mut dispatch_ctx = ToolDispatchContext {
            tool_name: &tc.name,
            tool_call_id: &tc.id,
            arguments: &mut effective_arguments,
            execution_root,
            state: &state_snapshot,
        };
        match run_pre_dispatch_policies(&config.pre_dispatch_policies, &mut dispatch_ctx) {
            PreDispatchVerdict::Continue => {
                pre_dispatch_results.push(PreDispatchPassResult::Ready {
                    idx,
                    effective_arguments,
                });
            }
            PreDispatchVerdict::Inject(msgs) => {
                injected_messages.extend(msgs);
                pre_dispatch_results.push(PreDispatchPassResult::Ready {
                    idx,
                    effective_arguments,
                });
            }
            PreDispatchVerdict::Stop(reason) => {
                if batch_stop_reason.is_none() {
                    batch_stop_reason = Some(reason);
                }
            }
            PreDispatchVerdict::Skip(error_text) => {
                pre_dispatch_results.push(PreDispatchPassResult::Skip { idx, error_text });
            }
        }
    }

    if let Some(reason) = batch_stop_reason {
        return Err(stopped_preprocess_outcome(
            tool_calls,
            reason,
            results,
            tool_timings,
            injected_messages,
            tx,
        )
        .await);
    }

    // A later `Stop` must abort the entire batch before any approval side
    // effects are emitted, so approval runs only after the whole batch clears
    // pre-dispatch.
    for pre_dispatch_result in pre_dispatch_results {
        if cancellation_token.is_cancelled() {
            return Err(aborted_preprocess_outcome(
                tool_calls,
                results,
                tool_timings,
                injected_messages,
            )
            .await);
        }

        let (idx, mut effective_arguments, skipped_error) = match pre_dispatch_result {
            PreDispatchPassResult::Ready {
                idx,
                effective_arguments,
            } => (idx, effective_arguments, None),
            PreDispatchPassResult::Skip { idx, error_text } => {
                (idx, serde_json::Value::Null, Some(error_text))
            }
        };
        let tc = &tool_calls[idx];

        if let Some(error_text) = skipped_error {
            let error_result = AgentToolResult {
                content: vec![ContentBlock::Text { text: error_text }],
                details: serde_json::Value::Null,
                is_error: true,
                transfer_signal: None,
            };
            emit_error_result(&tc.name, &tc.id, error_result, idx, results, tx).await;
            continue;
        }

        if let Some(ref approve_fn) = config.approve_tool
            && config.approval_mode != ApprovalMode::Bypassed
        {
            let requires_approval = tool_map
                .get(tc.name.as_str())
                .is_some_and(|t| t.requires_approval());

            let should_call_approval = match config.approval_mode {
                ApprovalMode::Smart => requires_approval,
                ApprovalMode::Enabled => true,
                ApprovalMode::Bypassed => unreachable!(),
            };

            if should_call_approval {
                match check_approval(
                    approve_fn,
                    tc,
                    &effective_arguments,
                    idx,
                    cancellation_token,
                    requires_approval,
                    tool_map,
                    results,
                    tx,
                )
                .await
                {
                    ApprovalOutcome::Approved => {}
                    ApprovalOutcome::ApprovedWith(new_params) => {
                        effective_arguments = new_params;
                        let execution_root = tool_map
                            .get(tc.name.as_str())
                            .and_then(|tool| tool.execution_root());
                        let mut dispatch_ctx = ToolDispatchContext {
                            tool_name: &tc.name,
                            tool_call_id: &tc.id,
                            arguments: &mut effective_arguments,
                            execution_root,
                            state: &state_snapshot,
                        };
                        match run_pre_dispatch_policies(
                            &config.pre_dispatch_policies,
                            &mut dispatch_ctx,
                        ) {
                            PreDispatchVerdict::Continue => {}
                            PreDispatchVerdict::Inject(msgs) => {
                                injected_messages.extend(msgs);
                            }
                            PreDispatchVerdict::Skip(error_text) => {
                                let error_result = AgentToolResult {
                                    content: vec![ContentBlock::Text { text: error_text }],
                                    details: serde_json::Value::Null,
                                    is_error: true,
                                    transfer_signal: None,
                                };
                                emit_error_result(&tc.name, &tc.id, error_result, idx, results, tx)
                                    .await;
                                continue;
                            }
                            PreDispatchVerdict::Stop(reason) => {
                                return Err(stopped_preprocess_outcome(
                                    tool_calls,
                                    reason,
                                    results,
                                    tool_timings,
                                    injected_messages,
                                    tx,
                                )
                                .await);
                            }
                        }
                    }
                    ApprovalOutcome::Rejected => continue,
                    ApprovalOutcome::Cancelled => {
                        return Err(aborted_preprocess_outcome(
                            tool_calls,
                            results,
                            tool_timings,
                            injected_messages,
                        )
                        .await);
                    }
                    ApprovalOutcome::ChannelClosed => return Err(ToolExecOutcome::ChannelClosed),
                }
            }
        }

        prepared.push(PreparedToolCall {
            idx,
            effective_arguments,
        });
    }

    Ok(PreprocessResult {
        prepared,
        injected_messages,
    })
}

async fn emit_approval_resolved(
    tx: &mpsc::Sender<AgentEvent>,
    tc: &ToolCallInfo,
    approved: bool,
) -> bool {
    emit(
        tx,
        AgentEvent::ToolApprovalResolved {
            id: tc.id.clone(),
            name: tc.name.clone(),
            approved,
        },
    )
    .await
}

async fn reject_approval_panic(
    tc: &ToolCallInfo,
    idx: usize,
    panic_message: &str,
    results: &Arc<tokio::sync::Mutex<Vec<(usize, crate::types::ToolResultMessage)>>>,
    tx: &mpsc::Sender<AgentEvent>,
) -> ApprovalOutcome {
    if !emit_approval_resolved(tx, tc, false).await {
        return ApprovalOutcome::ChannelClosed;
    }

    emit_error_result(
        &tc.name,
        &tc.id,
        AgentToolResult::error(format!(
            "Tool call '{}' was rejected because the approval callback panicked: \
             {panic_message}",
            tc.name
        )),
        idx,
        results,
        tx,
    )
    .await;
    ApprovalOutcome::Rejected
}

// ─── Approval helper ────────────────────────────────────────────────────────

/// Run the approval gate for a single tool call.
///
/// # Canonical event order
///
/// The full per-tool-call event sequence is:
///
/// 1. [`AgentEvent::ToolApprovalRequested`] — emitted here, before the callback fires.
/// 2. [`AgentEvent::ToolApprovalResolved`] — emitted here, after the callback resolves.
/// 3. [`AgentEvent::ToolExecutionStart`] — emitted later by `dispatch_single_tool`.
/// 4. [`AgentEvent::ToolExecutionEnd`] — emitted after the tool's `execute()` returns.
///
/// Approval always precedes execution: a tool must be approved before it is
/// dispatched, so `ToolExecutionStart` cannot be observed until after
/// `ToolApprovalResolved`. Consumers (TUI, eval, tests) may rely on this order.
#[allow(clippy::too_many_arguments)]
async fn check_approval(
    approve_fn: &ApproveToolFn,
    tc: &ToolCallInfo,
    effective_arguments: &serde_json::Value,
    idx: usize,
    cancellation_token: &CancellationToken,
    requires_approval: bool,
    tool_map: &HashMap<&str, &Arc<dyn AgentTool>>,
    results: &Arc<tokio::sync::Mutex<Vec<(usize, crate::types::ToolResultMessage)>>>,
    tx: &mpsc::Sender<AgentEvent>,
) -> ApprovalOutcome {
    if cancellation_token.is_cancelled() {
        return ApprovalOutcome::Cancelled;
    }

    if !emit(
        tx,
        AgentEvent::ToolApprovalRequested {
            id: tc.id.clone(),
            name: tc.name.clone(),
            arguments: effective_arguments.clone(),
        },
    )
    .await
    {
        return ApprovalOutcome::ChannelClosed;
    }

    // Resolve approval context with panic safety.
    let approval_context = tool_map.get(tc.name.as_str()).and_then(|tool| {
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            tool.approval_context(effective_arguments)
        }))
        .unwrap_or_else(|_| {
            tracing::warn!(tool_name = %tc.name, "approval_context() panicked — using None");
            None
        })
    });

    let request = ToolApprovalRequest {
        tool_call_id: tc.id.clone(),
        tool_name: tc.name.clone(),
        arguments: effective_arguments.clone(),
        requires_approval,
        context: approval_context,
    };
    let approval_future =
        match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| approve_fn(request))) {
            Ok(future) => future,
            Err(panic_value) => {
                let panic_message = panic_payload_message(panic_value.as_ref());
                error!(
                    tool_call_id = %tc.id,
                    tool_name = %tc.name,
                    "approval callback panicked before returning a future: {panic_message}"
                );
                return reject_approval_panic(tc, idx, &panic_message, results, tx).await;
            }
        };
    let decision = match tokio::select! {
        biased;
        () = cancellation_token.cancelled() => {
            if !emit_approval_resolved(tx, tc, false).await {
                return ApprovalOutcome::ChannelClosed;
            }

            return ApprovalOutcome::Cancelled;
        }
        decision = std::panic::AssertUnwindSafe(approval_future).catch_unwind() => decision
    } {
        Ok(decision) => decision,
        Err(panic_value) => {
            let panic_message = panic_payload_message(panic_value.as_ref());
            error!(
                tool_call_id = %tc.id,
                tool_name = %tc.name,
                "approval callback panicked: {panic_message}"
            );
            return reject_approval_panic(tc, idx, &panic_message, results, tx).await;
        }
    };
    let approved = !matches!(decision, ToolApproval::Rejected);

    if !emit_approval_resolved(tx, tc, approved).await {
        return ApprovalOutcome::ChannelClosed;
    }

    match decision {
        ToolApproval::Approved => ApprovalOutcome::Approved,
        ToolApproval::ApprovedWith(new_params) => ApprovalOutcome::ApprovedWith(new_params),
        ToolApproval::Rejected => {
            let rejection_result = AgentToolResult::error(format!(
                "Tool call '{}' was rejected by the approval gate.",
                tc.name
            ));
            emit_error_result(&tc.name, &tc.id, rejection_result, idx, results, tx).await;
            ApprovalOutcome::Rejected
        }
    }
}