iphone-cli 0.1.5

Let AI agents read and operate any app on a real iPhone through the accessibility tree. No XCUITest, WebDriverAgent or Xcode signing.
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
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
#![allow(clippy::result_large_err)]

use std::{io::Read, time::Instant};

use clap::{Parser, Subcommand};
use iphone_cli::{
    client, clock, connect, daemon, devices, diagnose, events, fields, human,
    mcp,
    reply::{Fail, envelope},
    script, setup,
};
use serde_json::{Map, Value, json};

#[derive(Parser)]
#[command(
    name = "iph",
    version,
    about = "Read and operate any app on a real iPhone through its accessibility tree",
    long_about = "Read and operate any app on a real iPhone through its accessibility tree.\n\
                  No XCUITest, WebDriverAgent or Xcode signing. Output is JSON; add --human for people.\n\
                  Exit codes: 0 ok, 1 nothing was sent, 2 outcome unknown (check the screen)."
)]
struct Cli {
    /// Device to use. Defaults to IPH_UDID, config.toml, or the only connected iPhone.
    #[arg(long, global = true)]
    udid: Option<String>,
    /// Print for people instead of JSON.
    #[arg(long, global = true)]
    human: bool,
    /// Accepted for symmetry; JSON is already the default.
    #[arg(long, global = true, hide = true)]
    json: bool,
    #[command(subcommand)]
    command: Cmd,
}

#[derive(Subcommand)]
enum Cmd {
    /// List connected iPhones.
    Devices,
    /// Verify and save the selected paired iPhone's IP when automatic discovery fails.
    Connect(connect::Args),
    /// Save connection diagnostics and optional reproduction output for a GitHub issue.
    Diagnose(diagnose::Args),
    /// Walk through the one-time preparation of a phone.
    Setup {
        /// Enable disabled Wi-Fi connection/debugging flags over USB.
        #[arg(long)]
        fix_wifi: bool,
    },
    /// Check that the phone is ready; says what to do for each problem.
    Doctor {
        /// Skip the check that sends a real touch (it scrolls Settings down and back).
        #[arg(long)]
        no_touch_test: bool,
        /// Enable disabled Wi-Fi connection/debugging flags over USB.
        #[arg(long)]
        fix_wifi: bool,
    },
    /// List the elements on screen.
    Read {
        /// Only the foreground app's elements.
        #[arg(long)]
        app: bool,
        /// Include elements outside the screen.
        #[arg(long)]
        all: bool,
        /// Wait for identifiers (about 0.6 s more).
        #[arg(long)]
        full: bool,
        /// Attach every numbered accessibility attribute.
        #[arg(long)]
        raw: bool,
        /// Accept a reading up to this many milliseconds old.
        #[arg(long)]
        max_age: Option<u64>,
    },
    /// Find elements matching a selector.
    Find {
        selector: String,
        #[arg(long)]
        all: bool,
    },
    /// Tap an element (selector) or a point (x,y).
    Tap {
        target: String,
        /// Hold for this many milliseconds.
        #[arg(long)]
        long: Option<u64>,
        #[arg(long)]
        double: bool,
        /// Read the screen once right after the tap instead of waiting for it to settle.
        #[arg(long)]
        no_wait: bool,
    },
    /// Swipe: up, down, left, right, or x1,y1,x2,y2.
    Swipe {
        direction: String,
        /// Milliseconds the movement takes.
        #[arg(long)]
        duration: Option<u64>,
        /// Slow to a stop before lifting (a drag) instead of flicking.
        #[arg(long)]
        drag: bool,
    },
    /// Pinch in or out, or turn: two fingers around the middle of the screen or a target.
    Pinch {
        /// `in` or `out`; or give `--scale` and/or `--rotate` instead.
        direction: Option<String>,
        /// End span over start span, 0.25..4 (above 1 spreads the fingers).
        #[arg(long)]
        scale: Option<f64>,
        /// Degrees, positive clockwise, -180..180.
        #[arg(long, allow_negative_numbers = true)]
        rotate: Option<f64>,
        /// A selector or x,y where the fingers meet. Default: the middle of the screen.
        #[arg(long)]
        at: Option<String>,
        /// Milliseconds the fingers move (default 500).
        #[arg(long)]
        duration: Option<u64>,
    },
    /// Scroll the content up or down, optionally until an element shows.
    Scroll {
        direction: String,
        #[arg(long)]
        until: Option<String>,
        #[arg(long)]
        max: Option<u32>,
    },
    /// Type text into the focused field (pasted, so any language works).
    Type {
        text: String,
        /// Replace what the field holds.
        #[arg(long)]
        clear: bool,
        /// Press Return if the input's effect was observed; otherwise withhold it.
        #[arg(long)]
        submit: bool,
    },
    /// Press a key: return, esc, tab, cmd+a …
    Key { key: String },
    /// Press a hardware button: home, lock, volume_up, volume_down.
    Button { button: String },
    /// Launch an app by bundle id or name.
    Launch {
        app: String,
        /// Quit it first so it starts from its first screen.
        #[arg(long)]
        restart: bool,
        /// Environment variable for the app's process, repeatable: --env NAME=value. Starts the app anew.
        #[arg(long = "env", value_name = "K=V")]
        env: Vec<String>,
        /// Launch arguments for the app, after `--`: iph launch <app> -- -key value. Starts the app anew.
        #[arg(last = true)]
        arguments: Vec<String>,
    },
    /// List installed apps.
    Apps,
    /// Save a screenshot (PNG).
    Screenshot {
        #[arg(short, long)]
        output: Option<String>,
    },
    /// Run a JSON array of steps from a file or stdin (-).
    Batch { file: String },
    /// Run JavaScript from a file or stdin (-): read(), tap(), scroll() … as functions.
    Script {
        file: String,
        /// Argument the script reads as `args.name`, repeatable: --arg name=value
        #[arg(long = "arg", value_name = "K=V")]
        args: Vec<String>,
    },
    /// Run a saved script by name (see `iph scripts`).
    Run {
        name: String,
        /// Argument the script reads as `args.name`, repeatable: --arg name=value
        #[arg(long = "arg", value_name = "K=V")]
        args: Vec<String>,
    },
    /// List saved scripts.
    Scripts,
    /// Serve the same commands as MCP tools over stdio.
    Mcp {
        /// Offer only these tools (comma separated, e.g. read,find,run).
        #[arg(long, value_delimiter = ',')]
        tools: Vec<String>,
    },
    /// Do Not Disturb on the phone: on, off (back to the Focus that was on), status.
    Dnd { action: String },
    /// Stop the background daemon for this phone.
    Stop,
    /// Internal: the resident process.
    #[command(hide = true)]
    Daemon,
    /// Internal: send a raw daemon command (recovery tests).
    #[command(hide = true)]
    Debug { command: String },
}

fn print(value: &Value, human_out: bool, cmd: &str) {
    if human_out {
        println!("{}", human::render(cmd, value));
    } else if std::io::IsTerminal::is_terminal(&std::io::stdout()) {
        println!("{}", serde_json::to_string_pretty(value).unwrap());
    } else {
        println!("{value}");
    }
}

fn exit_code(value: &Value) -> i32 {
    if value["ok"] == true {
        return 0;
    }
    match value["outcome"].as_str() {
        Some("unknown") => 2,
        _ => 1,
    }
}

/// `--arg name=value` pairs as the object a script reads as `args`. Values
/// stay text; a script that wants a number says `Number(args.n)`.
fn script_args(pairs: &[String]) -> Result<Map<String, Value>, Fail> {
    let mut map = Map::new();
    for pair in pairs {
        let Some((k, v)) = pair.split_once('=') else {
            return Err(Fail::invalid(format!("--arg expects name=value, got `{pair}`")));
        };
        map.insert(k.to_string(), json!(v));
    }
    Ok(map)
}

fn swipe_args(direction: &str, duration: Option<u64>, drag: bool) -> Result<Value, Fail> {
    let nums: Vec<f64> = direction
        .split(',')
        .filter_map(|p| p.trim().parse::<f64>().ok())
        .collect();
    let mut v = if direction.contains(',') {
        if nums.len() != 4 {
            return Err(Fail::invalid("swipe takes a direction or x1,y1,x2,y2"));
        }
        json!({ "from": [nums[0], nums[1]], "to": [nums[2], nums[3]] })
    } else {
        json!({ "direction": direction })
    };
    if let Some(d) = duration {
        v["duration_ms"] = json!(d);
    }
    v["drag"] = json!(drag);
    Ok(v)
}

fn launch_args(app: &str, restart: bool, env: &[String], arguments: &[String]) -> Result<Value, Fail> {
    let mut environment = serde_json::Map::new();
    for pair in env {
        let (name, value) = pair
            .split_once('=')
            .filter(|(name, _)| !name.is_empty())
            .ok_or_else(|| Fail::invalid(format!("--env takes NAME=value, got \"{pair}\"")))?;
        environment.insert(name.to_string(), json!(value));
    }
    Ok(json!({ "app": app, "restart": restart, "arguments": arguments, "environment": environment }))
}

fn main() {
    let cli = Cli::parse();
    events::init_tracing();
    // The command futures nest deeply; give the thread that polls them room.
    let worker = std::thread::Builder::new()
        .name("iph-main".into())
        .stack_size(64 << 20)
        .spawn(move || {
            let runtime = tokio::runtime::Builder::new_multi_thread()
                .enable_all()
                .thread_stack_size(16 << 20)
                .build()
                .expect("tokio runtime");
            let code = runtime.block_on(run(cli));
            // Background tasks (tunnel packet pump) must not hold the process open.
            runtime.shutdown_background();
            code
        })
        .expect("spawn main thread");
    std::process::exit(worker.join().unwrap_or(1));
}

async fn run(cli: Cli) -> i32 {
    let started = Instant::now();
    let human_out = cli.human;

    // Commands that need no phone.
    match &cli.command {
        Cmd::Diagnose(args) => {
            // Run one finite iph command without a shell. Reject recursive
            // collectors and interactive/long-lived commands.
            if !args.command.is_empty() {
                let child = Cli::try_parse_from(std::iter::once("iph".to_string()).chain(args.command.iter().cloned()));
                if child.is_ok_and(|c| matches!(c.command, Cmd::Diagnose(_) | Cmd::Daemon | Cmd::Mcp { .. } | Cmd::Setup { .. })) {
                    let v = envelope(Err(Fail::invalid("diagnose can capture a finite iph command; diagnose, daemon, mcp and setup cannot be nested")), started);
                    print(&v, human_out, "diagnose");
                    return 1;
                }
            }
            let v = envelope(diagnose::run(args.clone(), cli.udid.clone()).await, started);
            print(&v, human_out, "diagnose");
            return exit_code(&v);
        }
        Cmd::Scripts => {
            let v = envelope(script::cmd_scripts(), started);
            print(&v, human_out, "scripts");
            return exit_code(&v);
        }
        Cmd::Devices => {
            let v = envelope(devices::cmd_devices(cli.udid.clone()).await, started);
            print(&v, human_out, "devices");
            return exit_code(&v);
        }
        _ => {}
    }

    let udid = match client::resolve_udid(cli.udid.clone()).await {
        Ok(u) => u,
        Err(f) => {
            let v = envelope(Err(f), started);
            print(&v, human_out, "error");
            return exit_code(&v);
        }
    };

    let (cmd, args): (&str, Value) = match cli.command {
        Cmd::Connect(args) => {
            let v = envelope(connect::run(&udid, args).await, started);
            print(&v, human_out, "connect");
            return exit_code(&v);
        }
        Cmd::Daemon => {
            return match daemon::run(udid).await {
                Ok(()) => 0,
                Err(e) => {
                    eprintln!("iph daemon: {e:#}");
                    1
                }
            };
        }
        Cmd::Mcp { tools } => {
            return match mcp::serve(udid, tools).await {
                Ok(()) => 0,
                Err(e) => {
                    eprintln!("iph mcp: {e:#}");
                    1
                }
            };
        }
        Cmd::Setup { fix_wifi } => return setup::run(&udid, fix_wifi).await,
        Cmd::Stop => {
            let last = client::stop_daemon(&udid).await;
            let v = envelope(Ok(fields! { "stopped": last.is_some() }), started);
            print(&v, human_out, "stop");
            return 0;
        }
        Cmd::Debug { command } => {
            let v = client::request(&udid, &command, Value::Null).await;
            print(&v, human_out, "debug");
            return exit_code(&v);
        }
        Cmd::Doctor { no_touch_test, fix_wifi } => ("doctor", json!({ "no_touch_test": no_touch_test, "fix_wifi": fix_wifi })),
        Cmd::Read { app, all, full, raw, max_age } => (
            "read",
            json!({ "app": app, "all": all, "full": full, "raw": raw, "max_age_ms": max_age }),
        ),
        Cmd::Find { selector, all } => ("find", json!({ "selector": selector, "all": all })),
        Cmd::Tap { target, long, double, no_wait } => {
            ("tap", json!({ "target": target, "long_ms": long, "double": double, "no_wait": no_wait }))
        }
        Cmd::Swipe { direction, duration, drag } => match swipe_args(&direction, duration, drag) {
            Ok(v) => ("swipe", v),
            Err(f) => {
                let v = envelope(Err(f), started);
                print(&v, human_out, "swipe");
                return exit_code(&v);
            }
        },
        Cmd::Pinch { direction, scale, rotate, at, duration } => (
            "pinch",
            json!({ "direction": direction, "scale": scale, "rotate": rotate, "at": at, "duration_ms": duration }),
        ),
        Cmd::Scroll { direction, until, max } => (
            "scroll",
            json!({ "direction": direction, "until": until, "max": max }),
        ),
        Cmd::Type { text, clear, submit } => {
            ("type", json!({ "text": text, "clear": clear, "submit": submit }))
        }
        Cmd::Key { key } => ("key", json!({ "key": key })),
        Cmd::Button { button } => ("button", json!({ "button": button })),
        Cmd::Dnd { action } => ("dnd", json!({ "action": action })),
        Cmd::Launch { app, restart, env, arguments } => match launch_args(&app, restart, &env, &arguments) {
            Ok(v) => ("launch", v),
            Err(f) => {
                let v = envelope(Err(f), started);
                print(&v, human_out, "launch");
                return exit_code(&v);
            }
        },
        Cmd::Apps => ("apps", Value::Null),
        Cmd::Screenshot { output } => {
            let name = output.unwrap_or_else(|| {
                format!("iph-screenshot-{}.png", clock::now_utc().replace([':', '-'], ""))
            });
            // The daemon writes the file, so the path must not depend on its cwd.
            let path = std::path::absolute(&name)
                .map(|p| p.display().to_string())
                .unwrap_or(name);
            ("screenshot", json!({ "path": path }))
        }
        Cmd::Batch { file } => {
            let text = if file == "-" {
                let mut s = String::new();
                std::io::stdin().read_to_string(&mut s).map(|_| s)
            } else {
                std::fs::read_to_string(&file)
            };
            let steps = text
                .map_err(|e| Fail::invalid(format!("{file}: {e}")))
                .and_then(|t| {
                    serde_json::from_str::<Value>(&t)
                        .map_err(|e| Fail::invalid(format!("{file}: not JSON: {e}")))
                })
                .and_then(|v| match v {
                    Value::Array(_) => Ok(v),
                    _ => Err(Fail::invalid("batch needs a JSON array of steps")),
                });
            match steps {
                Ok(steps) => ("batch", json!({ "steps": steps })),
                Err(f) => {
                    let v = envelope(Err(f), started);
                    print(&v, human_out, "batch");
                    return exit_code(&v);
                }
            }
        }
        Cmd::Script { file, args } => {
            let code = if file == "-" {
                let mut s = String::new();
                std::io::stdin().read_to_string(&mut s).map(|_| s)
            } else {
                std::fs::read_to_string(&file)
            };
            let request = code
                .map_err(|e| Fail::invalid(format!("{file}: {e}")))
                .and_then(|code| Ok(script::request(&code, &script_args(&args)?, None)));
            match request {
                Ok(request) => ("script", request),
                Err(f) => {
                    let v = envelope(Err(f), started);
                    print(&v, human_out, "script");
                    return exit_code(&v);
                }
            }
        }
        Cmd::Run { name, args } => {
            let request = script::load(&name).and_then(|(code, source)| {
                Ok(script::request(&code, &script_args(&args)?, Some((&name, &source))))
            });
            match request {
                Ok(request) => ("script", request),
                Err(f) => {
                    let v = envelope(Err(f), started);
                    print(&v, human_out, "script");
                    return exit_code(&v);
                }
            }
        }
        Cmd::Scripts | Cmd::Devices | Cmd::Diagnose(_) => unreachable!(),
    };

    let value = client::request(&udid, cmd, args).await;
    print(&value, human_out, cmd);
    exit_code(&value)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn strings(v: &[&str]) -> Vec<String> {
        v.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn launch_env_splits_at_the_first_equals() {
        let v = launch_args("a", false, &strings(&["TZ=UTC", "TOKEN=a=b", "EMPTY="]), &strings(&["-k", "v"])).unwrap();
        assert_eq!(v["environment"], json!({"TZ": "UTC", "TOKEN": "a=b", "EMPTY": ""}));
        assert_eq!(v["arguments"], json!(["-k", "v"]));
    }

    #[test]
    fn launch_env_without_a_name_or_equals_is_not_sent() {
        for bad in ["NOEQUALS", "=v", ""] {
            let f = launch_args("a", false, &strings(&[bad]), &[]).unwrap_err();
            assert_eq!(f.code, "invalid_argument");
        }
    }
}