Automation API

Android device automation

File Operations

Utils

Read, write, list, upload, and manage files on the device

Access file operations through agent.utils.files. Comprehensive file system access for automations. For uploading files to the server, use agent.utils.uploadTempFile.

AgentFiles Interface
TypeScript
interface AgentFiles {
exists(path: string): boolean;
getSize(filePath: string): number;
readFullFileBase64(filePath: string): string;
readFullFile(filePath: string): string;
openStream(filePath: string): string;
readChunk(streamId: string, chunkSize: number): number[];
closeStream(streamId: string): void;
list(dirPath: string): FileInfo[];
getPathInfo(path: string): DirectoryInfo | FilePathInfo | PathNotFoundInfo;
getStorageRoot(): string;
getHashes(filePath: string): FileHashes | FileHashError;
deleteFile(path: string): boolean; // Since 2.138
deleteDir(path: string): boolean; // Since 2.138
rename(oldPath: string, newPath: string): boolean; // Since 2.138
getDirPath(type: string): string; // Since 2.138
startDownload(url: string, localPath: string, options?: DownloadRequestOptions): string; // Since 2.138
getDownloadStatus(id: string): DownloadStatusInfo; // Since 2.138
retryDownload(id: string): boolean; // Since 2.138
base64ToBytes(base64: string): Uint8Array;
bytesToBlob(bytes: number[] | Uint8Array, mimeType?: string): Blob | null;
readFileAsBlob(filePath: string, mimeType?: string): Blob | null;
}
// On agent.utils (for file upload)
interface AgentUtils {
uploadTempFile(filename: string, base64Data: string): Promise<UploadTempFileResult | { success: false; error: string }>;
uploadTempFile(localFilePath: string): Promise<UploadTempFileResult | { success: false; error: string }>;
}

Basic Operations

exists()

TypeScript
exists(path: string): boolean

Checks if a file or directory exists at the specified path.

Parameters

NameTypeDescription
pathstringPath to check

Returns

booleantrue if the path exists

Examples

TypeScript
if (agent.utils.files.exists("/sdcard/Download/data.json")) {
const content = agent.utils.files.readFullFile("/sdcard/Download/data.json");
}

getSize()

TypeScript
getSize(filePath: string): number

Gets the size of a file in bytes.

Parameters

NameTypeDescription
filePathstringPath to the file

Returns

numberFile size in bytes, or -1 if not found

Examples

TypeScript
const size = agent.utils.files.getSize("/sdcard/video.mp4");

getStorageRoot()

TypeScript
getStorageRoot(): string

Gets the root storage path for the device (typically '/sdcard' or '/storage/emulated/0').

Returns

stringStorage root path

Examples

TypeScript
const root = agent.utils.files.getStorageRoot();
const downloadPath = root + "/Download";

Reading Files

readFullFile()

TypeScript
readFullFile(filePath: string): string

Reads the entire file content as UTF-8 text.

Parameters

NameTypeDescription
filePathstringPath to the file

Returns

stringFile content as text

Examples

TypeScript
const config = agent.utils.files.readFullFile("/sdcard/config.json");
const data = JSON.parse(config);

readFullFileBase64()

TypeScript
readFullFileBase64(filePath: string): string

Reads the entire file content as a Base64-encoded string. Useful for binary files.

Parameters

NameTypeDescription
filePathstringPath to the file

Returns

stringBase64-encoded file content

Examples

TypeScript
const imageBase64 = agent.utils.files.readFullFileBase64("/sdcard/DCIM/photo.jpg");
const ocrResult = await agent.actions.recognizeText(imageBase64);

readFileAsBlob()

TypeScript
readFileAsBlob(filePath: string, mimeType?: string): Blob | null

Reads a file directly as a Blob object.

Parameters

NameTypeDescription
filePathstringPath to the file
mimeType?stringMIME type for the blob

Returns

Blob | nullBlob object or null on failure

Examples

TypeScript
const imageBlob = agent.utils.files.readFileAsBlob("/sdcard/image.png", "image/png");

Streaming Large Files

openStream()

TypeScript
openStream(filePath: string): string

Opens a file stream for reading large files in chunks.

Parameters

NameTypeDescription
filePathstringPath to the file

Returns

stringStream ID for use with readChunk and closeStream

Examples

TypeScript
const streamId = agent.utils.files.openStream("/sdcard/large_file.bin");
let chunk;
while ((chunk = agent.utils.files.readChunk(streamId, 1024 * 1024)).length > 0) {
// Process chunk...
}
agent.utils.files.closeStream(streamId);

readChunk()

TypeScript
readChunk(streamId: string, chunkSize: number): number[]

Reads a chunk of data from an open file stream.

Parameters

NameTypeDescription
streamIdstringStream ID from openStream()
chunkSizenumberMaximum bytes to read

Returns

number[]Array of byte values (empty if end of file)

closeStream()

TypeScript
closeStream(streamId: string): void

Closes an open file stream.

Parameters

NameTypeDescription
streamIdstringStream ID from openStream()

Directory Operations

list()

TypeScript
list(dirPath: string): FileInfo[]

Lists all files and directories in the specified directory.

Parameters

NameTypeDescription
dirPathstringDirectory path

Returns

FileInfo[]Array of file/directory information

Examples

TypeScript
const files = agent.utils.files.list("/sdcard/Download");
for (const file of files) {
console.log(file.name, file.isDirectory ? "(dir)" : file.size + " bytes");
}

getPathInfo()

TypeScript
getPathInfo(path: string): DirectoryInfo | FilePathInfo | PathNotFoundInfo

Gets detailed information about a path, including whether it's a file or directory.

Parameters

NameTypeDescription
pathstringPath to check

Returns

DirectoryInfo | FilePathInfo | PathNotFoundInfoDetailed path information based on path type

Examples

TypeScript
const info = agent.utils.files.getPathInfo("/sdcard/Download");
if (info.exists && info.isDirectory) {
console.log("Contains", info.totalItems, "items");
}

File Management

deleteFile()

TypeScript
deleteFile(path: string): boolean

Deletes a file at the specified path. Only works on files, not directories. Returns false if the path doesn't exist, is a directory, or deletion fails.Since 2.138 (150)

Parameters

NameTypeDescription
pathstringPath to the file to delete

Returns

booleantrue if the file was deleted successfully

Examples

TypeScript
const deleted = agent.utils.files.deleteFile("/sdcard/Download/temp.txt");
if (deleted) {
console.log("File deleted");
}

deleteDir()

TypeScript
deleteDir(path: string): boolean

Deletes a directory and all its contents recursively. Only works on directories, not files. Returns false if the path doesn't exist, is a file, or deletion fails.Since 2.138 (150)

Parameters

NameTypeDescription
pathstringPath to the directory to delete

Returns

booleantrue if the directory was deleted successfully

Examples

TypeScript
const deleted = agent.utils.files.deleteDir("/sdcard/Download/temp_folder");
if (deleted) {
console.log("Directory and all contents deleted");
}

rename()

TypeScript
rename(oldPath: string, newPath: string): boolean

Renames or moves a file or directory from oldPath to newPath. Parent directories for the new path are created automatically. Fails if the source doesn't exist or destination already exists.Since 2.138 (150)

Parameters

NameTypeDescription
oldPathstringCurrent path (file or directory)
newPathstringNew path

Returns

booleantrue if renamed/moved successfully

Examples

TypeScript
// Rename a file
agent.utils.files.rename("/sdcard/Download/old.txt", "/sdcard/Download/new.txt");
// Move a file to another directory
agent.utils.files.rename("/sdcard/Download/photo.jpg", "/sdcard/Pictures/photo.jpg");
// Rename a directory
agent.utils.files.rename("/sdcard/Download/old_folder", "/sdcard/Download/new_folder");

getDirPath()

TypeScript
getDirPath(type: "Download" | "Movies" | "Music" | "Pictures" | "DCIM" | "Documents" | "Ringtones" | "Alarms" | "Notifications" | "Podcasts"): string

Gets the external public directory path for a given type.Since 2.138 (150)

Parameters

NameTypeDescription
typestringDirectory type: "Download", "Movies", "Music", "Pictures", "DCIM", "Documents", "Ringtones", "Alarms", "Notifications", "Podcasts"

Returns

stringAbsolute path (e.g., "/storage/emulated/0/Download")

Examples

TypeScript
const downloadDir = agent.utils.files.getDirPath("Download");
const files = agent.utils.files.list(downloadDir);
console.log("Downloads:", files.length, "files");
const musicDir = agent.utils.files.getDirPath("Music");

File Download

startDownload()

TypeScript
startDownload(url: string, localPath: string, options?: DownloadRequestOptions): string

Starts downloading a file from a URL to a local path on the device. Returns a unique download ID that can be used to track progress with getDownloadStatus. Parent directories are created automatically. Supports resume on retry. Optionally specify HTTP method, headers, and body.Since 2.138 (150)

Parameters

NameTypeDescription
urlstringThe URL to download from
localPathstringThe local file path to save the downloaded file to
options?DownloadRequestOptionsOptional HTTP request options (method, headers, body)

Returns

stringA unique download ID for tracking progress

Examples

Start a download and poll for progress
TypeScript
const downloadDir = agent.utils.files.getDirPath("Download");
const id = agent.utils.files.startDownload(
"https://example.com/large-file.zip",
downloadDir + "/large-file.zip"
);
// Poll for progress
let status;
do {
await sleep(1000);
status = agent.utils.files.getDownloadStatus(id);
if (status.totalBytes > 0) {
const percent = Math.round((status.bytesDownloaded / status.totalBytes) * 100);
console.log("Progress:", percent + "%");
}
} while (status.status === "downloading");
if (status.status === "success") {
console.log("Downloaded to:", status.filePath, "Size:", status.fileSize);
} else {
console.error("Failed:", status.error);
}
Download with custom headers and POST method
TypeScript
const id = agent.utils.files.startDownload(
"https://api.example.com/export",
"/sdcard/Download/export.csv",
{
method: "POST",
headers: {
"Authorization": "Bearer my-token",
"Content-Type": "application/json",
},
body: JSON.stringify({ format: "csv", dateRange: "last30days" }),
}
);

getDownloadStatus()

TypeScript
getDownloadStatus(id: string): DownloadStatusInfo

Returns the current status of a download. Status can be "downloading", "success", or "failed". Includes progress info (bytesDownloaded, totalBytes) and result info (filePath, fileSize) on success.Since 2.138 (150)

Parameters

NameTypeDescription
idstringThe download ID returned by startDownload

Returns

DownloadStatusInfoObject with download status, progress, and result info

Examples

Check download status
TypeScript
const status = agent.utils.files.getDownloadStatus(downloadId);
console.log("Status:", status.status);
console.log("Progress:", status.bytesDownloaded, "/", status.totalBytes);

retryDownload()

TypeScript
retryDownload(id: string): boolean

Retries a failed download. Only works if the download is in failed state. The download resumes from where it left off if the server supports Range requests.Since 2.138 (150)

Parameters

NameTypeDescription
idstringThe download ID returned by startDownload

Returns

booleantrue if retry was started, false if download not found or not in failed state

Examples

Retry a failed download
TypeScript
const status = agent.utils.files.getDownloadStatus(downloadId);
if (status.status === "failed") {
console.log("Download failed:", status.error);
const retried = agent.utils.files.retryDownload(downloadId);
if (retried) console.log("Retrying...");
}

DownloadStatusInfo

Status information for a file download.

TypeScript
interface DownloadStatusInfo {
id: string; // Unique download ID
status: "downloading" | "success" | "failed";
error: string | null; // Error message if failed
bytesDownloaded: number; // Bytes downloaded so far
totalBytes: number; // Total size (-1 if unknown)
fileSize: number; // Final file size on success (-1 otherwise)
filePath: string | null; // Absolute path on success
}

DownloadRequestOptions

Optional HTTP request options for startDownload.

TypeScript
interface DownloadRequestOptions {
method?: string; // HTTP method (default: "GET")
headers?: Record<string, string>; // HTTP headers
body?: string; // Request body (for POST, PUT, etc.)
}

Download & Read

fetch2()

TypeScript
fetch2(url: string, options?: Fetch2Options): Promise<{ success: true; content: string | Blob | Uint8Array; size: number } | { success: false; error: string }>

Downloads a file from a URL and returns its content directly. Internally downloads to a temporary file, reads the content, then deletes the temp file. On failure, automatically retries using resume-capable retryDownload.

Parameters

NameTypeDescription
urlstringThe URL to download from
options?Fetch2OptionsDownload options

Returns

Promise<{ success: true; content: string | Blob | Uint8Array; size: number } | { success: false; error: string }>File content on success, or error on failure

Examples

Download and parse JSON
TypeScript
const result = await agent.utils.fetch2("https://example.com/data.json");
if (result.success) {
const data = JSON.parse(result.content as string);
console.log("Downloaded", result.size, "bytes");
}
Download as base64 for upload
TypeScript
const result = await agent.utils.fetch2("https://example.com/image.png", {
readAs: "base64",
});
if (result.success) {
await agent.utils.uploadTempFile("image.png", result.content as string);
}
Download with custom headers and timeout
TypeScript
const result = await agent.utils.fetch2("https://api.example.com/export", {
readAs: "text",
method: "POST",
headers: { "Authorization": "Bearer my-token" },
body: JSON.stringify({ format: "csv" }),
timeoutMs: 60_000,
maxRetries: 3,
});
if (!result.success) {
console.error("Download failed:", result.error);
}

Fetch2Options

Options for the fetch2 utility method.

TypeScript
interface Fetch2Options {
readAs?: "text" | "base64" | "blob" | "bytes"; // Default: "text" (UTF-8)
timeoutMs?: number; // Max wait time in ms (default: 120000)
maxRetries?: number; // Retry attempts on failure (default: 2)
method?: string; // HTTP method (default: "GET")
headers?: Record<string, string>; // HTTP headers
body?: string; // Request body (for POST, PUT, etc.)
}

File Integrity

getHashes()

TypeScript
getHashes(filePath: string): FileHashes | FileHashError

Calculates MD5, SHA-1, and SHA-256 hashes for a file.

Parameters

NameTypeDescription
filePathstringPath to the file

Returns

FileHashes | FileHashErrorHash values or error

Examples

TypeScript
const hashes = agent.utils.files.getHashes("/sdcard/download.apk");
if (!("error" in hashes)) {
console.log("MD5:", hashes.md5);
console.log("SHA-256:", hashes.sha256);
}

File Upload

uploadTempFile()

TypeScript
uploadTempFile(filename: string, base64Data: string): Promise<UploadTempFileResult | { success: false; error: string }>

Uploads a file to the server as a temporary file. The file will be automatically deleted after 15 minutes. This overload accepts base64-encoded file data.

Parameters

NameTypeDescription
filenamestringName for the uploaded file (including extension)
base64DatastringBase64-encoded file content

Returns

UploadTempFileResult | { success: false; error: string }Upload result with file URL on success, or error on failure

Examples

Upload a screenshot
TypeScript
const screenshot = await agent.actions.screenshot(1080, 1920, 80);
if (screenshot.screenshot) {
const result = await agent.utils.uploadTempFile(
"screenshot.jpg",
screenshot.screenshot
);
if (result.success) {
console.log("File URL:", result.data.url);
console.log("Expires at:", result.data.expiresAt);
} else {
console.error("Upload failed:", result.error);
}
}
Upload text data as file
TypeScript
const jsonData = JSON.stringify({ results: [1, 2, 3] });
const base64 = btoa(jsonData);
const result = await agent.utils.uploadTempFile("results.json", base64);
if (result.success) {
console.log("Uploaded to:", result.data.url);
}

uploadTempFile (local file)()

TypeScript
uploadTempFile(localFilePath: string): Promise<UploadTempFileResult | { success: false; error: string }>

Uploads a local file from the device to the server as a temporary file. The file will be automatically deleted after 15 minutes. This overload reads the file in chunks to handle large files efficiently.

Parameters

NameTypeDescription
localFilePathstringAbsolute path to the file on the device

Returns

UploadTempFileResult | { success: false; error: string }Upload result with file URL on success, or error on failure

Examples

Upload a downloaded file
TypeScript
const result = await agent.utils.uploadTempFile("/sdcard/Download/report.pdf");
if (result.success) {
console.log("Uploaded:", result.data.originalName);
console.log("Size:", result.data.size, "bytes");
console.log("URL:", result.data.url);
} else {
console.error("Upload failed:", result.error);
}
Upload and share URL
TypeScript
const imagePath = "/sdcard/DCIM/Camera/photo.jpg";
if (agent.utils.files.exists(imagePath)) {
const result = await agent.utils.uploadTempFile(imagePath);
if (result.success) {
// Use the URL (valid for 15 minutes)
await agent.utils.job.submitTask("success", {
imageUrl: result.data.url
}, true, []);
}
}

Data Conversion

base64ToBytes()

TypeScript
base64ToBytes(base64: string): Uint8Array

Converts a Base64-encoded string to a Uint8Array.

Parameters

NameTypeDescription
base64stringBase64-encoded string

Returns

Uint8ArrayDecoded byte array

bytesToBlob()

TypeScript
bytesToBlob(bytes: number[] | Uint8Array, mimeType?: string): Blob | null

Converts a byte array to a Blob object.

Parameters

NameTypeDescription
bytesnumber[] | Uint8ArrayByte array
mimeType?stringMIME type for the blob

Returns

Blob | nullBlob object or null on failure

Types

FileInfo

TypeScript
interface FileInfo {
name: string; // File or directory name
path: string; // Full path
isDirectory: boolean;
isFile: boolean;
size: number; // Size in bytes (0 for directories)
lastModified: number; // Timestamp
}

DirectoryInfo

TypeScript
interface DirectoryInfo {
exists: true;
path: string;
name: string;
isDirectory: true;
isFile: false;
lastModified: number;
canRead: boolean;
canWrite: boolean;
fileCount: number; // Number of files
directoryCount: number; // Number of subdirectories
totalItems: number; // Total items
}

FilePathInfo

TypeScript
interface FilePathInfo {
exists: true;
path: string;
name: string;
isDirectory: false;
isFile: true;
lastModified: number;
canRead: boolean;
canWrite: boolean;
size: number;
}

PathNotFoundInfo

TypeScript
interface PathNotFoundInfo {
exists: false;
error?: string;
}

FileHashes

TypeScript
interface FileHashes {
md5: string;
sha1: string;
sha256: string;
size: number;
}

UploadTempFileResult

Result returned when a file is successfully uploaded.

TypeScript
interface UploadTempFileResult {
success: true;
message: string; // "File uploaded successfully"
data: {
filename: string; // Server-assigned filename (e.g., "1234567890_example.pdf")
originalName: string; // Original filename provided
size: number; // File size in bytes
url: string; // Full URL to access the file
expiresAt: string; // ISO 8601 expiration timestamp (15 minutes from upload)
};
}