Skip to main content

artifactize_core/
verify_tools.rs

1//! Protocol-neutral implementation of the public Verify and inspection tools.
2mod catalog;
3mod error;
4mod input;
5mod page;
6mod read;
7mod tool;
8
9pub use catalog::{Hints, Tool, tools};
10pub use error::{ArgumentsError, Error};
11pub use input::Call;
12pub use page::{CursorError, Page};
13
14use std::{future::Future, time::Duration};
15
16use serde::Serialize;
17use tokio_util::sync::CancellationToken;
18
19use crate::{project::VerifyOptions, runs, types::RunId};
20use input::{Command, DEFAULT_WAIT_SECONDS, Plugin, Verify};
21
22/// Includes a zero-bound initial read and failure recovery; no MCP call reaches 45 s.
23const WAIT_CALL_LIMIT: Duration = Duration::from_secs(44);
24
25#[derive(Serialize)]
26#[serde(untagged)]
27pub enum Output {
28    Observation(runs::RunObservation),
29    Result(Box<runs::RunResultPage>),
30    Cancellation(runs::CancelAcknowledgement),
31    Inspection(Page),
32    Plugin(PluginResult),
33}
34
35#[derive(Serialize)]
36#[serde(tag = "action", rename_all = "lowercase")]
37pub enum PluginResult {
38    Added(crate::config::plugins::PluginInfo),
39    Removed {
40        #[serde(rename = "type")]
41        name: crate::config::ArtifactType,
42    },
43}
44
45/// Chat does not expose project-level plugin installation or removal.
46pub(crate) fn chat_tool(name: &str) -> bool {
47    matches!(
48        tool::ToolId::parse(name),
49        Some(tool::ToolId::Verify(_) | tool::ToolId::Read(_))
50    )
51}
52
53impl Call {
54    /// Execute the same operation in an MCP transport or an in-process Chat session.
55    /// Transports resolve their own scope before invoking this; a Chat scopes it to one worktree.
56    pub async fn execute<F: Future<Output = Result<(), String>>>(
57        self,
58        context: &runs::Context,
59        cancel: CancellationToken,
60        progress: impl FnMut(runs::RunEvent) -> F,
61    ) -> Result<Output, Error> {
62        let command = match self.command {
63            Command::Verify(command) => command,
64            Command::Plugin(plugin) => {
65                use crate::config::plugins;
66                let result = match plugin {
67                    Plugin::Add(args) => PluginResult::Added(
68                        plugins::add(context.repo(), &args.path).map_err(Error::Config)?,
69                    ),
70                    Plugin::Remove(args) => {
71                        plugins::remove(context.repo(), &args.name).map_err(Error::Config)?;
72                        PluginResult::Removed { name: args.name }
73                    }
74                };
75                return Ok(Output::Plugin(result));
76            }
77            Command::Inspect(inspection) => {
78                return Ok(Output::Inspection(
79                    read::inspect(context, inspection).await?,
80                ));
81            }
82        };
83        Ok(match command {
84            Verify::Start(args) => {
85                let options = VerifyOptions {
86                    jobs: args.jobs.map(|limit| limit.get() as usize),
87                    modes: runs::RunModes {
88                        speculate: args.speculate,
89                    },
90                    comment: args.comment,
91                    ..Default::default()
92                };
93                Output::Observation(
94                    runs::start_with_args_hash(
95                        context,
96                        args.scope.selection(),
97                        &options,
98                        args.request_key,
99                        args.request_args_hash,
100                    )
101                    .await?,
102                )
103            }
104            Verify::Status(run) => Output::Observation(runs::status(context, &run).await?),
105            Verify::Wait(args) => Output::Observation(
106                tokio::time::timeout(
107                    WAIT_CALL_LIMIT,
108                    runs::wait(context, &args.run, Some(args.duration()), cancel),
109                )
110                .await
111                .map_err(|_| Error::Timeout)??,
112            ),
113            Verify::Watch(run) => Output::Observation(
114                tokio::time::timeout(
115                    WAIT_CALL_LIMIT,
116                    runs::watch(
117                        context,
118                        &run,
119                        Some(Duration::from_secs(DEFAULT_WAIT_SECONDS)),
120                        cancel,
121                        progress,
122                    ),
123                )
124                .await
125                .map_err(|_| Error::Timeout)??,
126            ),
127            Verify::Result(args) => Output::Result(Box::new(
128                runs::result(context, &args.run, args.cursor).await?,
129            )),
130            Verify::Cancel(run) => Output::Cancellation(runs::cancel(context, &run).await?),
131        })
132    }
133
134    /// Whether success reports the identity of the Run this tool started, not an inspected Run.
135    pub fn started_run(&self) -> bool {
136        matches!(self.command, Command::Verify(Verify::Start(_)))
137    }
138
139    /// Remap an ACP agent-supplied `verify_start` `request_key` into the disjoint internal
140    /// `chat/<sha256[..32]>` namespace and attach canonical `request_args_hash`.
141    pub(crate) fn remap_acp_chat_key(
142        &mut self,
143        session_id: &crate::types::SessionId,
144        send: usize,
145        raw_arguments: &serde_json::Value,
146    ) -> Result<(), String> {
147        if let Command::Verify(Verify::Start(args)) = &mut self.command
148            && let Some(agent_key) = args.request_key.take()
149        {
150            args.request_key = Some(crate::acp::verify_bridge::internal_chat_request_key(
151                session_id,
152                send,
153                agent_key.as_str(),
154            )?);
155            args.request_args_hash = Some(crate::acp::verify_bridge::canonical_args_hash(
156                raw_arguments,
157            ));
158        }
159        Ok(())
160    }
161}
162
163impl Output {
164    pub fn observed_run(&self) -> Option<&RunId> {
165        match self {
166            Self::Observation(observation) => Some(&observation.run),
167            _ => None,
168        }
169    }
170}