Skip to main content

aft/
run_tool_call.rs

1use std::path::PathBuf;
2use std::time::{Duration, Instant};
3
4use serde_json::{json, Value};
5
6use crate::context::AppContext;
7use crate::protocol::{RawRequest, Response};
8
9pub type DispatchFn<'a> = dyn Fn(RawRequest, &AppContext) -> Response + 'a;
10pub type FinalizeFn<'a> = dyn Fn(&mut Response) + 'a;
11
12/// Monotonic timestamps for one subc tool call. The recorder stays on the
13/// request path and only takes an `Instant::now()` at each phase boundary.
14#[derive(Debug)]
15pub struct PhaseTrace {
16    frame_decoded: Instant,
17    executor_submitted: Option<Instant>,
18    job_admitted: Option<Instant>,
19    translate_done: Option<Instant>,
20    execute_done: Option<Instant>,
21    format_done: Option<Instant>,
22    finalize_done: Option<Instant>,
23}
24
25#[derive(Debug, Clone, Copy)]
26pub struct ToolCallEgressTiming {
27    pub enqueued: Instant,
28    pub dequeued: Instant,
29    pub write_started: Instant,
30    pub write_finished: Instant,
31    pub frame_bytes: usize,
32    pub queue_depth: usize,
33    pub writer_active_at_enqueue: bool,
34    pub writer_queue_was_full: bool,
35    pub reserve_timeouts: u32,
36}
37
38#[derive(Debug, Clone, Copy)]
39pub struct ToolCallPhaseDurations {
40    pub queue: Duration,
41    pub translate: Duration,
42    pub execute: Duration,
43    pub format: Duration,
44    pub finalize: Duration,
45    pub egress_enqueue: Duration,
46    pub egress_queue: Duration,
47    pub egress_prepare: Duration,
48    pub egress_write: Duration,
49    pub egress: Duration,
50    pub frame_bytes: usize,
51    pub writer_queue_depth: usize,
52    pub writer_active_at_enqueue: bool,
53    pub writer_queue_was_full: bool,
54    pub writer_reserve_timeouts: u32,
55    pub total: Duration,
56}
57
58impl PhaseTrace {
59    pub fn new(frame_decoded: Instant) -> Self {
60        Self {
61            frame_decoded,
62            executor_submitted: None,
63            job_admitted: None,
64            translate_done: None,
65            execute_done: None,
66            format_done: None,
67            finalize_done: None,
68        }
69    }
70
71    pub fn mark_executor_submitted(&mut self) {
72        self.executor_submitted = Some(Instant::now());
73    }
74
75    pub fn mark_job_admitted(&mut self) {
76        self.job_admitted = Some(Instant::now());
77    }
78
79    fn mark_translate_done(&mut self) {
80        self.translate_done = Some(Instant::now());
81    }
82
83    fn mark_execute_done(&mut self) {
84        self.execute_done = Some(Instant::now());
85    }
86
87    fn mark_format_done(&mut self) {
88        self.format_done = Some(Instant::now());
89    }
90
91    fn mark_finalize_done(&mut self) {
92        self.finalize_done = Some(Instant::now());
93    }
94
95    pub fn finish(self, egress: ToolCallEgressTiming) -> Option<ToolCallPhaseDurations> {
96        let executor_submitted = self.executor_submitted?;
97        let job_admitted = self.job_admitted?;
98        let translate_done = self.translate_done?;
99        let execute_done = self.execute_done?;
100        let format_done = self.format_done?;
101        let finalize_done = self.finalize_done?;
102        Some(ToolCallPhaseDurations {
103            queue: job_admitted.duration_since(executor_submitted),
104            translate: translate_done.duration_since(job_admitted),
105            execute: execute_done.duration_since(translate_done),
106            format: format_done.duration_since(execute_done),
107            finalize: finalize_done.duration_since(format_done),
108            egress_enqueue: egress.enqueued.duration_since(finalize_done),
109            egress_queue: egress.dequeued.duration_since(egress.enqueued),
110            egress_prepare: egress.write_started.duration_since(egress.dequeued),
111            egress_write: egress.write_finished.duration_since(egress.write_started),
112            egress: egress.write_finished.duration_since(finalize_done),
113            frame_bytes: egress.frame_bytes,
114            writer_queue_depth: egress.queue_depth,
115            writer_active_at_enqueue: egress.writer_active_at_enqueue,
116            writer_queue_was_full: egress.writer_queue_was_full,
117            writer_reserve_timeouts: egress.reserve_timeouts,
118            total: egress.write_finished.duration_since(self.frame_decoded),
119        })
120    }
121}
122
123/// The full result of a tool call: the COMPLETE dispatch Response carried VERBATIM,
124/// plus the server-rendered agent-facing text (what the deleted TS formatters used to produce).
125/// Oracle #1: carry the WHOLE Response — promote nothing, drop nothing (preview_diff, attachments,
126/// status_bar, bg_completions, lsp_diagnostics, code, message, candidates, … all ride inside `response`).
127#[derive(Debug)]
128pub struct ToolCallResult {
129    pub text: String,
130    pub response: crate::protocol::Response,
131}
132
133/// Reserve a discriminated seam so bash/PTY/streaming (P3) doesn't force a signature rewrite.
134/// Only `Unary` is constructed today. Do NOT build `Stream`.
135#[derive(Debug)]
136pub enum ToolCallOutcome {
137    Unary(ToolCallResult),
138}
139
140/// Server-owned settings for a single `tool_call` request.
141/// These fields cannot be supplied through the agent's arguments object.
142#[derive(Debug, Clone)]
143pub struct ToolCallContext {
144    pub project_root: PathBuf,
145    pub session_id: Option<String>,
146    pub request_id: String,
147    pub diagnostics_on_edit: bool,
148    pub preview: bool,
149    /// Plugin-computed registration fact carried by transports whose bind
150    /// protocol cannot include configure-time process state.
151    pub edit_slot_survives: Option<bool>,
152    /// Whether configure's immediate registration-downgrade warning was discarded
153    /// by this transport and must be reported on the first tool call instead.
154    pub report_registration_downgrade: bool,
155}
156
157pub(crate) fn ensure_hashline_registration(
158    app_ctx: &AppContext,
159    project_root: &std::path::Path,
160    session: &str,
161    edit_slot_survives: Option<bool>,
162    report_registration_downgrade: bool,
163) -> bool {
164    let binding_root = app_ctx
165        .canonical_cache_root_opt()
166        .unwrap_or_else(|| project_root.to_path_buf());
167    let edit_slot_survives = match edit_slot_survives {
168        Some(value) => value,
169        None if app_ctx.harness_opt().is_some_and(|harness| {
170            matches!(
171                harness,
172                crate::harness::Harness::Opencode | crate::harness::Harness::Pi
173            )
174        }) && app_ctx
175            .hashline_bindings()
176            .peek(&binding_root, session)
177            .is_none() =>
178        {
179            false
180        }
181        None => return false,
182    };
183    let registration = app_ctx.hashline_bindings().register(
184        &binding_root,
185        session.to_string(),
186        crate::hashline::integration::RegistrationRequest {
187            configured_enabled: app_ctx.config().hashline_enabled,
188            edit_slot_survives,
189        },
190    );
191    report_registration_downgrade
192        && registration.downgrade.is_some()
193        && !registration.stores_preserved
194}
195
196fn attach_hashline_downgrade(response: &mut Response) {
197    let warning = crate::commands::configure::hashline_downgrade_warning();
198    if let Some(data) = response.data.as_object_mut() {
199        match data.get_mut("warnings").and_then(Value::as_array_mut) {
200            Some(warnings) => warnings.push(warning),
201            None => {
202                data.insert("warnings".to_string(), json!([warning]));
203            }
204        }
205    }
206}
207
208fn append_hashline_downgrade_text(text: &mut String) {
209    text.push_str("\n\n");
210    text.push_str(crate::commands::configure::HASHLINE_DOWNGRADE_MESSAGE);
211}
212
213pub fn run_tool_call(
214    bare_name: &str,
215    args: Value,
216    format_context: &crate::subc_format::FormatContext,
217    ctx: &ToolCallContext,
218    app_ctx: &AppContext,
219    dispatch: &DispatchFn<'_>,
220    finalizer: Option<&FinalizeFn<'_>>,
221    mut phase_trace: Option<&mut PhaseTrace>,
222) -> ToolCallOutcome {
223    let sanitized_args = strip_agent_preview_arg_owned(args);
224    let binding_root = app_ctx
225        .canonical_cache_root_opt()
226        .unwrap_or_else(|| ctx.project_root.clone());
227    let session = ctx
228        .session_id
229        .as_deref()
230        .unwrap_or(crate::protocol::DEFAULT_SESSION_ID);
231    let surface_downgraded = ensure_hashline_registration(
232        app_ctx,
233        &ctx.project_root,
234        session,
235        ctx.edit_slot_survives,
236        ctx.report_registration_downgrade,
237    );
238    let binding_guard = app_ctx.hashline_bindings().capture(binding_root, session);
239    let translate_context = crate::subc_translate::TranslateContext {
240        diagnostics_on_edit: ctx.diagnostics_on_edit,
241        preview: ctx.preview,
242        effective_hashline: crate::hashline::integration::effective_for_capture(
243            binding_guard.as_ref(),
244        ),
245    };
246    let (command, translated_args) = if crate::subc_translate::supports_tool(bare_name) {
247        match crate::subc_translate::subc_translate_owned_with_context(
248            bare_name,
249            sanitized_args,
250            ctx.project_root.as_path(),
251            translate_context,
252        ) {
253            Ok(translated) => (translated.command, translated.args),
254            Err(err) => {
255                if let Some(trace) = phase_trace.as_mut() {
256                    trace.mark_translate_done();
257                    trace.mark_execute_done();
258                }
259                let response = Response::error(ctx.request_id.clone(), err.code, err.message);
260                let result = tool_call_result_from_response(
261                    bare_name,
262                    format_context,
263                    response,
264                    surface_downgraded,
265                );
266                if let Some(trace) = phase_trace.as_mut() {
267                    trace.mark_format_done();
268                    trace.mark_finalize_done();
269                }
270                return ToolCallOutcome::Unary(result);
271            }
272        }
273    } else {
274        let map = match sanitized_args {
275            Value::Object(map) => map,
276            _ => serde_json::Map::new(),
277        };
278        (bare_name.to_string(), map)
279    };
280
281    let raw_req = match raw_request_from_translated(command, translated_args, ctx) {
282        Ok(req) => req,
283        Err(error) => {
284            if let Some(trace) = phase_trace.as_mut() {
285                trace.mark_translate_done();
286                trace.mark_execute_done();
287            }
288            let response = Response::error(
289                ctx.request_id.clone(),
290                "invalid_request",
291                format!("failed to build request from tool call: {error}"),
292            );
293            let result = tool_call_result_from_response(
294                bare_name,
295                format_context,
296                response,
297                surface_downgraded,
298            );
299            if let Some(trace) = phase_trace.as_mut() {
300                trace.mark_format_done();
301                trace.mark_finalize_done();
302            }
303            return ToolCallOutcome::Unary(result);
304        }
305    };
306    if let Some(trace) = phase_trace.as_mut() {
307        trace.mark_translate_done();
308    }
309
310    let mut response = dispatch(raw_req, app_ctx);
311    if let Some(trace) = phase_trace.as_mut() {
312        trace.mark_execute_done();
313    }
314    if surface_downgraded {
315        attach_hashline_downgrade(&mut response);
316    }
317    let mut text =
318        crate::subc_format::format_response_with_context(bare_name, &response, format_context);
319    if surface_downgraded {
320        append_hashline_downgrade_text(&mut text);
321    }
322    if let Some(trace) = phase_trace.as_mut() {
323        trace.mark_format_done();
324    }
325    if let Some(finalizer) = finalizer {
326        finalizer(&mut response);
327    }
328    if let Some(trace) = phase_trace.as_mut() {
329        trace.mark_finalize_done();
330    }
331
332    ToolCallOutcome::Unary(ToolCallResult { text, response })
333}
334
335fn raw_request_from_translated(
336    command: String,
337    mut params: serde_json::Map<String, Value>,
338    ctx: &ToolCallContext,
339) -> Result<RawRequest, &'static str> {
340    if params.contains_key("method") {
341        return Err("duplicate field `command`");
342    }
343
344    if ctx.preview {
345        params.insert("preview".to_string(), json!(true));
346    }
347
348    params.remove("id");
349    params.remove("command");
350    params.remove("session_id");
351    let lsp_hints = params.remove("lsp_hints").filter(|value| !value.is_null());
352
353    Ok(RawRequest {
354        id: ctx.request_id.clone(),
355        command,
356        lsp_hints,
357        session_id: ctx.session_id.clone(),
358        params: Value::Object(params),
359    })
360}
361
362pub(crate) fn strip_agent_preview_arg_owned(mut args: Value) -> Value {
363    if let Some(map) = args.as_object_mut() {
364        map.remove("preview");
365    }
366    args
367}
368
369fn tool_call_result_from_response(
370    bare_name: &str,
371    format_context: &crate::subc_format::FormatContext,
372    mut response: Response,
373    surface_downgraded: bool,
374) -> ToolCallResult {
375    if surface_downgraded {
376        attach_hashline_downgrade(&mut response);
377    }
378    let mut text =
379        crate::subc_format::format_response_with_context(bare_name, &response, format_context);
380    if surface_downgraded {
381        append_hashline_downgrade_text(&mut text);
382    }
383    ToolCallResult { text, response }
384}
385
386#[cfg(test)]
387mod tests {
388    use super::*;
389
390    #[test]
391    fn phase_trace_reports_execution_and_writer_egress_subphases() {
392        let t0 = Instant::now();
393        let trace = PhaseTrace {
394            frame_decoded: t0,
395            executor_submitted: Some(t0 + Duration::from_millis(1)),
396            job_admitted: Some(t0 + Duration::from_millis(3)),
397            translate_done: Some(t0 + Duration::from_millis(6)),
398            execute_done: Some(t0 + Duration::from_millis(10)),
399            format_done: Some(t0 + Duration::from_millis(15)),
400            finalize_done: Some(t0 + Duration::from_millis(21)),
401        };
402
403        let phases = trace
404            .finish(ToolCallEgressTiming {
405                enqueued: t0 + Duration::from_millis(28),
406                dequeued: t0 + Duration::from_millis(35),
407                write_started: t0 + Duration::from_millis(37),
408                write_finished: t0 + Duration::from_millis(48),
409                frame_bytes: 262_144,
410                queue_depth: 17,
411                writer_active_at_enqueue: true,
412                writer_queue_was_full: true,
413                reserve_timeouts: 2,
414            })
415            .unwrap();
416
417        assert_eq!(phases.queue, Duration::from_millis(2));
418        assert_eq!(phases.translate, Duration::from_millis(3));
419        assert_eq!(phases.execute, Duration::from_millis(4));
420        assert_eq!(phases.format, Duration::from_millis(5));
421        assert_eq!(phases.finalize, Duration::from_millis(6));
422        assert_eq!(phases.egress_enqueue, Duration::from_millis(7));
423        assert_eq!(phases.egress_queue, Duration::from_millis(7));
424        assert_eq!(phases.egress_prepare, Duration::from_millis(2));
425        assert_eq!(phases.egress_write, Duration::from_millis(11));
426        assert_eq!(phases.egress, Duration::from_millis(27));
427        assert_eq!(phases.frame_bytes, 262_144);
428        assert_eq!(phases.writer_queue_depth, 17);
429        assert!(phases.writer_active_at_enqueue);
430        assert!(phases.writer_queue_was_full);
431        assert_eq!(phases.writer_reserve_timeouts, 2);
432        assert_eq!(phases.total, Duration::from_millis(48));
433    }
434
435    mod raw_request_construction {
436        use std::hint::black_box;
437
438        use super::*;
439        use crate::test_allocations::count as count_allocations;
440
441        fn context(preview: bool) -> ToolCallContext {
442            ToolCallContext {
443                project_root: PathBuf::from("/workspace"),
444                session_id: Some("session-realistic".to_string()),
445                request_id: "subc-7-42".to_string(),
446                diagnostics_on_edit: true,
447                preview,
448                edit_slot_survives: None,
449                report_registration_downgrade: false,
450            }
451        }
452
453        fn object(value: Value) -> serde_json::Map<String, Value> {
454            value.as_object().cloned().expect("test input is an object")
455        }
456
457        fn legacy_raw_request(
458            command: String,
459            mut params: serde_json::Map<String, Value>,
460            ctx: &ToolCallContext,
461        ) -> Result<RawRequest, String> {
462            if ctx.preview {
463                params.insert("preview".to_string(), json!(true));
464            }
465            params.insert("id".to_string(), json!(ctx.request_id.clone()));
466            params.insert("command".to_string(), json!(command));
467            params.insert("session_id".to_string(), json!(ctx.session_id.clone()));
468            serde_json::from_value(Value::Object(params)).map_err(|error| error.to_string())
469        }
470
471        fn dispatch_result_bytes(request: RawRequest) -> Vec<u8> {
472            let response = Response::success(
473                request.id.clone(),
474                json!({
475                    "received_command": request.command,
476                    "received_lsp_hints": request.lsp_hints,
477                    "received_session_id": request.session_id,
478                    "received_params": request.params,
479                }),
480            );
481            serde_json::to_vec(&response).expect("serialize recording dispatch response")
482        }
483
484        #[test]
485        fn direct_raw_request_construction_avoids_flatten_rematerialization() {
486            let direct_params = object(json!({
487                "file": "/workspace/src/main.rs",
488                "start_line": 150,
489                "end_line": 229,
490            }));
491            let legacy_params = direct_params.clone();
492            let ctx = context(false);
493            let direct_command = "read".to_string();
494            let legacy_command = direct_command.clone();
495
496            let (direct, direct_allocations) = count_allocations(|| {
497                raw_request_from_translated(direct_command, direct_params, &ctx)
498                    .expect("direct request")
499            });
500            let (legacy, legacy_allocations) = count_allocations(|| {
501                legacy_raw_request(legacy_command, legacy_params, &ctx).expect("legacy request")
502            });
503            black_box((&direct, &legacy));
504
505            assert_eq!(direct_allocations, 2);
506            assert!(
507                legacy_allocations >= 20,
508                "legacy flatten path unexpectedly used only {legacy_allocations} allocations"
509            );
510            assert!(
511                legacy_allocations >= direct_allocations + 18,
512                "direct={direct_allocations}, legacy={legacy_allocations}"
513            );
514        }
515
516        #[test]
517        fn direct_raw_request_matches_legacy_dispatch_bytes() {
518            let edits = (0..100)
519                .map(|index| {
520                    json!({
521                        "match": format!("old declaration {index}"),
522                        "replacement": format!("new declaration {index}"),
523                        "replace_all": false,
524                    })
525                })
526                .collect::<Vec<_>>();
527            let cases = [
528                (
529                    "read",
530                    "read",
531                    object(json!({
532                        "file": "/workspace/src/main.rs",
533                        "start_line": 1,
534                        "end_line": 80,
535                    })),
536                    false,
537                ),
538                (
539                    "write",
540                    "write",
541                    object(json!({
542                        "file": "/workspace/src/new.rs",
543                        "content": "fn created() {}\n",
544                        "create_dirs": true,
545                    })),
546                    false,
547                ),
548                (
549                    "batch-edit-100",
550                    "batch",
551                    object(json!({
552                        "file": "/workspace/src/large.rs",
553                        "edits": edits,
554                    })),
555                    false,
556                ),
557                (
558                    "preview",
559                    "read",
560                    object(json!({"file": "/workspace/src/main.rs"})),
561                    true,
562                ),
563                (
564                    "lsp-hints",
565                    "move_symbol",
566                    object(json!({
567                        "file": "/workspace/src/main.rs",
568                        "symbol": "run",
569                        "destination": "/workspace/src/moved.rs",
570                        "lsp_hints": {
571                            "symbols": [{
572                                "name": "run",
573                                "file": "/workspace/src/main.rs",
574                                "line": 12,
575                                "kind": "function",
576                            }],
577                        },
578                    })),
579                    false,
580                ),
581                (
582                    "null-lsp-hints",
583                    "move_symbol",
584                    object(json!({
585                        "file": "/workspace/src/main.rs",
586                        "symbol": "run",
587                        "destination": "/workspace/src/moved.rs",
588                        "lsp_hints": null,
589                    })),
590                    false,
591                ),
592            ];
593
594            for (label, command, params, preview) in cases {
595                let ctx = context(preview);
596                let direct = raw_request_from_translated(command.to_string(), params.clone(), &ctx)
597                    .expect("direct request");
598                let legacy =
599                    legacy_raw_request(command.to_string(), params, &ctx).expect("legacy request");
600
601                assert_eq!(
602                    dispatch_result_bytes(direct),
603                    dispatch_result_bytes(legacy),
604                    "recording dispatch response differed for {label}"
605                );
606            }
607        }
608
609        #[test]
610        fn direct_raw_request_preserves_method_alias_rejection() {
611            let params = object(json!({"method": "agent-supplied-command"}));
612            let ctx = context(false);
613            let direct_error =
614                raw_request_from_translated("read".to_string(), params.clone(), &ctx)
615                    .expect_err("method alias must conflict with server-owned command");
616            let legacy_error = legacy_raw_request("read".to_string(), params, &ctx)
617                .expect_err("legacy path rejects the duplicate alias");
618
619            assert_eq!(direct_error, legacy_error);
620        }
621    }
622}