pi_agent_rust 0.6.0

Native AI coding agent CLI - Rust port of Pi Agent
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
//! Opt-in desktop automation (bd-cv653.2.5).
//!
//! Live operations use OS helpers, never the deterministic fixture backend.
//! Host approval is required for input and clipboard mutations by default.
//! Screenshots and clipboard reads can expose private desktop data: enable this
//! tool only for a desktop the session is authorized to inspect.

use crate::agent_cx::AgentCx;
use crate::ask::{AskHandler, AskOption, AskQuestion, AskRequest};
use crate::error::{Error, Result};
use crate::model::{ContentBlock, TextContent};
use crate::tools::{Tool, ToolEffects, ToolOutput, ToolUpdate};
use async_trait::async_trait;
use futures::future::{Either, select};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::{BTreeMap, VecDeque};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

mod mock;
mod native;
#[cfg(unix)]
mod process;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DisplayInfo {
    pub id: u32,
    pub name: String,
    pub width: u32,
    pub height: u32,
    pub is_primary: bool,
    pub scale_factor: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct WindowInfo {
    pub id: u32,
    pub title: String,
    pub app_name: String,
    pub x: i32,
    pub y: i32,
    pub width: u32,
    pub height: u32,
    pub is_minimized: bool,
    pub is_focused: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AxNode {
    pub role: String,
    pub title: Option<String>,
    pub value: Option<String>,
    pub enabled: bool,
    pub focused: bool,
    pub children: Vec<Self>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComputerAuditEntry {
    pub timestamp_ms: u64,
    pub action: String,
    pub details: Value,
    pub allowed: bool,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct ComputerSettings {
    #[serde(alias = "enableComputer")]
    pub enable_computer: Option<bool>,
    #[serde(alias = "requireApproval")]
    pub require_approval: Option<bool>,
    #[serde(alias = "screenshotDir")]
    pub screenshot_dir: Option<String>,
}

pub struct ComputerTool {
    cwd: PathBuf,
    mock_mode: Option<bool>,
    clipboard_buffer: Mutex<String>,
    audit_log: Mutex<VecDeque<ComputerAuditEntry>>,
    require_approval: bool,
    approval_handler: Option<AskHandler>,
    helpers: BTreeMap<String, PathBuf>,
    state: Arc<asupersync::sync::Mutex<native::State>>,
}

impl ComputerTool {
    pub fn new(cwd: &Path) -> Self {
        Self {
            cwd: cwd.to_path_buf(),
            mock_mode: None,
            clipboard_buffer: Mutex::new(String::new()),
            audit_log: Mutex::new(VecDeque::new()),
            require_approval: true,
            approval_handler: None,
            helpers: BTreeMap::new(),
            state: Arc::new(asupersync::sync::Mutex::new(native::State::default())),
        }
    }

    #[must_use]
    pub const fn with_mock(mut self, mock: bool) -> Self {
        self.mock_mode = Some(mock);
        self
    }

    /// Trusted host policy, not a model-facing argument. The registry forwards
    /// computer.requireApproval here. Disabling it grants session-wide input.
    #[must_use]
    pub const fn with_require_approval(mut self, require: bool) -> Self {
        self.require_approval = require;
        self
    }

    /// Install the host's actual picker. There is no noninteractive recommended
    /// answer fallback: absence, dismissal, errors and malformed replies deny.
    #[must_use]
    pub fn with_approval_handler(mut self, handler: AskHandler) -> Self {
        self.approval_handler = Some(handler);
        self
    }

    /// Override an OS helper from trusted host code (also useful for protocol
    /// fixtures). Tool arguments cannot choose executables or inject a PATH.
    pub fn with_helper_path(mut self, name: &str, path: impl Into<PathBuf>) -> Result<Self> {
        let path = path.into();
        if !native::HELPERS.contains(&name) || !path.is_absolute() {
            return Err(error(
                "helper override requires a known helper and an absolute path",
            ));
        }
        self.helpers.insert(name.to_string(), path);
        Ok(self)
    }

    pub fn get_audit_log(&self) -> Vec<ComputerAuditEntry> {
        self.audit_log
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .iter()
            .cloned()
            .collect()
    }

    fn record_audit(&self, action: &str, args: &Value, allowed: bool, outcome: &str, mock: bool) {
        // Never duplicate typed text, clipboard contents, window titles or
        // screenshots in a long-lived audit log. Retain only bounded metadata.
        let timestamp_ms = u64::try_from(
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_millis(),
        )
        .unwrap_or(u64::MAX);
        let details = json!({
            "outcome": outcome, "mock": mock,
            "window_id": args.get("window_id").and_then(Value::as_u64),
            "display_id": args.get("display_id").and_then(Value::as_u64),
            "text_bytes": args.get("text").and_then(Value::as_str).map(str::len)
        });
        let mut log = self
            .audit_log
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        if log.len() == 256 {
            log.pop_front();
        }
        log.push_back(ComputerAuditEntry {
            timestamp_ms,
            action: action.chars().take(64).collect(),
            details,
            allowed,
        });
    }

    fn is_mock(&self) -> bool {
        self.mock_mode
            .unwrap_or_else(|| std::env::var("PI_COMPUTER_MOCK").as_deref() == Ok("1"))
    }

    async fn authorize(&self, action: &str, args: &Value) -> Result<()> {
        if !self.require_approval || !mutating(action) {
            return Ok(());
        }
        let handler = self.approval_handler.as_ref().ok_or_else(|| error(
            "desktop input requires host approval; no approval handler is installed. The host may install with_approval_handler, or explicitly grant session-wide input with computer.requireApproval=false. Tool arguments cannot grant permission",
        ))?;
        let id = uuid::Uuid::new_v4().to_string();
        let request = AskRequest {
            questions: vec![AskQuestion {
                id: Some(id.clone()),
                header: Some("Desktop permission".into()),
                question: format!(
                    "Allow this desktop action once? It can affect the active application.\n{args}"
                ),
                options: vec![
                    AskOption {
                        label: "Deny".into(),
                        description: None,
                    },
                    AskOption {
                        label: "Allow once".into(),
                        description: None,
                    },
                ],
                recommended: Some(0),
                multi: false,
            }],
        };
        let response = handler(request).await?;
        if response.dismissed || response.answers.len() != 1 {
            return Err(error("desktop action was not approved"));
        }
        let answer = &response.answers[0];
        if answer.question_id != id
            || answer.other.is_some()
            || answer.selected.as_slice() != ["Allow once"]
        {
            return Err(error("desktop action was not approved"));
        }
        Ok(())
    }
}

#[async_trait]
#[allow(clippy::unnecessary_literal_bound)]
impl Tool for ComputerTool {
    fn name(&self) -> &str {
        "computer"
    }
    fn label(&self) -> &str {
        "Computer"
    }
    fn description(&self) -> &str {
        "Inspect the authorized desktop, capture actual screenshots, and perform OS input/clipboard actions. Native capabilities depend on the desktop backend and installed helpers. Input requires trusted host approval; unavailable operations fail explicitly."
    }
    fn parameters(&self) -> Value {
        json!({
            "type": "object", "required": ["action"], "additionalProperties": false,
            "properties": {
                "action": {"type":"string", "enum":["list_displays","list_windows","screenshot","mouse_move","mouse_click","mouse_drag","key_type","key_press","ax_tree","clipboard_read","clipboard_write","scroll","focus_window"]},
                "display_id": {"type":"integer", "minimum":1, "description":"Monitor ID from list_displays"},
                "window_id": {"type":"integer", "minimum":1, "description":"Window ID from list_windows; input with this field requires that window to be focused"},
                "x": {"type":"integer", "description":"Desktop pixel X coordinate"},
                "y": {"type":"integer", "description":"Desktop pixel Y coordinate"},
                "button": {"type":"string", "enum":["left","right","middle"]},
                "text": {"type":"string", "maxLength":4096, "description":"Literal input/clipboard text, never executed as helper commands"},
                "key": {"type":"string", "description":"One key/chord, e.g. Return, Tab, Escape, Ctrl+C"},
                "direction": {"type":"string", "enum":["up","down","left","right"]},
                "amount": {"type":"integer", "minimum":1, "maximum":100},
                "output_path": {"type":"string", "description":"New PNG destination; existing files are never overwritten"},
                "timeout_ms": {"type":"integer", "minimum":1, "maximum":120_000, "default":30_000}
            }
        })
    }
    fn effects(&self) -> ToolEffects {
        ToolEffects::read()
            .union(ToolEffects::write())
            .union(ToolEffects::process())
    }

    async fn execute(
        &self,
        _tool_call_id: &str,
        args: Value,
        _on_update: Option<Box<dyn Fn(ToolUpdate) + Send + Sync>>,
    ) -> Result<ToolOutput> {
        let action = args
            .get("action")
            .and_then(Value::as_str)
            .unwrap_or("unknown");
        let mock = self.is_mock();
        let duration: Duration = match native::validate(&args) {
            Ok(duration) => duration,
            Err(failure) => {
                self.record_audit(action, &args, false, "invalid", mock);
                return Err(failure);
            }
        };
        if mock {
            let result = mock::execute(self, &args);
            self.record_audit(
                action,
                &args,
                true,
                if result.is_ok() { "success" } else { "error" },
                true,
            );
            return result;
        }
        let owner = AgentCx::for_current_or_request();
        let mut allowed = false;
        let operation = async {
            native::check_owner(&owner)?;
            self.authorize(action, &args).await?;
            allowed = true;
            // This owned guard is Send, unlike asupersync's borrowed guard.
            let mut state =
                asupersync::sync::OwnedMutexGuard::lock(Arc::clone(&self.state), owner.cx())
                    .await
                    .map_err(|_| error("desktop session lock cancelled"))?;
            native::execute(&owner, &self.cwd, &self.helpers, &mut state, &args).await
        };
        let cancelled = async {
            let (sender, mut receiver) = asupersync::channel::oneshot::channel::<()>();
            let _ = receiver.recv(owner.cx()).await;
            drop(sender);
        };
        let watchdog = async {
            match select(Box::pin(owner.time().sleep(duration)), Box::pin(cancelled)).await {
                Either::Left(_) => {
                    "desktop action timed out; OS side effects may already have occurred"
                }
                Either::Right(_) => {
                    "desktop action cancelled; OS side effects may already have occurred"
                }
            }
        };
        let result = match select(Box::pin(operation), Box::pin(watchdog)).await {
            Either::Left((result, _)) => result,
            Either::Right((message, pending)) => {
                drop(pending);
                Err(error(message))
            }
        };
        self.record_audit(
            action,
            &args,
            allowed,
            if result.is_ok() { "success" } else { "error" },
            false,
        );
        result
    }
}

fn mutating(action: &str) -> bool {
    matches!(
        action,
        "mouse_move"
            | "mouse_click"
            | "mouse_drag"
            | "key_type"
            | "key_press"
            | "clipboard_write"
            | "scroll"
            | "focus_window"
    )
}
fn error(message: impl Into<String>) -> Error {
    Error::tool("computer", message)
}
fn output(text: String, mut details: Value, mock: bool) -> ToolOutput {
    details["mock"] = json!(mock);
    ToolOutput {
        content: vec![ContentBlock::Text(TextContent::new(text))],
        details: Some(details),
        is_error: false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn model_flags_cannot_authorize_input() {
        assert!(
            native::validate(&json!({"action":"key_type","text":"test","confirmed":true})).is_err()
        );
        let tool = ComputerTool::new(Path::new("."));
        assert!(
            futures::executor::block_on(tool.authorize("key_type", &json!({"text":"test"})))
                .is_err()
        );
    }
    #[test]
    fn audit_is_bounded_and_excludes_private_payloads() {
        let tool = ComputerTool::new(Path::new("."));
        for _ in 0..300 {
            tool.record_audit(
                "key_type",
                &json!({"text":"private-secret"}),
                false,
                "denied",
                false,
            );
        }
        let entries = tool.get_audit_log();
        assert_eq!(entries.len(), 256);
        assert!(!entries[0].allowed);
        assert!(
            !serde_json::to_string(&entries)
                .unwrap()
                .contains("private-secret")
        );
    }
    #[test]
    fn only_exact_host_selection_approves() {
        use crate::ask::{AskAnswer, AskResponse};
        for selected in ["Deny", "Allow once"] {
            let handler: AskHandler = Arc::new(move |request| {
                Box::pin(async move {
                    Ok(AskResponse {
                        dismissed: false,
                        answers: vec![AskAnswer {
                            question_id: request.questions[0].id.clone().unwrap(),
                            selected: vec![selected.into()],
                            other: None,
                        }],
                    })
                })
            });
            let tool = ComputerTool::new(Path::new(".")).with_approval_handler(handler);
            assert_eq!(
                futures::executor::block_on(tool.authorize("key_press", &json!({"key":"Return"})))
                    .is_ok(),
                selected == "Allow once"
            );
        }
    }

    #[test]
    fn native_failure_never_publishes_a_fixture_screenshot() {
        let dir = tempfile::tempdir().unwrap();
        let tool = ComputerTool::new(dir.path())
            .with_mock(false)
            .with_helper_path("scrot", dir.path().join("missing-scrot"))
            .unwrap();
        let runtime = asupersync::runtime::RuntimeBuilder::current_thread()
            .build()
            .unwrap();
        let result = runtime.block_on(tool.execute(
            "missing-native",
            json!({"action":"screenshot","output_path":"must-not-exist.png"}),
            None,
        ));
        assert!(result.is_err());
        assert!(!dir.path().join("must-not-exist.png").exists());
        assert_eq!(tool.get_audit_log()[0].details["outcome"], "error");
    }

    #[test]
    fn tool_boundary_enforces_approval_before_any_native_input() {
        let dir = tempfile::tempdir().unwrap();
        let tool = ComputerTool::new(dir.path())
            .with_mock(false)
            .with_helper_path("xdotool", dir.path().join("must-not-run"))
            .unwrap();
        let runtime = asupersync::runtime::RuntimeBuilder::current_thread()
            .build()
            .unwrap();
        let result = runtime.block_on(tool.execute(
            "denied-input",
            json!({"action":"key_type","text":"private-secret"}),
            None,
        ));
        let failure = result.unwrap_err();
        assert!(failure.to_string().contains("host approval"));
        let log = tool.get_audit_log();
        assert!(!log[0].allowed);
        assert!(
            !serde_json::to_string(&log)
                .unwrap()
                .contains("private-secret")
        );
    }
}