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 = if raw_req.command == "inspect" {
311        crate::commands::inspect::handle_inspect_tool_call(&raw_req, app_ctx)
312    } else {
313        dispatch(raw_req, app_ctx)
314    };
315    if let Some(trace) = phase_trace.as_mut() {
316        trace.mark_execute_done();
317    }
318    if surface_downgraded {
319        attach_hashline_downgrade(&mut response);
320    }
321    let mut text =
322        crate::subc_format::format_response_with_context(bare_name, &response, format_context);
323    if surface_downgraded {
324        append_hashline_downgrade_text(&mut text);
325    }
326    if let Some(trace) = phase_trace.as_mut() {
327        trace.mark_format_done();
328    }
329    if let Some(finalizer) = finalizer {
330        finalizer(&mut response);
331    }
332    if let Some(trace) = phase_trace.as_mut() {
333        trace.mark_finalize_done();
334    }
335
336    ToolCallOutcome::Unary(ToolCallResult { text, response })
337}
338
339fn raw_request_from_translated(
340    command: String,
341    mut params: serde_json::Map<String, Value>,
342    ctx: &ToolCallContext,
343) -> Result<RawRequest, &'static str> {
344    if params.contains_key("method") {
345        return Err("duplicate field `command`");
346    }
347
348    if ctx.preview {
349        params.insert("preview".to_string(), json!(true));
350    }
351
352    params.remove("id");
353    params.remove("command");
354    params.remove("session_id");
355    let lsp_hints = params.remove("lsp_hints").filter(|value| !value.is_null());
356
357    Ok(RawRequest {
358        id: ctx.request_id.clone(),
359        command,
360        lsp_hints,
361        session_id: ctx.session_id.clone(),
362        params: Value::Object(params),
363    })
364}
365
366pub(crate) fn strip_agent_preview_arg_owned(mut args: Value) -> Value {
367    if let Some(map) = args.as_object_mut() {
368        map.remove("preview");
369    }
370    args
371}
372
373fn tool_call_result_from_response(
374    bare_name: &str,
375    format_context: &crate::subc_format::FormatContext,
376    mut response: Response,
377    surface_downgraded: bool,
378) -> ToolCallResult {
379    if surface_downgraded {
380        attach_hashline_downgrade(&mut response);
381    }
382    let mut text =
383        crate::subc_format::format_response_with_context(bare_name, &response, format_context);
384    if surface_downgraded {
385        append_hashline_downgrade_text(&mut text);
386    }
387    ToolCallResult { text, response }
388}
389
390#[cfg(test)]
391mod tests {
392    use super::*;
393
394    #[test]
395    fn phase_trace_reports_execution_and_writer_egress_subphases() {
396        let t0 = Instant::now();
397        let trace = PhaseTrace {
398            frame_decoded: t0,
399            executor_submitted: Some(t0 + Duration::from_millis(1)),
400            job_admitted: Some(t0 + Duration::from_millis(3)),
401            translate_done: Some(t0 + Duration::from_millis(6)),
402            execute_done: Some(t0 + Duration::from_millis(10)),
403            format_done: Some(t0 + Duration::from_millis(15)),
404            finalize_done: Some(t0 + Duration::from_millis(21)),
405        };
406
407        let phases = trace
408            .finish(ToolCallEgressTiming {
409                enqueued: t0 + Duration::from_millis(28),
410                dequeued: t0 + Duration::from_millis(35),
411                write_started: t0 + Duration::from_millis(37),
412                write_finished: t0 + Duration::from_millis(48),
413                frame_bytes: 262_144,
414                queue_depth: 17,
415                writer_active_at_enqueue: true,
416                writer_queue_was_full: true,
417                reserve_timeouts: 2,
418            })
419            .unwrap();
420
421        assert_eq!(phases.queue, Duration::from_millis(2));
422        assert_eq!(phases.translate, Duration::from_millis(3));
423        assert_eq!(phases.execute, Duration::from_millis(4));
424        assert_eq!(phases.format, Duration::from_millis(5));
425        assert_eq!(phases.finalize, Duration::from_millis(6));
426        assert_eq!(phases.egress_enqueue, Duration::from_millis(7));
427        assert_eq!(phases.egress_queue, Duration::from_millis(7));
428        assert_eq!(phases.egress_prepare, Duration::from_millis(2));
429        assert_eq!(phases.egress_write, Duration::from_millis(11));
430        assert_eq!(phases.egress, Duration::from_millis(27));
431        assert_eq!(phases.frame_bytes, 262_144);
432        assert_eq!(phases.writer_queue_depth, 17);
433        assert!(phases.writer_active_at_enqueue);
434        assert!(phases.writer_queue_was_full);
435        assert_eq!(phases.writer_reserve_timeouts, 2);
436        assert_eq!(phases.total, Duration::from_millis(48));
437    }
438
439    mod raw_request_construction {
440        use std::hint::black_box;
441
442        use super::*;
443        use crate::test_allocations::count as count_allocations;
444
445        fn context(preview: bool) -> ToolCallContext {
446            ToolCallContext {
447                project_root: PathBuf::from("/workspace"),
448                session_id: Some("session-realistic".to_string()),
449                request_id: "subc-7-42".to_string(),
450                diagnostics_on_edit: true,
451                preview,
452                edit_slot_survives: None,
453                report_registration_downgrade: false,
454            }
455        }
456
457        fn object(value: Value) -> serde_json::Map<String, Value> {
458            value.as_object().cloned().expect("test input is an object")
459        }
460
461        fn legacy_raw_request(
462            command: String,
463            mut params: serde_json::Map<String, Value>,
464            ctx: &ToolCallContext,
465        ) -> Result<RawRequest, String> {
466            if ctx.preview {
467                params.insert("preview".to_string(), json!(true));
468            }
469            params.insert("id".to_string(), json!(ctx.request_id.clone()));
470            params.insert("command".to_string(), json!(command));
471            params.insert("session_id".to_string(), json!(ctx.session_id.clone()));
472            serde_json::from_value(Value::Object(params)).map_err(|error| error.to_string())
473        }
474
475        fn dispatch_result_bytes(request: RawRequest) -> Vec<u8> {
476            let response = Response::success(
477                request.id.clone(),
478                json!({
479                    "received_command": request.command,
480                    "received_lsp_hints": request.lsp_hints,
481                    "received_session_id": request.session_id,
482                    "received_params": request.params,
483                }),
484            );
485            serde_json::to_vec(&response).expect("serialize recording dispatch response")
486        }
487
488        #[test]
489        fn direct_raw_request_construction_avoids_flatten_rematerialization() {
490            let direct_params = object(json!({
491                "file": "/workspace/src/main.rs",
492                "start_line": 150,
493                "end_line": 229,
494            }));
495            let legacy_params = direct_params.clone();
496            let ctx = context(false);
497            let direct_command = "read".to_string();
498            let legacy_command = direct_command.clone();
499
500            let (direct, direct_allocations) = count_allocations(|| {
501                raw_request_from_translated(direct_command, direct_params, &ctx)
502                    .expect("direct request")
503            });
504            let (legacy, legacy_allocations) = count_allocations(|| {
505                legacy_raw_request(legacy_command, legacy_params, &ctx).expect("legacy request")
506            });
507            black_box((&direct, &legacy));
508
509            assert_eq!(direct_allocations, 2);
510            assert!(
511                legacy_allocations >= 20,
512                "legacy flatten path unexpectedly used only {legacy_allocations} allocations"
513            );
514            assert!(
515                legacy_allocations >= direct_allocations + 18,
516                "direct={direct_allocations}, legacy={legacy_allocations}"
517            );
518        }
519
520        #[test]
521        fn direct_raw_request_matches_legacy_dispatch_bytes() {
522            let edits = (0..100)
523                .map(|index| {
524                    json!({
525                        "match": format!("old declaration {index}"),
526                        "replacement": format!("new declaration {index}"),
527                        "replace_all": false,
528                    })
529                })
530                .collect::<Vec<_>>();
531            let cases = [
532                (
533                    "read",
534                    "read",
535                    object(json!({
536                        "file": "/workspace/src/main.rs",
537                        "start_line": 1,
538                        "end_line": 80,
539                    })),
540                    false,
541                ),
542                (
543                    "write",
544                    "write",
545                    object(json!({
546                        "file": "/workspace/src/new.rs",
547                        "content": "fn created() {}\n",
548                        "create_dirs": true,
549                    })),
550                    false,
551                ),
552                (
553                    "batch-edit-100",
554                    "batch",
555                    object(json!({
556                        "file": "/workspace/src/large.rs",
557                        "edits": edits,
558                    })),
559                    false,
560                ),
561                (
562                    "preview",
563                    "read",
564                    object(json!({"file": "/workspace/src/main.rs"})),
565                    true,
566                ),
567                (
568                    "lsp-hints",
569                    "move_symbol",
570                    object(json!({
571                        "file": "/workspace/src/main.rs",
572                        "symbol": "run",
573                        "destination": "/workspace/src/moved.rs",
574                        "lsp_hints": {
575                            "symbols": [{
576                                "name": "run",
577                                "file": "/workspace/src/main.rs",
578                                "line": 12,
579                                "kind": "function",
580                            }],
581                        },
582                    })),
583                    false,
584                ),
585                (
586                    "null-lsp-hints",
587                    "move_symbol",
588                    object(json!({
589                        "file": "/workspace/src/main.rs",
590                        "symbol": "run",
591                        "destination": "/workspace/src/moved.rs",
592                        "lsp_hints": null,
593                    })),
594                    false,
595                ),
596            ];
597
598            for (label, command, params, preview) in cases {
599                let ctx = context(preview);
600                let direct = raw_request_from_translated(command.to_string(), params.clone(), &ctx)
601                    .expect("direct request");
602                let legacy =
603                    legacy_raw_request(command.to_string(), params, &ctx).expect("legacy request");
604
605                assert_eq!(
606                    dispatch_result_bytes(direct),
607                    dispatch_result_bytes(legacy),
608                    "recording dispatch response differed for {label}"
609                );
610            }
611        }
612
613        #[test]
614        fn direct_raw_request_preserves_method_alias_rejection() {
615            let params = object(json!({"method": "agent-supplied-command"}));
616            let ctx = context(false);
617            let direct_error =
618                raw_request_from_translated("read".to_string(), params.clone(), &ctx)
619                    .expect_err("method alias must conflict with server-owned command");
620            let legacy_error = legacy_raw_request("read".to_string(), params, &ctx)
621                .expect_err("legacy path rejects the duplicate alias");
622
623            assert_eq!(direct_error, legacy_error);
624        }
625    }
626}