adk-computer-use 2.1.0

ADK-Rust graph, auth, and wire contracts for computer-use-mcp
Documentation
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
use adk_agent::LlmAgentBuilder;
use adk_computer_use::{
    ComputerUseMcpConfig, ComputerUseMcpRuntime, ComputerUseRuntime, ScopeAuthorizer,
    TraceCorrelation, build_reference_graph_with_checkpointer,
};
use adk_core::{Agent, Content, Part};
use adk_graph::{ExecutionConfig, GraphError, MemoryCheckpointer, State};
use adk_model::GeminiModel;
use adk_runner::Runner;
use adk_session::{CreateRequest, InMemorySessionService, SessionService};
use adk_tool::McpToolset;
use chrono::Utc;
use futures::StreamExt;
use rmcp::{ServiceExt, transport::TokioChildProcess};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::process::Command;
use tokio::time::{sleep, timeout};

struct DemoPathCleanup(Vec<PathBuf>);

impl Drop for DemoPathCleanup {
    fn drop(&mut self) {
        for path in &self.0 {
            if path.is_dir() {
                let _ = fs::remove_dir_all(path);
            } else {
                let _ = fs::remove_file(path);
            }
        }
    }
}

#[path = "../support/mod.rs"]
mod support;
use support::{object, output, spawn_pip, supervisor_dir};

fn nested<'a>(value: &'a Value, key: &str) -> Option<&'a Value> {
    output(value).get(key).or_else(|| output(value).get("output").and_then(|value| value.get(key)))
}

async fn plan_fields(prompt: &str) -> Result<Value, Box<dyn std::error::Error>> {
    let api_key = std::env::var("GOOGLE_API_KEY")
        .or_else(|_| std::env::var("GEMINI_API_KEY"))
        .map_err(|_| "GOOGLE_API_KEY or GEMINI_API_KEY is required")?;
    let model_name =
        std::env::var("COMPUTER_USE_PLANNER_MODEL").unwrap_or_else(|_| "gemini-2.5-flash".into());
    let schema = json!({
        "type": "object",
        "required": ["name", "project"],
        "properties": {
            "name": { "type": "string", "minLength": 1, "maxLength": 120 },
            "project": { "type": "string", "minLength": 1, "maxLength": 120 }
        }
    });
    let agent: Arc<dyn Agent> = Arc::new(
        LlmAgentBuilder::new("computer-use-form-planner")
            .description("Schema-constrained planner for the governed form showcase")
            .instruction(
                "Extract the exact public demonstration Name and Project requested by the user. \
                 Return only schema-valid JSON. Do not add fields, tools, targets, or secrets. \
                 The downstream ADK graph and runtime own approval and execution.",
            )
            .model(Arc::new(GeminiModel::new(&api_key, &model_name)?))
            .output_schema(schema)
            .output_max_retries(2)
            .temperature(0.0)
            .build()?,
    );
    let sessions: Arc<dyn SessionService> = Arc::new(InMemorySessionService::new());
    sessions
        .create(CreateRequest {
            app_name: "computer-use-form".into(),
            user_id: "local-operator".into(),
            session_id: Some("form-planner".into()),
            state: HashMap::new(),
        })
        .await?;
    let runner = Runner::builder()
        .app_name("computer-use-form")
        .agent(agent)
        .session_service(sessions)
        .build()?;
    let mut stream = runner
        .run_str("local-operator", "form-planner", Content::new("user").with_text(prompt))
        .await?;
    let mut response = String::new();
    while let Some(event) = stream.next().await {
        if let Some(content) = event?.llm_response.content {
            for part in content.parts {
                if let Part::Text { text } = part {
                    response.push_str(&text);
                }
            }
        }
    }
    let value: Value = serde_json::from_str(response.trim())?;
    if value.get("name").and_then(Value::as_str).is_none()
        || value.get("project").and_then(Value::as_str).is_none()
    {
        return Err("planner did not return the required public form fields".into());
    }
    Ok(value)
}

fn build_form_app(root: &Path) -> Result<PathBuf, Box<dyn std::error::Error>> {
    let app = root.join("ADK Form Showcase.app");
    let contents = app.join("Contents");
    let executable_dir = contents.join("MacOS");
    fs::create_dir_all(&executable_dir)?;
    fs::write(
        contents.join("Info.plist"),
        r#"<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>CFBundleExecutable</key><string>ADKFormShowcase</string>
<key>CFBundleIdentifier</key><string>ai.zavora.adk-form-showcase</string>
<key>CFBundleName</key><string>ADK Form Showcase</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>LSMinimumSystemVersion</key><string>13.0</string>
</dict></plist>"#,
    )?;
    let source = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("examples")
        .join("macos")
        .join("macos_form_showcase.swift");
    let executable = executable_dir.join("ADKFormShowcase");
    let result = std::process::Command::new("swiftc")
        .arg(source)
        .args(["-o"])
        .arg(&executable)
        .args(["-framework", "AppKit"])
        .status()?;
    if !result.success() {
        return Err("swiftc failed to build the local form showcase".into());
    }
    Ok(app)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    if cfg!(not(target_os = "macos")) {
        return Err("the live native form showcase currently targets macOS".into());
    }
    let prompt = std::env::args().skip(1).collect::<Vec<_>>().join(" ");
    let prompt = if prompt.is_empty() {
        "Use the public demo Name 'James' and Project 'computer-use showcase'.".to_string()
    } else {
        prompt
    };
    println!("PROMPT: {prompt}");
    let fields = plan_fields(&prompt).await?;
    println!("PLANNED_PUBLIC_FIELDS: {}", serde_json::to_string(&fields)?);

    let run_root = std::env::temp_dir().join(format!("adk-form-{}", uuid::Uuid::new_v4()));
    fs::create_dir_all(&run_root)?;
    let app = build_form_app(&run_root)?;
    let socket = PathBuf::from(format!("/tmp/adk-{}.sock", uuid::Uuid::new_v4().simple()));
    let _path_cleanup = DemoPathCleanup(vec![socket.clone(), run_root.clone()]);
    let mut form = Command::new(app.join("Contents/MacOS/ADKFormShowcase"));
    let mut form = form.kill_on_drop(true).spawn()?;

    let entrypoint = std::env::var("COMPUTER_USE_MCP_ENTRYPOINT")
        .map_err(|_| "COMPUTER_USE_MCP_ENTRYPOINT must point to the local dist/server.js")?;
    let principal =
        std::env::var("COMPUTER_USE_PRINCIPAL_ID").unwrap_or_else(|_| "adk-local-operator".into());
    // Darwin limits AF_UNIX paths to roughly 104 bytes. Keep the control
    // socket short even when the temporary app bundle lives in a long path.
    let supervisor_token = format!("{}{}", uuid::Uuid::new_v4(), uuid::Uuid::new_v4());
    let mut server = Command::new(std::env::var("NODE").unwrap_or_else(|_| "node".into()));
    server
        .arg(&entrypoint)
        .env("COMPUTER_USE_V8", "true")
        .env("COMPUTER_USE_ACTIVE_PROFILE", "v8-safe")
        .env("COMPUTER_USE_PRINCIPAL_ID", &principal)
        .env("COMPUTER_USE_V8_CONFIRM_TOOLS", "fill_form")
        .env("COMPUTER_USE_RUNTIME_DEBUG", "true")
        .env("COMPUTER_USE_SUPERVISOR_SOCKET", &socket)
        .env("COMPUTER_USE_SUPERVISOR_TOKEN", &supervisor_token)
        .env("COMPUTER_USE_SUPERVISOR_FRAMES", "true");
    let client = ().serve(TokioChildProcess::new(server)?).await?;
    let toolset = Arc::new(McpToolset::new(client).with_name("computer-use-form"));
    let started =
        toolset.call_tool_value("start_session", object(json!({ "objective": prompt }))?).await?;
    let session_id = output(&started)
        .get("session")
        .and_then(|value| value.get("sessionId"))
        .and_then(Value::as_str)
        .ok_or("start_session did not return sessionId")?
        .to_string();

    let bootstrap = Arc::new(ComputerUseMcpRuntime::new(
        toolset.clone(),
        ComputerUseMcpConfig {
            session_id: session_id.clone(),
            expected_principal_id: principal.clone(),
            capability_tool: "fill_form".into(),
            target_app: None,
            target_window_id: None,
            correlation: TraceCorrelation::default(),
        },
    ));
    let target_window = timeout(Duration::from_secs(20), async {
        loop {
            let observed = bootstrap
                .observe_tool("list_windows", json!({}))
                .await
                .map_err(|e| e.to_string())?;
            if let Some(window) =
                nested(&observed, "windows").and_then(Value::as_array).and_then(|windows| {
                    windows.iter().find(|window| {
                        window.get("title").and_then(Value::as_str) == Some("ADK Form Showcase")
                    })
                })
            {
                return Ok::<Value, String>(window.clone());
            }
            sleep(Duration::from_millis(250)).await;
        }
    })
    .await
    .map_err(|_| "timed out discovering the showcase window")??;
    let window_id = target_window
        .get("windowId")
        .and_then(Value::as_u64)
        .ok_or("showcase window did not expose windowId")?;
    let app_id = target_window
        .get("bundleId")
        .and_then(Value::as_str)
        .ok_or("showcase window did not expose bundleId")?
        .to_string();
    let pid = target_window.get("pid").and_then(Value::as_u64).ok_or("window PID missing")?;
    println!("TARGET: app={app_id} pid={pid} window={window_id}");

    let mut pip = spawn_pip(
        &supervisor_dir(&entrypoint)?,
        &socket,
        &supervisor_token,
        &principal,
        &session_id,
    )?;
    let action_id = uuid::Uuid::new_v4().to_string();
    let proposed_action = json!({
        "action_id": action_id,
        "expires_in_ms": 300_000,
        "execution_group_id": "adk-form-showcase",
        "agent_id": "sole-form-executor",
        "tool": "fill_form",
        "arguments": {
            "window_id": window_id,
            "focus_strategy": "prepare_display",
            "fields": [
                { "role": "AXTextField", "label": "Name", "value": fields["name"] },
                { "role": "AXTextField", "label": "Project", "value": fields["project"] }
            ]
        },
        "mode": "foreground",
        "data_labels": ["public"],
        "target": {
            "platform": "darwin",
            "app_id": app_id,
            "pid": pid,
            "window_id": window_id,
            "bounds": target_window["bounds"],
            "observation_id": uuid::Uuid::new_v4().to_string(),
            "confidence": 1.0,
            "captured_at": Utc::now().to_rfc3339()
        }
    });
    println!("PLANNED_ACTION: {}", serde_json::to_string(&proposed_action)?);

    let runtime = Arc::new(ComputerUseMcpRuntime::new(
        toolset.clone(),
        ComputerUseMcpConfig {
            session_id: session_id.clone(),
            expected_principal_id: principal.clone(),
            capability_tool: "fill_form".into(),
            target_app: Some(app_id),
            target_window_id: Some(window_id),
            correlation: TraceCorrelation {
                adk_session_id: Some("adk-live-form".into()),
                adk_invocation_id: Some("adk-live-form-invocation".into()),
                adk_graph_thread_id: Some("adk-live-form-graph".into()),
                trace_id: None,
            },
        },
    ));
    let graph = build_reference_graph_with_checkpointer(
        runtime.clone(),
        Arc::new(ScopeAuthorizer::from_verified_identity(
            principal,
            None,
            ["computer:plan", "computer:execute:foreground"],
        )),
        Some(Arc::new(MemoryCheckpointer::new())),
    )?;
    let mut input = State::new();
    input.insert("proposed_action".into(), proposed_action.clone());
    let interrupted = match graph.invoke(input, ExecutionConfig::new("adk-live-form-graph")).await {
        Err(GraphError::Interrupted(interrupted)) => interrupted,
        Ok(_) => return Err("form action unexpectedly bypassed approval".into()),
        Err(error) => return Err(error.into()),
    };
    let preview = interrupted
        .state
        .get("preview")
        .cloned()
        .ok_or("interrupted graph did not retain its preview")?;
    let action_digest = preview
        .pointer("/envelope/argsDigest")
        .and_then(Value::as_str)
        .ok_or("preview action digest missing")?
        .to_string();
    let policy_digest = preview
        .pointer("/policy/policyDigest")
        .and_then(Value::as_str)
        .ok_or("preview policy digest missing")?
        .to_string();
    println!(
        "PRE_LEASE_INTERRUPT_PROOF: {}",
        serde_json::to_string(&json!({
            "checkpoint_id": interrupted.checkpoint_id,
            "route": interrupted.state.get("route"),
            "action_digest": action_digest,
            "policy_digest": policy_digest,
            "reservation_acquired": interrupted.state.contains_key("reservation"),
            "lease_acquired": interrupted.state.contains_key("lease"),
            "receipt_created": interrupted.state.contains_key("receipt")
        }))?
    );
    println!("APPROVAL_INTERRUPT: review the action in the PiP window");
    println!("APPROVAL_OPTIONS: exact action or same fields (10 uses / 2 minutes)");

    let approval_timeout = std::env::var("COMPUTER_USE_FORM_APPROVAL_TIMEOUT_SECONDS")
        .ok()
        .and_then(|value| value.parse::<u64>().ok())
        .filter(|value| (30..=900).contains(value))
        .unwrap_or(300);
    timeout(Duration::from_secs(approval_timeout), async {
        let mut after = 0_u64;
        loop {
            let events = toolset
                .call_tool_value(
                    "get_session_events",
                    object(json!({
                        "session_id": session_id,
                        "after_sequence": after,
                        "limit": 100
                    }))?,
                )
                .await?;
            if let Some(items) = nested(&events, "events").and_then(Value::as_array) {
                for event in items {
                    after = after.max(event.get("sequence").and_then(Value::as_u64).unwrap_or(0));
                    if event.get("type").and_then(Value::as_str) == Some("action.approved")
                        && event.get("actionId").and_then(Value::as_str) == Some(&action_id)
                    {
                        return Ok::<(), Box<dyn std::error::Error>>(());
                    }
                }
            }
            sleep(Duration::from_millis(250)).await;
        }
    })
    .await
    .map_err(|_| "approval timed out")??;

    let approved_preview = runtime.preview_action(proposed_action.clone()).await?;
    if !approved_preview.executable {
        return Err("the runtime did not recognize the runtime-held PiP approval".into());
    }
    let mut resume = State::new();
    resume.insert(
        "approval".into(),
        json!({
            "actionDigest": action_digest,
            "policyDigest": policy_digest,
            "runtimeApproved": true
        }),
    );
    let result = graph
        .invoke(
            resume,
            ExecutionConfig::new("adk-live-form-graph")
                .with_resume_from(&interrupted.checkpoint_id),
        )
        .await?;
    println!(
        "GRAPH_RESULT: {}",
        serde_json::to_string(&json!({
            "observations_joined": result.get("observations_joined"),
            "route": result.get("route"),
            "receipt_status": result.get("receipt").and_then(|value| value.get("status")),
            "receipt_id": result.get("receipt").and_then(|value| value.get("receiptId")),
            "resumed_checkpoint_id": interrupted.checkpoint_id,
            "original_action_id": action_id,
            "receipt_action_id": result.get("receipt").and_then(|value| value.get("actionId")),
            "verified": result.get("verified"),
            "runtime_held_approval": true
        }))?
    );
    println!("MACOS_VERIFICATION: the runtime independently read back both form fields");
    sleep(Duration::from_secs(3)).await;
    let _ = pip.kill().await;
    let _ = form.kill().await;
    toolset.cancellation_token().await.cancel();
    Ok(())
}