# Introduction Source: https://docs.simular.ai/agent-s/introduction Welcome to Simular Agent documentation # Agent S: An Open Agentic Framework That Uses Computers Like a Human Welcome to **Agent S**, an open-source framework designed to enable autonomous interaction with computers through an Agent-Computer Interface. Our mission is to build intelligent GUI agents that can learn from past experiences and perform complex tasks autonomously on your computer. Whether you're interested in AI, automation, or contributing to cutting-edge agent-based systems, we're excited to have you here! **Key Features:** * **Autonomous Interaction:** Agents can operate your computer as a human would, interacting with the GUI to accomplish tasks. * **Cross-Platform Support:** Compatible with macOS, Linux, and Windows, ensuring a wide range of usability. * **Extensible Design:** Easily integrate new functionalities and tools to tailor the agents to specific needs. **Getting Started:** **Clone the Repository:** ```bash theme={null} git clone https://github.com/simular-ai/Agent-S.git ``` **Install Dependencies:** ```bash theme={null} pip install . ``` **Run the Framework:** ```bash theme={null} python gui_agents/cli_app.py ``` # Quickstart Source: https://docs.simular.ai/agent-s/quickstart Start running industry leading computer use agents in under 5 minutes > **[Official Website](https://www.simular.ai/agent-s)** > > Get your docs set up locally for easy development > **[Paper](https://arxiv.org/abs/2410.08164)** > > Preview your changes before you push to make sure they're perfect > **[Video](https://www.youtube.com/watch?v=OBDE3Knte0g)** > > Preview your changes before you push to make sure they're perfect ## πŸ’‘ Introduction Welcome to **Agent S**, an open-source framework designed to enable autonomous interaction with computers through Agent-Computer Interface. Our mission is to build intelligent GUI agents that can learn from past experiences and perform complex tasks autonomously on your computer. Whether you're interested in AI, automation, or contributing to cutting-edge agent-based systems, we're excited to have you here! ## πŸ› οΈ Installation & Setup > ❗**Warning**❗: If you are on a Linux machine, creating a `conda` environment will interfere with `pyatspi`. As of now, there's no clean solution for this issue. Proceed through the installation without using `conda` or any virtual environment. Clone the repository: ```bash theme={null} git clone https://github.com/simular-ai/Agent-S.git ``` Install the gui-agents package: ``` pip install gui-agents ``` Set your LLM API Keys and other environment variables. You can do this by adding the following line to your .bashrc (Linux), or .zshrc (MacOS) file. ```bash theme={null} export OPENAI_API_KEY= ``` Alternatively, you can set the environment variable in your Python script: ```python theme={null} import os os.environ["OPENAI_API_KEY"] = "" ``` We also support Azure OpenAI, Anthropic, and vLLM inference. For more information refer to [models.md](models.md). ### Setup Retrieval from Web using Perplexica Agent S works best with web-knowledge retrieval. To enable this feature, you need to setup Perplexica: 1. Ensure Docker Desktop is installed and running on your system. 2. Navigate to the directory containing the project files. ```bash theme={null} cd Perplexica git submodule update --init ``` 3. Rename the `sample.config.toml` file to `config.toml`. For Docker setups, you need only fill in the following fields: * `OPENAI`: Your OpenAI API key. **You only need to fill this if you wish to use OpenAI's models**. * `OLLAMA`: Your Ollama API URL. You should enter it as `http://host.docker.internal:PORT_NUMBER`. If you installed Ollama on port 11434, use `http://host.docker.internal:11434`. For other ports, adjust accordingly. **You need to fill this if you wish to use Ollama's models instead of OpenAI's**. * `GROQ`: Your Groq API key. **You only need to fill this if you wish to use Groq's hosted models**. * `ANTHROPIC`: Your Anthropic API key. **You only need to fill this if you wish to use Anthropic models**. **Note**: You can change these after starting Perplexica from the settings dialog. * `SIMILARITY_MEASURE`: The similarity measure to use (This is filled by default; you can leave it as is if you are unsure about it.) 4. Ensure you are in the directory containing the `docker-compose.yaml` file and execute: ```bash theme={null} docker compose up -d ``` 5. Our implementation of Agent S incorporates the Perplexica API to integrate a search engine capability, which allows for a more convenient and responsive user experience. If you want to tailor the API to your settings and specific requirements, you may modify the URL and the message of request parameters in `agent_s/query_perplexica.py`. For a comprehensive guide on configuring the Perplexica API, please refer to [Perplexica Search API Documentation](https://github.com/ItzCrazyKns/Perplexica/blob/master/docs/API/SEARCH.md) For a more detailed setup and usage guide, please refer to the [Perplexica Repository](https://github.com/ItzCrazyKns/Perplexica.git). ### Setup Paddle-OCR Server Switch to a new terminal where you will run Agent S. Set the OCR\_SERVER\_ADDRESS environment variable as shown below. For a better experience, add the following line directly to your .bashrc (Linux), or .zshrc (MacOS) file. ```bash theme={null} export OCR_SERVER_ADDRESS=http://localhost:8000/ocr/ ``` Run the ocr\_server.py file code to use OCR-based bounding boxes. ```bash theme={null} cd Agent-S python gui_agents/utils/ocr_server.py ``` You can change the server address by editing the address in [agent\_s/utils/ocr\_server.py](agent_s/utils/ocr_server.py) file. > ❗**Warning**❗: The agent will directly run python code to control your computer. Please use with care. ## πŸš€ Usage ### CLI Run agent\_s on your computer using: ```bash theme={null} agent_s --model gpt-4o ``` This will show a user query prompt where you can enter your query and interact with Agent S. You can use any model from the list of supported models in [models.md](models.md). ### `gui_agents` SDK To deploy Agent S on MacOS or Windows: ```python theme={null} import pyautogui import io from gui_agents.core.AgentS import GraphSearchAgent import platform if platform.system() == "Darwin": from gui_agents.aci.MacOSACI import MacOSACI, UIElement grounding_agent = MacOSACI() elif platform.system() == "Windows": from gui_agents.aci.WindowsOSACI import WindowsACI, UIElement grounding_agent = WindowsACI() elif platform.system() == "Linux": from gui_agents.aci.LinuxOSACI import LinuxACI, UIElement grounding_agent = LinuxACI() else: raise ValueError("Unsupported platform") engine_params = { "engine_type": "openai", "model": "gpt-4o", } agent = GraphSearchAgent( engine_params, grounding_agent, platform="ubuntu", # "macos", "windows" action_space="pyautogui", observation_type="mixed", search_engine="Perplexica" ) # Get screenshot. screenshot = pyautogui.screenshot() buffered = io.BytesIO() screenshot.save(buffered, format="PNG") screenshot_bytes = buffered.getvalue() # Get accessibility tree. acc_tree = UIElement.systemWideElement() obs = { "screenshot": screenshot_bytes, "accessibility_tree": acc_tree, } instruction = "Close VS Code" info, action = agent.predict(instruction=instruction, observation=obs) exec(action[0]) ``` Refer to `cli_app.py` for more details on how the inference loop works. ### OSWorld To deploy Agent S in OSWorld, follow the [OSWorld Deployment instructions](OSWorld.md). ### WindowsAgentArena To deploy Agent S in WindowsAgentArena, follow the [WindowsAgentArena Deployment instructions](WindowsAgentArena.md). ## πŸ™Œ Contributors We’re grateful to all the [amazing people](https://github.com/simular-ai/Agent-S/graphs/contributors) who have contributed to this project. Thank you! πŸ™ ## πŸ’¬ Citation ``` @misc{agashe2024agentsopenagentic, title={Agent S: An Open Agentic Framework that Uses Computers Like a Human}, author={Saaket Agashe and Jiuzhou Han and Shuyu Gan and Jiachen Yang and Ang Li and Xin Eric Wang}, year={2024}, eprint={2410.08164}, archivePrefix={arXiv}, primaryClass={cs.AI}, url={https://arxiv.org/abs/2410.08164}, } ``` # Introduction Source: https://docs.simular.ai/introduction Welcome to Simular developer documentation β€” Sai, Simulang, and Agent S. Welcome to the **Simular** developer documentation. Here you will find guides and references for **scripting with Simulang** and the **Agent S** open-source framework. **[Sai](https://www.simular.ai/sai)** is Simular's **strongest computer-use agent** for when you need maximum capability on real desktop and browser UIs. ## Sai and Agent S ### **1. [Sai](https://www.simular.ai/sai)** **Sai** is Simular's **strongest computer-use agent** β€” our most capable option when you need deep, reliable automation across real desktop and browser UIs. Details, access, and how Sai fits with the rest of the product line are on the **[Sai product page](https://www.simular.ai/sai)**. Developers can drive Sai from their own code or coding agent (Claude Code, Codex, Cursor) with the **[Sai API](https://platform.simular.ai/documentation)**: send a task in plain language, and Sai completes it on a cloud Windows computer. ### **2. [Agent S](agent-s/introduction)** An **open-source** framework for agents that **control computers like a human** β€” UI, keyboard, and mouse β€” across environments. * Run agents **autonomously** inside many kinds of software. * **Extensible** with custom integrations and tooling. * **Platforms:** **macOS, Linux, and Windows**. *** ## Simulang (scripting) **Simulang** is our layer for scripting desktop automation. This documentation covers **two tracks**; treat them separately: | Track | What it is | Where to start | | - | - | - | | **Latest Simulang** | Standalone **`simulang` CLI**, **`simulang-js`**, and the **`/simulang`** skill in **Claude Code**. | [Simulang Primer](simulang/simulang-primer), then [Simulang with Claude Code](simulang/simulang-claude-code) | | **Simulang v0** | **Legacy** in-app JavaScript-style actions for a **deprecated** desktop automation surface. Kept for reference and migration only. | [Simulang v0 API](simular-pro/simulang), [Simulang v0 examples](simular-pro/examples) | For **new** work, use **Latest Simulang** (primer and Claude Code). Use the **v0** docs only if you still maintain workflows on the legacy in-app surface. Looking for something to read or remix end-to-end? The new **[Simulang Recipes](https://github.com/simular-ai/simulang-recipes)** repo collects community-built automations β€” a 2048 bot, a Wordle solver, a Calendar-to-Docs digest, a TikTok forwarder, and more β€” each one a small, runnable script you can clone and adapt. *** ### Next steps * Read about **[Sai](https://www.simular.ai/sai)** for Simular's strongest computer-use agent. * Call Sai from code or a coding agent with the **[Sai API](https://platform.simular.ai/documentation/quickstart)**. * Choose your **Simulang** track from the table above (prefer latest for new projects). * Browse the **[Simulang Recipes](https://github.com/simular-ai/simulang-recipes)** repo for runnable, end-to-end automations to clone and remix. * Explore **[Agent S](agent-s/introduction)** to build or extend open-source computer-use agents. * Join the community via **Discord** and **GitHub** in the header when you want help or to contribute. For more detail, use the sidebar: **Getting Started**, **Simulang**, **Sai** (integrations), the **Sai API** tab, **Simular** (legacy Simulang v0 reference), and **Agent S**. # Zoom Source: https://docs.simular.ai/sai/integrations/zoom Connect Zoom to Sai to schedule and manage meetings, share join links, check attendance, and find cloud recordings from chat. **[Sai](https://www.simular.ai/sai)** is Simular's computer-use agent. Once Zoom is connected, you can ask Sai in chat to schedule and manage meetings, pull join links and invite text, see who attended a past meeting, find cloud recordings, and read an AI Companion summary for a meeting you hosted. > [!NOTE] > > Add the Zoom integration **from Sai**, not from the Zoom App Marketplace. The Marketplace listing points you back to Sai. ## Prerequisites * A Sai account at [sai.simular.ai](https://sai.simular.ai) * A Zoom account. Cloud recordings and AI Companion summaries also need a Zoom plan that includes them. ## Adding the app **1. Sign in to Sai** Go to [https://sai.simular.ai](https://sai.simular.ai) and sign in, or open the Sai desktop app. **2. Open Settings β†’ Integrations** Open **Settings** from the sidebar, then choose **Integrations**. **3. Connect Zoom** Find **Zoom** and click **Connect**. Sign in to Zoom if asked, then click **Allow**. You land back in Sai with Zoom connected. Settings shows the Zoom email you authorized. **One Connect is one Zoom account.** Connecting a different Zoom login replaces the first. If the connection fails, see [Troubleshooting](#troubleshooting). ## Using the app Ask Sai in plain language. For example: * "Schedule a 30-minute sync with the design team tomorrow at 10am and send me the join link" * "List my upcoming Zoom meetings" * "Who joined yesterday's standup, and for how long?" * "Find the cloud recording of last week's all-hands" * "What did we decide on yesterday's standup?" (AI Companion summary, if one exists for a meeting you hosted) ### What Sai can do | Area | What you can ask for | | - | - | | **Meetings** | List upcoming or past meetings. Open a meeting, schedule a new one, change it, or cancel it. Pull the join link and the invite text you'd paste into an email. | | **Past attendance** | After a meeting has ended, see who joined and for how long, and list past instances of a recurring meeting. | | **Cloud recordings** | Find recordings once Zoom has finished processing them. Sai looks at the last 30 days by default β€” for older recordings, ask month by month. Sai shares the play and download links; it does not download the file. | | **Summaries** | Read an AI Companion summary when one exists for a meeting **you hosted**. | ### Approvals Scheduling, changing, or cancelling a meeting asks for your approval first. Changing or cancelling a **recurring** meeting applies to the whole series, not one occurrence. Sai confirms with you before doing that. ### What Sai does not do * Host webinars * Download recording files into Sai * Read AI Companion summaries for meetings you did not host AI Companion summaries also require a Zoom plan that includes them, AI Companion turned on for the meeting, and a summary that Zoom has already generated. ## Removing the app Disconnecting stops Sai from using Zoom and deletes the Zoom access and refresh tokens Sai holds for you. You can do it from Sai, from Zoom, or both. ### From Sai **1. Sign in to Sai** Go to [https://sai.simular.ai](https://sai.simular.ai) and sign in, or open the Sai desktop app. **2. Open Settings β†’ Integrations** Open **Settings** from the sidebar, then choose **Integrations**. **3. Disconnect Zoom** Find **Zoom** and click **Disconnect**. Sai forgets the connection and revokes its access on Zoom's side. To confirm, check **Manage β†’ Added Apps** in the Zoom App Marketplace. ### From Zoom **1. Open the Zoom App Marketplace** Sign in at [https://marketplace.zoom.us](https://marketplace.zoom.us). **2. Go to your added apps** Click **Manage β†’ Added Apps**. **3. Remove Sai** Select **Sai**, then click **Remove**. ### What happens after removal * Sai can no longer list meetings, schedule, or read recordings or summaries for that Zoom account until you connect again. * Sai's Zoom access and refresh tokens are deleted. * Sai does not keep a separate archive of your Zoom meeting data. Chat history from earlier requests may still be in that conversation. ## Troubleshooting > **Invalid redirect during Connect** > > Start **Connect** from Sai's Settings β†’ Integrations, not from an **Add** button on the Zoom App Marketplace. > **Sai connected the wrong Zoom account** > > Click **Disconnect** in Settings β†’ Integrations, then **Connect** again and pick the right Zoom login. > **Sai can't find a meeting summary** > > You must have hosted the meeting, AI Companion must have generated a summary, and your Zoom plan must include summaries. A summary that is still generating won't show up yet. > **Sai can't find a recording** > > Zoom must have finished processing the cloud recording. For meetings older than 30 days, ask Sai month by month. > **A scheduling request was refused** > > Zoom limits how many meetings one user can create or update per day. If you hit that limit, wait until the next day and try again. ## Support Email [support@simular.ai](mailto:support@simular.ai). Include the Zoom email you connected and, if you can, the request you asked Sai to run. # Simulang with Claude Code Source: https://docs.simular.ai/simulang/simulang-claude-code Automate your Mac from Claude Code with the /simulang skillβ€”install, prompts, and desktop tips. # Using Simulang with Claude Code Simulang is a **Claude Code skill** for **desktop automation** on macOS. You describe the task in natural language (open apps, click controls, type text, scroll, capture screenshots, inspect the accessibility tree); Claude looks up the installed `simulang-js` API, writes a TypeScript script, and runs it with the Simulang CLIβ€”same building blocks as the [Simulang Primer](/simulang/simulang-primer). ## Setup 1. **Install simulang CLI globally:** ```bash theme={null} npm install -g @simular-ai/simulang ``` 2. **Install the Claude Code skill:** ```bash theme={null} simulang init-claude ``` 3. **(Optional) Enable the log viewer** for visual debugging: ```bash theme={null} npm install @simular-ai/simulang-log-viewer ``` Then tell Claude: `/simulang enable log view in all scripts` ## Usage Invoke the skill with `/simulang` followed by what you want to do: ``` /simulang open google and search for weather in sf /simulang take a screenshot of the current screen /simulang find all buttons on the screen using accessibility tree /simulang click on the submit button /simulang type "hello world" and press enter ``` Claude will: 1. Look up the simulang-js API docs for the installed version 2. Write a TypeScript script 3. Run it with `simulang run` 4. Show you screenshots or results ## Example Prompts | Prompt | What Claude Does | | - | - | | `/simulang open safari and go to github.com` | Opens browser, navigates to URL | | `/simulang search for "Simular" on this page` | Presses Cmd+F, types search term | | `/simulang scroll down and take a screenshot` | Scrolls, captures screen | | `/simulang what's the version of simulang?` | Runs `simulang --version` | | `/simulang read the simulang-js API docs` | Reads `index.d.ts` and `CLAUDE.md` | ## Tips * **Be specific** β€” "click the blue Submit button" works better than "click submit" * **Ask for screenshots** β€” Claude can capture and view what's on screen * **Use grounding models** β€” For visual element finding, set `OPENROUTER_API_KEY` * **Enable log viewer** β€” Helps when the terminal is hidden behind automated apps ## Requirements * Node.js >= 22.18 * macOS: Grant Accessibility and Screen Recording permissions when prompted # Simulang Primer Source: https://docs.simular.ai/simulang/simulang-primer Hands-on tour of writing Simulang scripts β€” browser automation, forms, screenshots, and workflows. # The Simulang Primer A hands-on tour of writing scripts in **Simulang**. By the end you'll know how to drive a real browser, fill in a form, click through a UI, take screenshots, ground elements with a vision model, and compose larger workflows out of small reusable steps β€” all in plain TypeScript or JavaScript. This primer is meant to be read in order; each chapter builds on the one before it. The complete API reference for the underlying library is hosted at [simulang-js](https://docs.simular.ai/simulang-js/api/latest) β€” keep that open in another tab when you're ready to go deeper than what we cover here. Once a chapter clicks, the **[Simulang Recipes](https://github.com/simular-ai/simulang-recipes)** repo is the easiest way to see the same ideas applied end-to-end: every recipe is a small, runnable script you can clone, run, and adapt. *** ## Table of contents 1. [What is Simulang?](#1-what-is-simulang) 2. [Your first script](#2-your-first-script) 3. [Opening an app](#3-opening-an-app) 4. [Your first automation](#4-your-first-automation) 5. [The accessibility tree](#5-the-accessibility-tree) 6. [Acting on elements](#6-acting-on-elements) 7. [Finding the element you want](#7-finding-the-element-you-want) 8. [Waiting for the UI](#8-waiting-for-the-ui) 9. [When things don't work](#9-when-things-dont-work) 10. [A complete example](#10-a-complete-example) 11. [When accessibility isn't enough](#11-when-accessibility-isnt-enough) 12. [Files, env vars, and shelling out](#12-files-env-vars-and-shelling-out) 13. [Composing scripts](#13-composing-scripts) 14. [Common pitfalls](#14-common-pitfalls) 15. [Where to go next](#15-where-to-go-next) 16. [Simulang in Claude Code](#16-simulang-in-claude-code) *** ## 1. What is Simulang? **Simulang is a small command-line tool for running automation scripts against real desktop applications** β€” your default browser, your editor, a chat app, a native dialog, whatever happens to be running. A Simulang script is an ordinary ES module (a `.ts`, `.mts`, or `.mjs` file) that imports from `@simular-ai/simulang-js` and drives the OS through its accessibility APIs. If you've used Playwright or Puppeteer, the mental model will feel familiar: open a thing, find an element, interact with it, assert what happened. The differences: * Simulang isn't browser-only. The same APIs drive **native apps** β€” a messaging client to grab a 2FA code, a finder window, a desktop installer. * There's **no headless mode**. You're automating the actual UI a person would see, on the actual screen. * Element discovery uses the OS-level **accessibility tree**, not CSS selectors. That's how the same script can find a button in Chrome and a menu item in a native macOS app. This primer assumes you have `simulang` installed and a desktop you can run scripts against β€” see the [simulang-cli README](https://github.com/simular-ai/simulang-cli) for install, authentication, and version-pinning details. From here on, we focus on writing and running workflows. *** ## 2. Your first script Create `hello.ts`: ```ts theme={null} // hello.ts const { platform, version } = process console.log(`Hello from simulang on ${platform}, Node ${version}.`) ``` Run it: ``` $ simulang run hello.ts Hello from simulang on darwin, Node v22.18.0. ``` That's it β€” no boilerplate, no `async function main()` wrapper. A Simulang script is just an ES module, and the top of the file *is* the entry point. Top-level `await` works, dynamic imports work, and the full Node standard library is available. ```ts theme={null} // hello-async.ts // Top-level await is fine. await new Promise((r) => setTimeout(r, 50)) console.log('half a frame later…') // And so is dynamic import β€” useful for branching by platform. const fs = await import('node:fs/promises') console.log('cwd =', await fs.realpath(process.cwd())) ``` If you've worked with newer Node tooling this will feel completely ordinary. That's the point. **Recap.** A Simulang script is just an ES module. Save a `.ts`, `.mts`, or `.mjs` file. Run it with `simulang run`. Use `process.env`, `process.exit`, and anything else you'd use in a normal Node script. *** ## 3. Opening an app The `@simular-ai/simulang-js` package gives you everything else. Let's open `example.com` in the default browser: ```ts theme={null} // open-example.ts import { App, FocusPolicy, Visibility } from '@simular-ai/simulang-js' const instance = App.defaultBrowser().open( 'https://example.com', FocusPolicy.Steal, // β‘  bring the browser to the front Visibility.Show, // β‘‘ don't try to hide it true, // β‘’ block briefly for the page to start ) console.log('opened:', instance.pid) ``` Three things to call out: 1. **`FocusPolicy`** is `Steal` or `DoNotSteal`. *"Steal"* asks the OS to bring the app to the front; *"DoNotSteal"* asks it not to. The word "ask" is doing real work in that sentence β€” see the pitfalls chapter. 2. **`Visibility`** is `Show` or `Hidden`. Same caveat: it's a request, not a guarantee, and Chromium-based apps in particular ignore `Hidden`. 3. **`waitForLoadComplete`** (the trailing boolean) blocks for a short, fixed delay so the app or URL has a chance to become responsive before `open()` returns. It's a sleep, not a full network wait β€” you still need to give the page time to render before reaching for the DOM. The call returns an **`Instance`** β€” a handle to the running app: ```ts theme={null} instance.pid // process ID instance.isFocused() // boolean instance.focus() // bring it forward instance.hide() // minimise instance.isAccessible() // does the OS expose this app's accessibility tree? instance.enableAccessibility() ``` If you want to launch a *specific* app (not the system default), use `App.exactName()`: ```ts theme={null} App.exactName('Google Chrome').open( null, // no URL β€” just raise the app FocusPolicy.Steal, Visibility.Show, false, ) ``` `open(null, …)` is the canonical way to **raise an already-running app** to the foreground without changing its state. *** ## 4. Your first automation Time to make something happen. Save this as `wikipedia-stats.ts`: ```ts theme={null} // wikipedia-stats.ts β€” run with: simulang run wikipedia-stats.ts import { AccessibilityTree, App, AriaRole, FocusPolicy, Visibility, type AccessibilityNodeJs, } from '@simular-ai/simulang-js' const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)) function flattenDFS( node: AccessibilityNodeJs, out: AccessibilityNodeJs[] = [], ): AccessibilityNodeJs[] { out.push(node) for (const child of node.children) flattenDFS(child, out) return out } const instance = App.defaultBrowser().open( 'https://en.wikipedia.org', FocusPolicy.Steal, Visibility.Show, true, ) await sleep(2500) if (!instance.isAccessible()) instance.enableAccessibility() const tree = AccessibilityTree.fromPid(instance.pid) const link = flattenDFS(tree.snapshot(true)).find( (n) => n.role === AriaRole.Link && /special:statistics/i.test(n.description) && n.refId != null, ) if (!link) throw new Error('Could not find the Statistics link.') tree.activate(link.refId) console.log('Opened the Wikipedia statistics page.') ``` Run it. Wikipedia opens, Simulang walks the page's accessibility tree, finds the Statistics link, clicks it, and your browser jumps to Wikipedia's `Special:Statistics` page. **Why `n.description` and not `n.name`?** Web AX on macOS commonly exposes link text in the `description` field with `name` left empty. Other platforms differ β€” that's exactly the kind of cross-platform variability chapter 7 addresses with a `labelOf` helper that checks every field a label might live in. **macOS first-run prompt.** The first time a Simulang script touches another app, the OS will prompt you to grant accessibility permission to the terminal you ran it from (System Settings β†’ Privacy & Security β†’ Accessibility). Grant it once and you're set. That's the whole Simulang loop in twenty-odd lines. The shape is the same for every script you'll write β€” from this demo to a multi-step purchase flow: 1. **Open or attach to an app** β€” `App.defaultBrowser().open` (here), or `AccessibilityTree.fromPid` to drive something already running. 2. **Snapshot the accessibility tree** β€” `tree.snapshot(true)` returns the visible UI as a tree of nodes. 3. **Walk the tree** to find the node you want β€” any standard array or object operation works, since the snapshot is plain data. 4. **Act on its `refId`** β€” `tree.activate(refId)` for clicks, `tree.setValue(refId, text)` for typing, and a handful of others. Don't worry about every line yet β€” the next few chapters break it down. The takeaway is that you've now seen the four moves that make up every Simulang script. **A note on TypeScript.** This primer uses `.ts` so we can show type annotations where they're informative β€” `.mjs` works just as well. *** ## 5. The accessibility tree You just used the accessibility tree without an introduction. Let's back up and look at what it is. The **accessibility tree** is a snapshot of every visible widget in a window β€” the same data screen readers use to read a UI aloud. Every OS exposes one, and `@simular-ai/simulang-js` gives you a uniform Node API over it. ```ts theme={null} import { AccessibilityTree } from '@simular-ai/simulang-js' // Bind to the foreground window of whichever app is in front right now. const tree = AccessibilityTree.fromForeground() console.log('Bound to window:', tree.windowTitle) ``` You can also bind to a specific window by process ID β€” handy when you just opened the app yourself and have an `Instance.pid` (chapter 4 used this form): ```ts theme={null} const tree = AccessibilityTree.fromPid(instance.pid) ``` Once you've got a tree, take a snapshot: ```ts theme={null} const root = tree.snapshot(true) // true = visible-only; almost always what you want ``` The shape of every node looks like this: ```ts theme={null} interface AccessibilityNodeJs { role: AriaRole // numeric enum: Button = 7, Link = 32, ... name: string // accessible name value: string // current value (for inputs) description: string // platform-specific extra helpText: string // tooltip-style hint refId?: number // opaque handle for interactions (more below) children: AccessibilityNodeJs[] boundingBox: { x, y, width, height, ... } } ``` You walk this tree like any other object graph: ```ts theme={null} function flattenDFS(node, out = []) { out.push(node) for (const child of node.children) flattenDFS(child, out) return out } for (const node of flattenDFS(root).slice(0, 10)) { console.log(node.role, JSON.stringify(node.name).slice(0, 60)) } ``` **The most important property is `refId`.** It's an opaque integer that identifies a node *for this snapshot only*. You pass it to interaction methods like `tree.activate(refId)` to click. Two crucial properties: * **A `refId` is valid only as long as the snapshot that produced it.** Take a new snapshot, and the old refIds are dead. We'll see how to cope with that in chapter 8. * **A node only has a `refId` when the OS exposed one.** Some structural wrappers (groups, panels) don't have refIds; you can still see them in the tree, but you can't click them. Always check `refId != null` before acting. The roles are an enum called `AriaRole`. The common ones: ```ts theme={null} import { AriaRole } from '@simular-ai/simulang-js' AriaRole.Button // 7 AriaRole.Checkbox // 10 AriaRole.Dialog // 18 AriaRole.Document // 20 β€” the root of a web page AriaRole.Heading // 29 AriaRole.Img // 30 AriaRole.Link // 32 AriaRole.MenuItem // 43 AriaRole.Radio // 54 AriaRole.Tab // 72 AriaRole.Textbox // 78 ``` **Heads up.** `AriaRole` is a numeric enum. The TypeScript reverse-mapping trick β€” `AriaRole[someNode.role]` β€” does **not** work for numeric NAPI enums. Use the exported helper instead: ```ts theme={null} import { ariaRoleToString } from '@simular-ai/simulang-js' ariaRoleToString(node.role) // "button" ``` **Recap.** Bind to a window β†’ take a snapshot β†’ walk the tree to find the node you want β†’ act on its `refId`. The rest of this primer is elaborations on that loop. *** ## 6. Acting on elements Once you have a `refId`, the `AccessibilityTree` object exposes a small family of action methods: ```ts theme={null} tree.activate(refId) // "click" β€” works for buttons, links, menuitems tree.setValue(refId, text) // type into a textbox / combobox tree.toggle(refId) // flip a checkbox or switch tree.select(refId) // choose a tab, radio button, or list item tree.expandCollapse(refId) // open/close a dropdown or tree item tree.scrollIntoView(refId) // bring the element on-screen tree.focusElement(refId) // focus (also raises the window) tree.getBounds(refId) // current screen coordinates ``` In practice you'll spend most of your time with **`activate`** and **`setValue`**. The rest are special-purpose helpers for cases where a plain click doesn't do the right thing. **Sync, not async.** Every action method on `AccessibilityTree` is synchronous β€” they don't return Promises, and you don't `await` them. The `await` you saw in chapter 4 was for `sleep`, not for `tree.activate`. `tree.snapshot()` is also synchronous. The only things you `await` in a typical script are sleeps, polling helpers like `withSnapshot` (chapter 8), and Node stdlib promises (fetch, `node:fs/promises`). You already saw `activate` in chapter 4. Filling a form looks the same β€” find the input, set its value, find the submit button, activate it: ```ts theme={null} const nodes = flattenDFS(tree.snapshot(true)) const searchBox = nodes.find( (n) => n.role === AriaRole.Textbox && /search/i.test(n.name) && n.refId != null, ) const searchBtn = nodes.find( (n) => n.role === AriaRole.Button && /^search$/i.test(n.name) && n.refId != null, ) if (!searchBox || !searchBtn) throw new Error('search controls not found') tree.setValue(searchBox.refId, 'simulang') // β‘  type into the box tree.activate(searchBtn.refId) // β‘‘ click submit ``` Two details worth noticing β€” they apply to every action method: 1. The predicate checks **`n.refId != null`**. Without that, you might match a structural wrapper that has the right name but no way to be acted on. 2. Both `setValue` and `activate` use `refId`s from the *same* snapshot. As long as no new snapshot has happened between them, the refs stay valid. After any navigation or UI mutation, you'll need a fresh snapshot β€” chapter 8 shows the pattern. *** ## 7. Finding the element you want Real UIs make element discovery harder than "find by name." A few practical patterns we use again and again. **A note on the helpers in this chapter.** `labelOf`, `stripPUA`, `flattenDFS`, `pageNodes` below β€” and `withSnapshot` in the next chapter β€” are **not** exported from `@simular-ai/simulang-js`. They're a handful of lines each, and copying them into each script is faster than reaching for a dependency. The upside of script-local helpers is that you can tweak them when a project needs something different (a `labelOf` that includes `automationId`, a `pageNodes` scoped to a specific app). If you find yourself maintaining a project-wide variant, factor it into a local `lib/` directory and import it normally. ### 7.1 The label can live in any of four fields Different platforms put a control's accessible text in different places: * Native macOS apps usually put it in `name`. * Text inputs put the *current value* in `value` (not `name`). * Web AX on macOS often puts link text in `description`. * Tooltips show up in `helpText`. A single label-helper covers all four: ```ts theme={null} const labelOf = (n) => [n.name, n.value, n.description, n.helpText].filter(Boolean).join(' ').trim() ``` Now `labelOf(node)` is the answer to "what would a screen reader say about this element?", regardless of which field the OS chose. ### 7.2 Strip Private-Use-Area glyphs Web pages frequently put icon-font glyphs (Font Awesome, Material Icons) into link labels. These come through as characters in Unicode's Private Use Area (`U+E000`–`U+F8FF`), and they break anchored regexes: ```ts theme={null} // node.name might be " Logout" /^logout$/i.test(node.name) // false ☹ ``` Strip them: ```ts theme={null} const stripPUA = (s) => s.replace(/[-]/g, '').replace(/\s+/g, ' ').trim() const labelOf = (n) => stripPUA([n.name, n.value, n.description, n.helpText].filter(Boolean).join(' ')) ``` ### 7.3 Scope to the page, not the chrome A browser snapshot includes the URL bar, tab strip, bookmarks bar, dev-tools panes β€” none of which you usually want when you're looking for an "Add to cart" button. The convention is to flatten only the **last `AriaRole.Document` subtree**, which is the active tab's web content: ```ts theme={null} function pageNodes(root) { const all = flattenDFS(root) const docs = all.filter((n) => n.role === AriaRole.Document) if (!docs.length) return all // not a browser β€” full tree return flattenDFS(docs[docs.length - 1]) // last = active tab } ``` Then use `pageNodes(root)` instead of `flattenDFS(root)` when you're hunting for something inside the page. ### 7.4 Use the built-in search when it fits `AccessibilityTree` also exposes a search method that mirrors the common case: ```ts theme={null} import { TraversalOrder } from '@simular-ai/simulang-js' const hits = tree.find( TraversalOrder.DepthFirst, AriaRole.Button, // role filter (optional) 'Submit', // name contains (optional) true, // visibleOnly 1, // maxResults ) if (hits[0]) tree.activate(hits[0].refId) ``` Use the built-in `find` for "fast path, one role, one name match." Drop back to manual DFS when you need spatial reasoning β€” for example, "the second textbox that appears between the heading 'Sign in' and the button 'Continue'." *** ## 8. Waiting for the UI Pages mutate. Modals appear. The element you want shows up half a second after a click. Because `refId`s invalidate every time you call `snapshot()`, the safe pattern is a **polling loop that re-snapshots each tick and looks for what you want**: ```ts theme={null} async function withSnapshot( tree, predicate, { timeoutMs = 8000, intervalMs = 250, label = 'node' } = {}, ) { const deadline = Date.now() + timeoutMs while (Date.now() < deadline) { const root = tree.snapshot(true) // β‘  fresh refIds every tick const hit = predicate(flattenDFS(root)) // β‘‘ caller decides "found" if (hit) return hit // β‘’ first match wins await sleep(intervalMs) } throw new Error(`Timed out waiting for ${label}`) } ``` Used at the call site: ```ts theme={null} const link = await withSnapshot( tree, (nodes) => nodes.find( (n) => n.role === AriaRole.Link && /^logout$/i.test(labelOf(n)) && n.refId != null, ), { label: '"Logout" link' }, ) tree.activate(link.refId) ``` Three reasons this pattern shows up in every nontrivial script: 1. The element might not be there yet β€” page is still loading, animation is mid-flight, modal hasn't opened. 2. The element might be there but its `refId` is from a now-stale snapshot. Polling re-issues the snapshot for you. 3. The named `label` gives you a useful error message when the wait genuinely times out: *"Timed out waiting for the Allow button in the blocked-download panel"* is much nicer to read at 3am than *"Timed out waiting for node."* A predicate doesn't have to return a single node. When you need several pieces of state to all be visible at once, return a structured object: ```ts theme={null} const { emailField, passField, loginBtn } = await withSnapshot( tree, (nodes) => { const headingIdx = nodes.findIndex((n) => /sign in/i.test(labelOf(n))) if (headingIdx === -1) return null const btnIdx = nodes.findIndex( (n, i) => i > headingIdx && n.role === AriaRole.Button && /sign in/i.test(labelOf(n)), ) if (btnIdx === -1) return null const inputs = nodes .slice(headingIdx, btnIdx) .filter((n) => n.role === AriaRole.Textbox && n.refId != null) if (inputs.length < 2) return null return { emailField: inputs[0], passField: inputs[1], loginBtn: nodes[btnIdx] } }, { label: 'sign-in form (email + password + button)' }, ) ``` This is also how you handle login forms whose inputs have no accessible label at all: locate them **positionally**, between two well-labelled landmarks. *** ## 9. When things don't work Sooner or later you'll get `Timed out waiting for "Continue" button`, or your `find` will silently return `undefined`. Here's the troubleshooting playbook. ### 9.1 Print the tree The fastest way to debug a missing element is to dump what *is* there: ```ts theme={null} import { ariaRoleToString } from '@simular-ai/simulang-js' const lines = flattenDFS(tree.snapshot(true)) .filter((n) => n.refId != null && labelOf(n)) .map((n) => `${ariaRoleToString(n.role).padEnd(12)} ${JSON.stringify(labelOf(n)).slice(0, 60)}`) console.log(lines.join('\n')) ``` Drop that wherever your script is stuck. It prints every actionable element on the page with its role and accessible label. Two outcomes: * **The element isn't in the list.** The page hasn't rendered it yet. Sleep longer, or β€” better β€” wrap the lookup in `withSnapshot` so it polls. * **It is in the list, but your predicate isn't matching.** Almost always: the label is in `description` or `value` instead of `name`, or there's a stray icon-font glyph you didn't strip. See chapter 7. ### 9.2 Common root causes A handful of issues account for most "where did my element go" problems: * **The label is in `description`, `value`, or `helpText`, not `name`.** Use `labelOf` (chapter 7) instead of `node.name` directly. * **The element has no `refId`.** Structural wrappers (groups, panes) often share a name with their actionable children but don't get a refId of their own. Always filter with `n.refId != null` in your predicate. * **You're looking inside the wrong subtree.** Browser chrome (URL bar, bookmarks bar) lives at the top of the snapshot; the active page is inside the last `AriaRole.Document`. Use `pageNodes` (chapter 7) when you only want page content. * **The page renders after your snapshot.** Wrap the find in `withSnapshot` rather than bumping a brittle `sleep`. * **The element appears, then disappears.** SPAs sometimes re-mount nodes mid-update. `withSnapshot` retries on a fresh snapshot each tick; bare `find` doesn't. * **You're bound to the wrong window.** `AccessibilityTree.fromForeground()` binds to whichever app is frontmost *at the moment of the call*. If a notification stole focus during your `sleep`, you'll get its tree instead. `fromPid(instance.pid)` is the safer choice when you have a pid. ### 9.3 Iterate in the REPL When you're stuck on a predicate, `simulang run -i` is much faster than editing-and-rerunning the whole script. Bring the target app to the front first, then: ``` $ simulang run -i > const tree = AccessibilityTree.fromForeground() > const root = tree.snapshot(true) > flattenDFS(root).filter((n) => n.role === AriaRole.Button).map((n) => n.name) [ 'Sign in', 'Cancel', '' ] ``` `fromForeground()` binds to whatever's active at the moment of the call β€” that's why the app needs to be focused before you run it. *** ## 10. A complete example Let's tie everything together. The script below opens `automationexercise.com` (a public test site), confirms we're logged out, signs in with credentials from environment variables, and signs out again. We verify each state transition through the accessibility tree. ```ts theme={null} // login-and-out.ts import { AccessibilityTree, App, AriaRole, FocusPolicy, Visibility, } from '@simular-ai/simulang-js' const email = process.env.SITE_EMAIL const password = process.env.SITE_PASSWORD if (!email || !password) { console.error('Set SITE_EMAIL and SITE_PASSWORD before running.') process.exit(1) } const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) const stripPUA = (s) => s.replace(/[-]/g, '').replace(/\s+/g, ' ').trim() const labelOf = (n) => stripPUA([n.name, n.value, n.description, n.helpText].filter(Boolean).join(' ')) function flattenDFS(node, out = []) { out.push(node); for (const c of node.children) flattenDFS(c, out); return out } async function withSnapshot(tree, predicate, opts = {}) { const { timeoutMs = 8000, intervalMs = 250, label = 'node' } = opts const deadline = Date.now() + timeoutMs while (Date.now() < deadline) { const root = tree.snapshot(true) const hit = predicate(flattenDFS(root)) if (hit) return hit await sleep(intervalMs) } throw new Error(`Timed out waiting for ${label}`) } const isLink = (n, re) => n.role === AriaRole.Link && re.test(labelOf(n)) && n.refId != null const findLink = (nodes, re) => nodes.find((n) => isLink(n, re)) const SIGNUP_LOGIN = /^signup \/ login$/i const LOGOUT = /^logout$/i try { // 1. Open the site. const instance = App.defaultBrowser().open( 'https://automationexercise.com', FocusPolicy.Steal, Visibility.Show, true, ) await sleep(2500) if (!instance.isAccessible()) instance.enableAccessibility() const tree = AccessibilityTree.fromPid(instance.pid) // 2. Make sure we're logged out (self-heal from stale sessions). const navState = await withSnapshot( tree, (nodes) => { const logout = findLink(nodes, LOGOUT) if (logout) return { kind: 'logged-in', logout } if (findLink(nodes, SIGNUP_LOGIN)) return { kind: 'logged-out' } return null }, { label: 'nav with Signup/Login or Logout' }, ) if (navState.kind === 'logged-in') { tree.activate(navState.logout.refId) await withSnapshot( tree, (nodes) => findLink(nodes, SIGNUP_LOGIN) && !nodes.some((n) => isLink(n, LOGOUT)), { label: 'logged-out state' }, ) } // 3. Click "Signup / Login". const loginLink = await withSnapshot(tree, (nodes) => findLink(nodes, SIGNUP_LOGIN), { label: '"Signup / Login" link', }) tree.activate(loginLink.refId) // 4. Find the login form positionally and fill it. const { emailField, passField, loginBtn } = await withSnapshot( tree, (nodes) => { const hIdx = nodes.findIndex((n) => /^login to your account$/i.test(labelOf(n))) if (hIdx === -1) return null const btnIdx = nodes.findIndex( (n, i) => i > hIdx && n.role === AriaRole.Button && /^login$/i.test(labelOf(n)), ) if (btnIdx === -1) return null const inputs = nodes.slice(hIdx, btnIdx).filter( (n) => n.role === AriaRole.Textbox && n.refId != null, ) if (inputs.length < 2) return null return { emailField: inputs[0], passField: inputs[1], loginBtn: nodes[btnIdx] } }, { label: 'login form' }, ) tree.setValue(emailField.refId, email) tree.setValue(passField.refId, password) tree.activate(loginBtn.refId) // 5. Confirm login by waiting for the Logout link, then click it. const logoutLink = await withSnapshot(tree, (nodes) => findLink(nodes, LOGOUT), { label: 'Logout link', timeoutMs: 10000, }) tree.activate(logoutLink.refId) // 6. Confirm logout. await withSnapshot( tree, (nodes) => findLink(nodes, SIGNUP_LOGIN) && !nodes.some((n) => isLink(n, LOGOUT)), { label: 'logged-out confirmation' }, ) console.log('done.') } catch (error) { console.error('Failed:', error instanceof Error ? error.message : error) process.exit(1) } ``` Most real scripts are some variant of this shape: * **Imports at the top**, secrets from `process.env`. * **A handful of small helpers** (`sleep`, `labelOf`, `flattenDFS`, `withSnapshot`) β€” the chapter-7 note about script-local helpers applies here. * **One big `try`/`catch`** with `process.exit(1)` on failure. * **Numbered phases**, each one a `withSnapshot` that names what it's waiting for. The names double as breadcrumbs in the logs. *** ## 11. When accessibility isn't enough The accessibility tree is the right tool nine times out of ten, but not always. Two escape hatches: ### 11.1 Hardware mouse and keyboard When a control has no `refId` β€” a canvas, an embedded video player, an OS-level dialog the app doesn't expose β€” drop to real coordinates and key events: ```ts theme={null} import { MouseController, KeyboardController, Button, Direction, Coordinate, Key, } from '@simular-ai/simulang-js' const mouse = new MouseController() mouse.moveMouse(640, 360, Coordinate.Abs) // absolute screen pixels mouse.button(Button.Left, Direction.Click) // press + release const kb = new KeyboardController() kb.text('hello world') // types via the OS input layer kb.key(Key.Enter) // a single named key ``` `Coordinate.Abs` is absolute pixels; `Coordinate.Rel` is movement *relative to the current cursor position*. For drag-and-drop, send `Direction.Press`, move, then `Direction.Release`. ### 11.2 Vision grounding When you can *see* the element but neither the OS nor your regex can find it, take a screenshot and ask a vision model where it is: ```ts theme={null} import { Screen, screenshotFull, GroundingModel } from '@simular-ai/simulang-js' const shot = screenshotFull(true, Screen.mainScreen()) // hide the cursor const [x, y] = shot.ground(GroundingModel.default(), 'the blue Continue button') mouse.moveMouse(x, y, Coordinate.Abs) mouse.button(Button.Left, Direction.Click) ``` `shot.ground(model, query)` returns absolute screen coordinates for whatever the model thinks best matches your natural-language query. A few practical notes: * Pass `true` to `screenshotFull` to hide the cursor β€” otherwise the model may describe the cursor as part of the UI. * Grounding is **network-bound**: it needs `OPENROUTER_API_KEY` set. * Vision grounding is your last resort, not your first move. It's slower, costs money, and is less reliable than the accessibility tree. Use it for the 1% of cases where nothing else works. *** ## 12. Files, env vars, and shelling out There are no Simulang-specific I/O wrappers. Use Node's standard library directly: ```ts theme={null} import { readdirSync, readFileSync, writeFileSync, renameSync, statSync, existsSync } from 'node:fs' import { spawn, spawnSync } from 'node:child_process' import { join, dirname } from 'node:path' import { fileURLToPath } from 'node:url' // Resolve "the directory of this script." const HERE = dirname(fileURLToPath(import.meta.url)) // Plain I/O. writeFileSync(join(HERE, 'out.txt'), 'hello\n') const text = readFileSync(join(HERE, 'out.txt'), 'utf8') // Shell out β€” captured output. const result = spawnSync('python3', ['transform.py', 'in.csv'], { encoding: 'utf8' }) if (result.status !== 0) throw new Error(result.stderr) // Fire-and-forget β€” open a file with the OS default app. spawn('open', [join(HERE, 'out.txt')], { detached: true, stdio: 'ignore' }).unref() ``` `import.meta.url` + `fileURLToPath` is the ES-module equivalent of the CommonJS `__dirname`. Use it any time you need to resolve a path relative to the script itself. The `@simular-ai/simulang-js` package also ships convenience classes β€” `File`, `Directory`, `Clipboard`, `System` β€” when you want cross- platform helpers (an OS clipboard read, a temp directory with an explicit lifecycle). They're worth using for clipboard and audio work; for plain file reads and writes, staying in `node:fs` keeps the concept count low. *** ## 13. Composing scripts As workflows grow, you'll want to split them up. There are two natural ways. ### 13.1 Import helpers from sibling modules The simplest: extract reusable functions into their own files and import them. ```ts theme={null} // flow/login.mjs export async function login(tree, { email, password }) { // … positional find + setValue + activate, as in chapter 10 … } ``` ```ts theme={null} // flow/checkout.mjs export async function placeOrder(tree, item) { // … } ``` ```ts theme={null} // run.mjs import { App, FocusPolicy, Visibility, AccessibilityTree } from '@simular-ai/simulang-js' import { login } from './flow/login.mjs' import { placeOrder } from './flow/checkout.mjs' App.defaultBrowser().open('https://example.com', FocusPolicy.Steal, Visibility.Show, true) const tree = AccessibilityTree.fromForeground() await login(tree, { email: process.env.SITE_EMAIL, password: process.env.SITE_PASSWORD }) await placeOrder(tree, 'blue-shirt') ``` This is just ES modules β€” there's nothing Simulang-specific to learn. Pass shared resources (the `tree`, the `instance`) as arguments rather than reaching for module-level singletons. ### 13.2 Run other scripts as subprocesses When you want full isolation between phases β€” fresh process, fresh state, no shared imports β€” orchestrate from a parent script: ```ts theme={null} // orchestrator.mjs import { spawnSync } from 'node:child_process' import { dirname, join } from 'node:path' import { fileURLToPath } from 'node:url' const HERE = dirname(fileURLToPath(import.meta.url)) function runStep(label, script) { console.log(`\n===== ${label} =====`) const result = spawnSync('simulang', ['run', join(HERE, script)], { stdio: 'inherit', // stream the child's logs live env: process.env, // pass env vars through (SITE_EMAIL, OPENROUTER_API_KEY, …) }) if (result.status !== 0) { console.error(`"${label}" failed with exit ${result.status}.`) process.exit(result.status ?? 1) } } runStep('Sign in', 'sign-in.ts') runStep('Place order', 'place-order.ts') runStep('Download receipt', 'download-receipt.ts') ``` The big win: each step is **independently runnable**. If `place-order.ts` fails, you can iterate on it directly without re-running sign-in every time. *** ## 14. Common pitfalls A short list of things that bite first-time users (and second- and third-time users, honestly). ```ts theme={null} // β‘  refIds are tied to one snapshot. Don't cache them. const btn = flattenDFS(tree.snapshot(true)).find(...) await sleep(2000) // ← the page may have re-rendered tree.activate(btn.refId) // ⚠ stale refId // βœ“ Re-snapshot inside withSnapshot and act on a fresh ref. ``` ```ts theme={null} // β‘‘ AriaRole is a numeric enum. AriaRole[role] does NOT give a string. console.log(AriaRole[node.role]) // ⚠ undefined console.log(ariaRoleToString(node.role)) // βœ“ "button" ``` ```ts theme={null} // β‘’ FocusPolicy and Visibility are advisory. App.exactName('Google Chrome').open(null, FocusPolicy.DoNotSteal, Visibility.Hidden, false) // ⚠ Chromium / Electron apps and macOS Notes ignore these flags. The // app pops to the foreground and stays visible regardless. // βœ“ If you need certainty the app is focused, check and force it: if (!instance.isFocused()) instance.focus() // βœ“ If you need it hidden, call .hide() after the launch settles: await sleep(500) instance.hide() ``` ```ts theme={null} // β‘£ The accessible label can live in any of four fields. node.name === 'Sign in' // ⚠ might be in description on web AX labelOf(node) === 'Sign in' // βœ“ uses name|value|description|helpText ``` ```ts theme={null} // β‘€ Browser chrome contaminates snapshots. nodes.find((n) => /save/i.test(labelOf(n))) // ⚠ might match the URL bar pageNodes(root).find(/* … */) // βœ“ scope to the active tab ``` ```ts theme={null} // β‘₯ There is no built-in sleep / wait. Roll your own. const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) ``` ```ts theme={null} // ⑦ Top-level errors print ugly stack traces. Wrap and exit. try { // … your script … } catch (e) { console.error('Failed:', e instanceof Error ? e.message : e) process.exit(1) } ``` One more worth mentioning that doesn't fit a one-liner: * **Temp directories don't auto-clean.** If you use `Directory.temp()`, wrap the work in `try { … } finally { dir.remove() }`. *** ## 15. Where to go next You now know enough to write real Simulang scripts. From here: * **Clone the [Simulang Recipes](https://github.com/simular-ai/simulang-recipes) repo.** It's a growing collection of community-built automations β€” a Wordle solver, a 2048 bot, a Calendar-to-Docs digest, a daily news digest into Apple Notes, a TikTok-to-Slack forwarder, and more. Each recipe is a small, self-contained script with its own README; pick one close to what you want to build, run it, then read the source. Contributions welcome. * **Read `index.d.ts`** in the resolved `@simular-ai/simulang-js` install. It's the typed surface of the library β€” roughly 1500 lines, organised by class. Source of truth for signatures and enums, and the entry point to everything we didn't cover here (audio capture, speech-to-text, screen recording). * **Read the library's `CLAUDE.md`** next to `index.d.ts`. It covers idioms, lifecycle preconditions, and platform quirks β€” things types can't express. * **Browse the example scripts** in `examples/` inside the install. They're the best place to see larger patterns: a full purchase flow, file downloads with rename, screenshot-and-ground, module composition. * **Build your reflexes at the REPL.** When you're not sure how an API behaves, `simulang run -i` is faster than scripting it. Snapshots are cheap; experiment. Welcome to Simulang. Have fun automating things that used to need a human in the chair. *** ## 16. Simulang in Claude Code If you use **Claude Code** in the editor, you can drive the same desktop APIs without hand-writing every script: install the skill and use `/simulang` so Claude generates and runs automation for you. See **[Simulang with Claude Code](/simulang/simulang-claude-code)** for setup (`simulang init-claude`), example prompts, permissions, and tips. # Simulang v0 examples Source: https://docs.simular.ai/simular-pro/examples Example prompts and Simulang v0 snippets for Simular Pro β€” the in-app v0 action vocabulary. The best way to master Simular Pro is to learn from the example instructions (prompts) and corresponding **Simulang v0** code on this page. Just run the instructions on your Simular Pro to reproduce similar **Simulang v0** code, or copy the snippets on this page and execute them in the app. > [!NOTE] > > **Simulang v0 only β€” not the latest Simulang.** These examples apply **only** to **Simulang v0** embedded in **Simular Pro**. They do **not** match the current standalone Simulang CLI, `simulang-js`, or other **newer Simulang** surfaces; syntax and actions can differ. Use this page with the [Simulang v0 API reference](/simular-pro/simulang). For the latest scripting model, see the [Simulang Primer](/simulang/simulang-primer) and [Simulang with Claude Code](/simulang/simulang-claude-code). Find out how to: * [Read structured information](/simular-pro/examples#reading-structured-information) * [Repeat a task on multiple objects](/simular-pro/examples#repeating-a-task-on-multiple-objects-on-a-page) * [Write structured output](/simular-pro/examples#structured-information-output) * [Locate an element precisely](/simular-pro/examples#clicking-on-ui-elements) You can always refer to the [Simulang v0 API documentation](/simular-pro/simulang) if you need a refresher on each Simulang v0 action. > [!WARNING] > > Most of the **Simulang v0** code on this page was generated in one shot from the instructions. > Since there may be differences in individual machine configurations (e.g. browser settings), we recommend that you double check the Simulang v0 snippets before executing. > [!TIP] > > If Simular Pro did not click on an element you intended, try these [various methods](#clicking-on-ui-elements) for element localization. ## Reading structured information Many workflows start with extracting information from an application or webpage. Moreover, the extracted information often needs to be represented in a particular structure. For example: * A house on sale has the following fields: address, square footage, number of beds and baths, etc. * An email has these fields: sender address, time sent, title, etc. This section shows you how to instruct Simular Pro to extract information from diverse sources into structured forms. The resulting information will be ready for downstream workflow steps, such as [iterating a subtask over multiple elements](#repeating-a-task-on-multiple-objects-on-a-page) or [writing structured outputs to files](#structured-information-output). ### Community and communication applications: Extracting channel names on a desktop community app ```text Instruction theme={null} Open Discord Get the page content and extract the top 10 server names visible in the left sidebar. Do not include direct messages. ``` **Simulang v0** ```javascript Simulang v0 theme={null} function main() { // Open Discord open({app: "Discord"}); let servers = []; // Get page content and analyze servers var content = pageContent(); // Extract list of servers from the sidebar var serverList = ask({ prompt: "List the top 10 Discord server names visible in the left sidebar. Do not include the direct messages. Return as JSON array. Do not say anything else.", context: content }); servers = JSON.parse(serverList); return servers; } ``` ### Shopping: Get all store locations of a grocery chain ```text Instruction theme={null} Go to Wegmans stores webpage. Get all the locaitons and print them out. ``` **Simulang v0** ```javascript Simulang v0 theme={null} function main() { // Open Wegmans stores webpage open({url: "https://www.wegmans.com/stores"}); wait({waitTime: 2}); // Get page content and extract all locations var content = pageContent(); var locationsResponse = ask({ prompt: "Extract all store locations from this page. Return a JSON array of location names (cities/towns where Wegmans stores are located). Do not say or explain anything else, just return the requested data.", context: content }); var locations = JSON.parse(locationsResponse); // Print out all locations console.log("Wegmans Store Locations:"); for (let i = 0; i < locations.length; i++) { console.log(`${i + 1}. ${locations[i]}`); } return {status: "completed", totalLocations: locations.length, locations: locations}; } ``` ### Social media URL scraping: Get a company's social media URLs ```text Instruction theme={null} Go to simular.ai Get all of their social media URLs and print them out ``` **Simulang v0** ```javascript Simulang v0 theme={null} function main() { // Go to simular.ai open({url: "https://simular.ai"}); wait({waitTime: 3}); // Get page content const content = pageContent(); // Ask for social media URLs with explicit JSON format request const result = ask({ prompt: "Find all social media URLs on this page (Twitter, LinkedIn, YouTube, Facebook, Instagram, Discord, etc.). Return as a JSON array of URLs only. Do not say or explain anything else, just return the requested data.", context: content }); // Parse the JSON response const socialMediaUrls = JSON.parse(result); // Print out all social media URLs console.log("Social media URLs found on simular.ai:"); for (const url of socialMediaUrls) { console.log(url); } return {success: true, socialMediaUrls: socialMediaUrls}; } ``` ### News: Get all headlines from a news site ```text Instruction theme={null} Go to techcrunch, get all the news headlines, and print them out. ``` **Simulang v0** ```javascript Simulang v0 theme={null} function main() { // Open TechCrunch website open({url: "https://techcrunch.com"}); wait({waitTime: 3}); // Get page content const content = pageContent(); // Ask LLM to extract all news headlines const headlinesResponse = ask({ prompt: "Extract all news headlines from this TechCrunch page. Return only a JSON array of headline strings. Do not include any other text or explanation.", context: content }); // Parse the JSON response const headlines = JSON.parse(headlinesResponse); // Print out all headlines console.log("TechCrunch News Headlines:"); console.log("=========================="); for (let i = 0; i < headlines.length; i++) { console.log(`${i + 1}. ${headlines[i]}`); } return {success: true, headlinesCount: headlines.length}; } ``` ### Investing: Get an investment firm's list of portfolio companies ```text Instruction theme={null} Go to a16z's portfolio page and get all the features company names on the page. ``` **Simulang v0** ```javascript Simulang v0 theme={null} function main() { // Open Chrome and navigate to a16z portfolio page open({url: "https://a16z.com/portfolio"}); let allCompanies = new Set(); // Get current page content let content = pageContent(); // Extract visible company names let response = ask({ prompt: "This is the a16z portfolio page. List all visible featured portfolio company names on the page. Do not include a16z itself or any navigation elements. Return as JSON array of strings. Do not say or explain anything else, just return the requested data.", context: content }); allCompanies = JSON.parse(response); // Convert to sorted array and display results let sortedCompanies = Array.from(allCompanies).sort(); console.log(`Found ${sortedCompanies.length} featured companies on a16z's portfolio page:`); console.log(sortedCompanies.join("\n")); return { success: true, totalCompanies: sortedCompanies.length, companies: sortedCompanies }; } ``` ### Email management: Get the sender, date, and summary of the first unread email. ```text Instruction theme={null} Go to gmail.com Click the first unread email From the email content, get: sender email address, date, summary of topic ``` **Simulang v0** ```javascript Simulang v0 theme={null} function main() { // Go to Gmail open({url: "https://gmail.com"}); wait({waitTime: 3}); // Click the first unread email clickFirstUnreadEmail(); // Get email information let emailInfo = getEmailInfo(); // Output the results console.log(`Sender Email: ${emailInfo.senderEmail}`); console.log(`Date: ${emailInfo.date}`); console.log(`Summary: ${emailInfo.summary}`); return emailInfo; } //@ Click the first unread email function clickFirstUnreadEmail() { let content = pageContent(); let firstUnreadEmail = ask({ prompt: "Find the first unread email in the inbox and return its subject line or identifying text that can be clicked. Return only the clickable text, nothing else.", context: content }); click({concept: firstUnreadEmail}); wait({waitTime: 2}); } //@ Get email information including sender, date, and summary function getEmailInfo() { let content = pageContent(); let emailData = ask({ prompt: "From this email content, extract: 1) sender email address, 2) date of the email, 3) a brief summary of the topic/subject. Return as JSON with keys 'senderEmail', 'date', 'summary'. Do not say or explain anything else, just return the requested JSON data.", context: content }); return JSON.parse(emailData); } ``` ### Real estate: Get address, number of bedrooms and bathrooms, square footage, and price of homes in Palo Alto ```text Instruction theme={null} Go to redfin palo alto zip 14325 Get all the address, number of bed, number of bath, square feet, and price of the houses ``` **Simulang v0** ```javascript Simulang v0 theme={null} function main() { // Open Chrome and go to Redfin Palo Alto open({app: "Google Chrome"}); wait({waitTime: 2}); // Navigate to Redfin Palo Alto press({key: "l", cmd: true}); type({text: "redfin.com/city/14325/CA/Palo-Alto", withReturn: true}); wait({waitTime: 3}); // Get all house listings data let houseData = getHouseListings(); // Log the results console.log("House listings in Palo Alto:"); for (let i = 0; i < houseData.length; i++) { console.log(`House ${i + 1}:`); console.log(`Address: ${houseData[i].address}`); console.log(`Bedrooms: ${houseData[i].bedrooms}`); console.log(`Bathrooms: ${houseData[i].bathrooms}`); console.log(`Square Feet: ${houseData[i].squareFeet}`); console.log(`Price: ${houseData[i].price}`); console.log("---"); } return {status: "completed", houses: houseData}; } //@ Get all house listings with address, bedrooms, bathrooms, square feet, and price function getHouseListings() { // Get page content let content = pageContent(); // Ask LLM to extract house data let result = ask({ prompt: "Extract all house listings from this Redfin page. For each house, get: address, number of bedrooms, number of bathrooms, square feet, and price. Return as a JSON array with objects containing fields: address, bedrooms, bathrooms, squareFeet, price. Do not say or explain anything else, just return the requested JSON data.", context: content }); let houseData = JSON.parse(result); return houseData; } ``` ## Repeating a task on multiple objects on a page Having successfully used Simular Pro to [read structured information](#reading-structured-information), such as getting 1. all the names of companies on a page, or 2. all the store locations of a grocery chain, or 3. all the influencer channel names, etc. now you may need to repeat some task on each of those items, such as: 1. checking each company's stock prices, 2. each grocery store's items on sale 3. each influencer's subscriber count The following examples show how to instruct Simular Pro to iterate through all the items and do a follow-up task reliably on each item. ### Opening and reading all Simular blog posts ```text Instruction theme={null} Go to simular.ai/blog Get all the blog post URLs For each blog post URL, open it, extract the post title and a short summary, then close the tab. Print out the post titles and summaries. ``` **Simulang v0** ```javascript Simulang v0 theme={null} //@ Go to simular.ai/blog and get all blog post URLs function getBlogPostUrls() { open({url: "simular.ai/blog"}) wait({waitTime: 3}) var content = pageContent() var result = ask({ prompt: "Find all blog post URLs on this page. Return as a JSON array of complete URLs only. Do not say or explain anything else, just return the requested data.", context: content }) return JSON.parse(result) } //@ Extract title and summary from a blog post function extractPostInfo(url) { open({url: url}) wait({waitTime: 3}) var content = pageContent() var result = ask({ prompt: "Extract the blog post title and create a short summary (2-3 sentences) of the main content. Format as a JSON object with fields 'title' and 'summary'. Do not say or explain anything else, just return the requested data.", context: content }) return JSON.parse(result) } function main() { // Get all blog post URLs var blogUrls = getBlogPostUrls() var allPosts = [] // Process each blog post for (var i = 0; i < blogUrls.length; i++) { var url = blogUrls[i] // Extract title and summary var postInfo = extractPostInfo(url) postInfo.url = url allPosts.push(postInfo) // Close the current tab press({key: "w", cmd: true}) wait({waitTime: 1}) console.log(`Title: ${postInfo.title}`) console.log(`Summary: ${postInfo.summary}`) console.log(`URL: ${url}`) console.log("---") } return { success: true, posts: allPosts } } ``` ## Structured information output The sections above show you how Simular Pro can [read structured information](#reading-information-from-an-application-or-webpage) and [repeats a task](#repeating-a-task-on-multiple-objects-on-a-page) on 100 webpages - now you need it to write that valuable information somewhere. This section shows you many options to write structured output to a local file on disk or a web browser application. If you cannot find an output format you need, just ask us on [Discord](https://discord.gg/E2XfsK9fPV). ### Writing information into a Google Sheet ```text Instruction theme={null} Open a new Google Sheet Add headers Name, Summary, Date Write "Simular", "Simular pro can do anything!", "08/30/2025" into the first row. ``` **Simulang v0** ```javascript Simulang v0 theme={null} function main() { // Create a new Google Sheet open({url: "https://sheets.google.com/create"}); wait({waitTime: 2}); // Add headers setGoogleSheetCellValue({cell: "A1", value: "Name"}); setGoogleSheetCellValue({cell: "B1", value: "Summary"}); setGoogleSheetCellValue({cell: "C1", value: "Date"}); // Add data to the first row (row 2, since row 1 has headers) setGoogleSheetCellValue({cell: "A2", value: "Simular"}); setGoogleSheetCellValue({cell: "B2", value: "Simular pro can do anything!"}); setGoogleSheetCellValue({cell: "C2", value: "08/30/2025"}); return {success: true}; } ``` ### Writing information into Excel ```text Instruction theme={null} Open a new blank sheet in Excel Add headers Name, Summary, Date Write "Simular", "Simular pro can do anything!", "08/30/2025" into the first row. ``` **Simulang v0** ```javascript Simulang v0 theme={null} function main() { // Open Excel and create a new blank sheet open({app: "Microsoft Excel"}); // Create new blank workbook press({key: "n", cmd: true}); wait({waitTime: 2}); // Add headers in the first row click({concept: "cell A1"}); type({text: "Name"}); press({key: "tab"}); type({text: "Summary"}); press({key: "tab"}); type({text: "Date"}); // Move to the second row and add the data click({concept: "cell A2"}); type({text: "Simular"}); press({key: "tab"}); type({text: "Simular pro can do anything!"}); press({key: "tab"}); type({text: "08/30/2025"}); return {success: true}; } ``` ## Clicking on UI elements Sometimes, the basic `click({at: })` may not be enough for Simular Pro to identify a unique element. This may happen when more than one element share the same text description, or when the target element only has a visual label (e.g., image or icon). In these cases, you have two options: 1. In Settings, enable vision fallback for the click action. Simular Pro will automatically attempt to use the best method for UI localization. 2. Use more precise inputs to the `click` function, as shown by examples below. You can find the full specification of inputs to the `click` function [here](simulang#click). > [!TIP] > > Use the element picker tool ![](https://mintcdn.com/simular/PrNYTyoRhGytL_hQ/images/picker.png?fit=max\&auto=format\&n=PrNYTyoRhGytL_hQ\&q=85\&s=c24b9ec85a6e895d209ceb33eabc7253) to check the text description of your target element. ### Clicking one of multiple elements that have the same description or image. This pattern is a powerful and fast way to localize a target element whose textual description may not be unique: ``` click({ at: , spatialRelation: , anchorConcept: }) ``` You may use one from each of the following three spatial relation categories for `spatialRelation`: * distance: closest, furthest * positional filters: left, right, above, below, * containment filters: contains, containedIn For example, this will find the unique element called "link Introduction" that is above of and closest to a unique element called "heading Simular Pro": ``` click({ at: "link Introduction", spatialRelation: "above,closest", anchorConcept: "heading Simular Pro" }) ``` Here is an example drawn from this current page: ```text Instruction theme={null} Go to docs.simular.ai Click on Introduction closest to Getting Started Click on Introduction closest to Simulang Click on Introduction closest to Agent S Click on Introduction closest to Simular ``` **Simulang v0** ```javascript Simulang v0 theme={null} function main() { // Go to docs.simular.ai open({url: "https://docs.simular.ai"}); // Click on Introduction closest to Getting Started click({at: "Introduction", spatialRelation: "closest", anchorConcept: "Getting Started"}); wait({waitTime: 1}); // Click on Introduction closest to Simulang click({at: "link Introduction", spatialRelation: "below,closest", anchorConcept: "heading Simulang", mode: "anchorGrounding"}) wait({waitTime: 1}); // Click on Introduction closest to Agent S click({at: "link Introduction", spatialRelation: "above,closest", anchorConcept: "heading Agent S", mode: "anchorGrounding"}) wait({waitTime: 1}); // Click on Introduction closest to Simular click({at: "link Introduction", spatialRelation: "below,furthest", anchorConcept: "link Blog", mode: "anchorGrounding"}) wait({waitTime: 1}); return {success: true}; } ``` When attempting to close a popup window, you may need to distinguish between the close button of the popup window and the close button of the outer application. You can instruct Simular Pro to click the close button contained in the dialog window. > [!TIP] > > Use the element picker tool ![](https://mintcdn.com/simular/PrNYTyoRhGytL_hQ/images/picker.png?fit=max\&auto=format\&n=PrNYTyoRhGytL_hQ\&q=85\&s=c24b9ec85a6e895d209ceb33eabc7253) to get the description of the anchor element. ```text Instruction theme={null} Click the close button contained in the group dialog. ``` **Simulang v0** ```javascript Simulang v0 theme={null} function main() { Click({ at: "button close", spatialRelation: "containedIn", anchorConcept: "group dialog Find and replace" }); } ``` ### Clicking on an element without text description If your target element is a pure image without any text description, then you should use the vision mode to localize the element: ``` click({at: , mode: "vision"}) ``` > [!TIP] > > Use the element picker tool ![](https://mintcdn.com/simular/PrNYTyoRhGytL_hQ/images/picker.png?fit=max\&auto=format\&n=PrNYTyoRhGytL_hQ\&q=85\&s=c24b9ec85a6e895d209ceb33eabc7253) to check whether your target element has any useful text description. ```text Instruction theme={null} Go to docs.simular.ai Click the Simular logo using vision ``` **Simulang v0** ```javascript Simulang v0 theme={null} function main() { // Navigate to docs.simular.ai open({url: "https://docs.simular.ai"}); click({at: "simular logo", mode: "vision"}) } ``` Sometimes you may need to click on an empty space on the current screen, such as when applying a signature to some area of a document. ```text Instruction theme={null} Click the empty space below the date. ``` **Simulang v0** ```javascript Simulang v0 theme={null} function main() { click({at: "the space below the date", mode: "vision"}) } ``` ### Clicking on an element using both text and screenshot If neither specifying spatial relations nor pure vision work, you may need a combination of both to localize an element. The mode `textAndScreenshot` is able to localize any element that has a text description. ``` click({at: , mode: "textAndScreenshot"}) ``` You may use any natural language for the description of the element, including any referring expressions (e.g., "link Introduction in the Simulang section") ```text Instruction theme={null} Open docs.simular.ai Click the introduction link in the simulang section ``` **Simulang v0** ```javascript Simulang v0 theme={null} function main() { open({url: "https://docs.simular.ai"}) click({at: "link Introduction in the Simulang section", mode: "textAndScreenshot"}) } ``` # Introduction Source: https://docs.simular.ai/simular-pro/introduction Welcome to Simular Pro documentation **Simular Pro** is an advanced **desktop automation tool** designed to seamlessly automate desktop applications and workflows. By leveraging **fine-grained control** over the operating system, Simular Pro enables users to interact with applications, execute tasks, and streamline complex workflowsβ€”all with AI-driven intelligence. ## Key Features * **Full Desktop Automation** – Automate interactions with applications, files, and system processes just like a human user. * **Fine-Grained Control** – Execute **precise** and **complex** operations within desktop environments. * **Simulang Scripting** – Uses a **JavaScript-based syntax**, making automation flexible and developer-friendly. * **Cross-Application Support** – Control multiple applications and switch between them programmatically. * **Task Automation & AI Agents** – Automate repetitive tasks, schedule workflows, and integrate AI-driven agents. * **Secure & Efficient** – Designed for reliability and security in professional environments. ## System Requirements * **Currently supports macOS 15.0+** * Support for other operating systems is under development. Apply for Windows access [here](https://docs.google.com/forms/d/e/1FAIpQLScp5VbkF3tst1qVuzM1Z1WTfslPWuO5QJfFU9dBe6ljwr0E0Q/viewform). ## Get access Simular Pro is **currently for macOS by invitation only**. Download [here](https://www.simular.ai/simular-pro), try some preview actions for free, and apply for full access today! For **business users**, please **[contact us](mailto:support@simular.ai)** to request early access and explore enterprise solutions. # Simulang v0 Source: https://docs.simular.ai/simular-pro/simulang Simulang v0 API reference β€” the action vocabulary used inside the Simular app. Simular Pro gives you the highest level of flexibility and precise control over the full desktop via Simulang, a specialized set of intuitive and easy-to-use action building blocks defined on top of Javascript. While basic prompting of Simular using the chat mode may produce a good initial plan (in Simulang), full success for complex workflows may require edits to some steps in the plan. > [!NOTE] > > **Simulang v0 (Simular app only).** This page documents the **v0** JavaScript-style actions that run **inside the Simular app** when you author or refine desktop workflows in Simular Pro. It does not describe the standalone Simulang CLI, `simulang-js` scripting, or other surfaces; for those, see the [Simulang Primer](/simulang/simulang-primer) and [Simulang with Claude Code](/simulang/simulang-claude-code). The best way to learn Simulang is by [Simulang v0 examples](/simular-pro/examples). Find out how to: * [Read structured information](/simular-pro/examples#reading-structured-information) * [Repeat a task on multiple objects](/simular-pro/examples#repeating-a-task-on-multiple-objects-on-a-page) * [Write structured output](/simular-pro/examples#structured-information-output) * [Locate an element precisely](/simular-pro/examples#clicking-on-ui-elements) ## General ### Act Completes a task specified in natural language, up to a maximum number of steps. Returns: None ```javascript function theme={null} function Act({ task: String = "", maxSteps: Int = 100 }) ``` ```javascript Find all events of 100 museums in San Francisco theme={null} Act({task: "Find all events of 100 museums in San Francisco", maxSteps: 1000000}) ``` **Parameters** **task** An arbitrary task. **maxSteps** Stop when this number of primitive actions have been executed. ## Application ### Open Open or switch to an application. Returns: None ```javascript function theme={null} function Open({ app: String = null, url: String = null, waitForLoadComplete: Bool = true, waitTime: Int = 0 }) ``` ```javascript open chrome theme={null} Open({app: "Google Chrome"}) ``` ```javascript go to Zoom app theme={null} Open({app: "Zoom"}) ``` ```javascript switch to Slack theme={null} Open({app: "Slack"}) ``` ```javascript go to simular.ai theme={null} Open({url: "https://simular.ai"}) ``` **Parameters** **app** application name, e.g., Google Chrome, iMessage. **url** url address of a web page, e.g., google.com **waitForLoadComplete** Whether or not to wait for the app or URL to complete loading. Default is true. **waitTime** Duration in seconds to wait after opening the app or URL, in addition to the wait for load. ## Keyboard control ### Type Type using the keyboard. Returns: None ```javascript function theme={null} function Type({ text: String, withReturn: Bool = false, waitTime: Int = 0, waitForLoadComplete: Bool = false }) ``` ```javascript Enter John Smith with return theme={null} Type({text: "John Smith", withReturn: true}) ``` ```javascript Type John Smith theme={null} Type({text: "John Smith"}) ``` ```javascript Type https://google.com and press enter theme={null} Type({text: "https://google.com", withReturn: true}) ``` **Parameters** **text** A piece of text to type. **withReturn** Whether or not to press the return (enter) key after typing. **waitTime** Duration in seconds to wait after typing. **waitForLoadComplete** Whether or not to wait for a page to complete loading after typing. ### Shortcut Perform keyboard shortcut in the current application. Returns: None ```javascript function theme={null} function Shortcut({ key: String, cmd: Bool = false, ctrl: Bool = false, option: Bool = false, shift: Bool = false, waitTime: Int = 0 }) ``` ```javascript press ctrl+a theme={null} Shortcut({key: "a", ctrl: true}) ``` ```javascript use shortcut to select all theme={null} Shortcut({key: "a", cmd: true}) ``` ```javascript press cmd+shift+t theme={null} Shortcut({key: "t", cmd: true, shift: true}) ``` ```javascript press option and down arrow theme={null} Shortcut({key: "downArrow", option: true}) ``` ```javascript press enter theme={null} Shortcut({key: "enter"}) ``` **Parameters** **key** A key to be pressed **cmd** Whether the command modifier should be pressed when tapping the key. **ctrl** Whether the control modifier should be pressed when tapping the key. **option** Whether the option modifier should be pressed when tapping the key. **shift** Whether the shift modifier should be pressed when tapping the key. **waitTime** Time in second to wait after executing the action. ## Mouse Control ### Click Click on something, either specified by the `at` argument or the `element` argument. Disambiguate by specifing the spatial relation between the target element and an anchor concept. Available modes: 1. default is text-based grounding. 2. "textAndScreenshot": grounding using both text and vision. 3. "vision": vision-only grounding. When using modes with vision, all other arguments are ignored except `withCommand`, `clickType` and waits. Returns: None ```javascript function theme={null} function Click({ at: String = "", mode: String = "", clickType: String = "left", withCommand: Bool = false, element: UIElement = null, spatialRelation: String = "", anchorConcept: String = "", prior: String = "none", position: String = "center", includeInvisible: Bool = false, waitForLoadComplete: Bool = false, waitTime: Int = 0 }) ``` ```javascript click new tab theme={null} Click({at: "new tab"}) ``` ```javascript cmd+click verify insurance button theme={null} Click({at: "verify insurance button", withCommand: true}) ``` ```javascript double click Styles.zip theme={null} Click({at: "Styles.zip", clickType: "doubleClick"}) ``` ```javascript click "slider" closest to and on the right of "pointer size" theme={null} Click({at: "slider", spatialRelation: "closest,right", anchorConcept: "pointer size"}) ``` **Parameters** **at** Description of a target object to click. For higher accuracy, describe the target object by its role and value, e.g. "sign in button", "first name textfield". **mode** options: "textAndScreenshot", "vision". Leave empty for default text-based grounding. **clickType** Type of click. Options are: "left" (default), "right", and "doubleClick" (two quick left clicks) **withCommand** If true, agent presses the command key during click. **element** A UIElement. If given, ignores the `at` argument and directly clicks on this element. **spatialRelation** A comma-separated String of spatial relationship between the target object and element(s) that best match the `anchorConcept`. Options are: "closest", "furthest", "above", "right", "below", "left", "contains", "containedIn" **anchorConcept** Description of an object used as an anchor with `spatialRelation`. **prior** A optional global spatial location prior used for disambiguation among elements that have similar descriptions. Options are: "left", "right", "top", "bottom". For example, "left" means to choose the left-most element among candidates. **position** Position within the frame of an element to click. Options are: topleft, topcenter, topright, middleleft, center, middleright, bottomleft, bottomcenter, bottomright, anywhere **includeInvisible** Whether or not to find the target from sections of the page that are not currently visible (i.e., needs scrolling). **waitForLoadComplete** If true, waits for page to finish loading after the click. **waitTime** Integer number of seconds to wait after click. ### Move Moves the cursor to an object. Disambiguate by specifing the spatial relation between the target element and an anchor concept. All parameters besides `to` have the same definition as those in the `Click` action. Returns: None ```javascript function theme={null} function Move({ to: String = "", element: UIElement = null, spatialRelation: String = "", anchorConcept: String = "", prior: String = "none", includeInvisible: Bool = false, waitForLoadComplete: Bool = false, waitTime: Int = 0 }) ``` ```javascript Move to textarea below verify insurance theme={null} Move({to: "textarea", spatialRelation: "below", anchorConcept: "verify insurance"}) ``` **Parameters** **to** Description of a target object to click. For higher accuracy, describe the target object by its role and value, e.g. "sign in button", "first name textfield". **mode** See definition in `Click`. **element** See definition in `Click`. **spatialRelation** See definition in `Click`. **anchorConcept** See definition in `Click` **prior** See definition in `Click` **includeInvisible** See definition in `Click` **waitForLoadComplete** See definition in `Click` **waitTime** See definition in `Click` ### Drag Drag on the screen, starting from where the mouse is located Returns: ```javascript function theme={null} function Drag({ to: String = "", element: UIElement = null, destinationApp: String = null }) ``` ```javascript drag to "testFolder" in Google Chrome theme={null} Drag({to: "testFolder", destinationApp: "Google Chrome"}) ``` ```javascript drag to "testFolder" in the same app theme={null} Drag({to: "testFolder"}) ``` **Parameters** **to** the destination of the drag action in string **element** the destination of the drag action as UI Element **destinationApp** the target app, if destination is not in the same application as the origin ### Scroll Scroll on the screen in a specified direction. Returns: None ```javascript function theme={null} function Scroll({ direction: String = "down", distance: Int = 200 }) ``` ```javascript Scroll down theme={null} Scroll({direction: "down"}) ``` ```javascript Scroll up 500 pixels theme={null} Scroll({direction: "up", distance: 500}) ``` ```javascript Scroll left 200 pixels theme={null} Scroll({direction: "left", distance: 200}) ``` ```javascript Scroll right a bit theme={null} Scroll({direction: "right", distance: 100}) ``` ```javascript Scroll down to see more content theme={null} Scroll({direction: "down", distance: 300}) ``` **Parameters** **direction** The direction to scroll (up, down, left, right) Default is down. **distance** The scroll distance in pixels. Default is 200. ## Perception ### stateSatisfies Checks whether the current screen satisfies the specified condition. This is useful for checking complex conditions that cannot be easily checked by [ConceptsExist](#ConceptsExist) with simple element descriptions. However, it may be slower and use more tokens than `ConceptsExist` for large pages. Returns: true if the current screen satisfies the condition, false otherwise. ```javascript function theme={null} function stateSatisfies({ condition: String }) ``` ```javascript if the current state requires login, then respond to the user to request login theme={null} if (stateSatisfies({condition: "requires login"})) { Respond({message: "Please log in", requireConfirm: true}) } ``` **Parameters** **condition** A condition to check on the current screen ### ConceptsExist Checks whether all the concepts can be found on the current visible screen. Each concept must be a substring of the text description of an element in the current focused application. This is faster and more token-efficient than [stateSatisfies](#stateSatisfies) for checking conditions that can be represented by a small set of element descriptions. > [!TIP] > > Use the element picker tool ![](https://mintcdn.com/simular/PrNYTyoRhGytL_hQ/images/picker.png?fit=max\&auto=format\&n=PrNYTyoRhGytL_hQ\&q=85\&s=c24b9ec85a6e895d209ceb33eabc7253) to check the text description of any element in the currently focused application. Returns: If all concepts can be found, returns true, otherwise false. ```javascript function theme={null} function ConceptsExist({ concepts: [String] }) ``` ```javascript if there is a play button, click it theme={null} if (ConceptsExist({concepts: ["play button"]})) { click({at: "play button"}) } ``` ```javascript if the page has a sign in button and a log in button, ask user to log in theme={null} if (ConceptsExist({concepts: ["sign in button", "log in button"]})) { respond({message: "Could you log in?", requireConfirm: true}) } ``` **Parameters** **concepts** An array of target concepts to find. ### pageContent Gets a JSON object containing the structural text content and base64 encoded image of the current screen. This object can be sent to a vision-language model for answering questions about the current screen. Returns: A JSON dictionary with the following fields: * text: A text description of the current web page; * imageFilePath: temporary location in memory of the screenshot (accessible by `ask`). ```javascript function theme={null} function pageContent({ }) ``` ```javascript What is the color of this page? theme={null} var content = pageContent({}); var color = ask({prompt: "What is the color of this page? Return only the color:", context: content}); ``` ## Text Generation ### ask Runs a large vision-language model on the given input prompt string and a JSON dictionary context. Often used after pageContent(). Returns: String response from a large vision language model. ```javascript function theme={null} function ask({ prompt: String, context: [[String: String]] }) ``` ```javascript write a poem about the content of the current page theme={null} var content = pageContent({}); var output = ask({{prompt: "Write a poem about the content", context: content}}); ``` ```javascript check two pages' differences theme={null} var content1 = pageContent({}); doSomething({}) var content2 = pageContent({}); var content = [content1,content2] var output = ask({{prompt: "What are the difference between these two pages? ", context: content}}); ``` **Parameters** **prompt** String query to a large vision language model. **context** Array of JSON dictionaries, each containing the following fields: * text: an optional text description of the current web page. * imageFilePath: an optional path in memory of a screenshot taken by `pageContent()`. Also accepts a single JSON dictionary, such as the output of `pageContent()`. ## Wait ### Wait Put Agent into sleep state for a certain amount of time. Returns: None ```javascript function theme={null} function Wait({ waitTime: Int, unit: String = "s" }) ``` ```javascript Wait for 3s theme={null} Wait({waitTime: 3}) ``` ```javascript Wait for 500ms theme={null} Wait({waitTime: 500, unit: "ms"}) ``` **Parameters** **unit** Options are "s" for seconds (default) and "ms" for milliseconds. **waitTime** Duration of time to wait in the given units. ### WaitForConcepts Waits until all concepts can be found in the current frontmost window. If not all concepts can be found within 10 seconds, action returns failure Returns: None ```javascript function theme={null} function WaitForConcepts({ concepts: [String] }) ``` ```javascript Wait for the log in button and sign up button to show up theme={null} WaitForConcepts({concepts: ["log in button", "sign up button"]}) ``` **Parameters** **concepts** An array of target concepts to find. ## User interaction ### Respond Respond to the user with a short message. Optionally require the user to give a yes/no answer or input text to proceed. Returns: * If `requireConfirm` is true, then this function returns true if the user chooses "yes", returns false if the user chooses "no". * If `requireTextInput` is true, then returns the string value that the user submitted. * Otherwise, returns true ```javascript function theme={null} function Respond({ message: String, requireConfirm: Bool = false, requireTextInput: Bool = false }) ``` ```javascript Ask the user for confirmation theme={null} Respond({message: "Could you confirm?", requireConfirm: true}) ``` ```javascript Output llmResult to the user theme={null} Respond({message: llmResult}) ``` **Parameters** **message** A message to show to the user. **requireConfirm** Whether or not user confirmation is required to proceed with the remaining actions. Default is false. If requireConfirm is true, then the message must be phrased as a question, to which the only possible responses are "yes" and "no". **requireTextInput** Whether or not to require the user to input text before proceeding. Default is false. If requireTextInput is true, then the user will be prompted to input text after the message is shown. ## System IO ### copyToClipboard Copies a String to clipboard. Returns: None ```javascript function theme={null} function copyToClipboard({ text: String }) ``` ```javascript copy cell to the clipboard theme={null} copyToClipboard({text: cell}) ``` **Parameters** **text** Text to be copied to the clipboard. ### GetFromClipboard Get the content of the current clipboard. Returns: Content of the currrent clipboard ```javascript function theme={null} function GetFromClipboard({ }) ``` ```javascript get the clipboard content theme={null} var clipboardContent = GetFromClipboard({}) ``` ### SaveScreenshot Takes a screenshot of an element on the screen or the whole screen, and saves the screenshot as a PNG to a file. Returns: None ```javascript function theme={null} function SaveScreenshot({ element: UIElement = null, fileName: String = null, directory: String = null }) ``` ```javascript Save screenshot of whole screen to screenshot.png theme={null} SaveScreenshot({fileName: "screenshot.png"}) ``` ```javascript Screenshot the group element and save to clipboard theme={null} SaveScreenshot({element: group}) ``` ```javascript Screenshot the table element and save to /User/path/to/screenshot/ theme={null} SaveScreenshot({element: table, directory: "/User/path/to/screenshot/"}) ``` **Parameters** **element** If provided, limit the screenshot to the frame of the element. Default is the whole screen. **fileName** Name for the image name, default is "simularSavedImage.png". **directory** Directory to save the image, default at desktop. ### ScreenshotToClipboard Take a screenshot of an element or the current page and save it to the system clipboard Returns: None ```javascript function theme={null} function ScreenshotToClipboard({ element: UIElement = null }) ``` ```javascript take screenshot and save to clipboard theme={null} ScreenshotToClipboard({}) ``` ```javascript get the table element on the page, save a screenshot of it to clipboard theme={null} var elements = GetElements({elementRoles: ["table"]}) ScreenshotToClipboard({element: elements[0]}) ``` **Parameters** **element** If provided, limit the screenshot to the frame of the element. Default is the whole screen. ### ReadFile Read the contents of a file whose location is specified by `path`. Returns: Contents of the file as a String ```javascript function theme={null} function ReadFile({ path: String }) ``` ```javascript read the file named results.json theme={null} var results = ReadFile({path: "results.json"}) ``` ```javascript get contents of file /Users/somebody/Documents/project/links.txt theme={null} var links = ReadFile({path: "/Users/somebody/Documents/project/links.txt"}) ``` **Parameters** **path** Either an absolute path to a file, or a name of a file (assumed to be in the default app cache directory). ### WriteToFile Writes the given text to a file. If the file already exists, then appends text to it, with an option to overwrite the existing content. Unless specified path, writes to /Library/Caches/com.simular.Simular-Pro/SimularActionResult/ Will throw an error if there is an existing non-folder file named SimularActionResult Returns: None ```javascript function theme={null} function WriteToFile({ text: String, path: String? = "SimularActionResult.txt", overwrite: Bool = false }) ``` ```javascript Append jsonResult to /User/somebody/Documents/result.json theme={null} WriteToFile({text: jsonResult, path: "/User/somebody/Documents/result.json"}) ``` ```javascript Write jsonResult to /User/someone/Desktop/result.json, overwrite existing file. theme={null} WriteToFile({text: jsonResult, path: "/User/someone/Desktop/result.json", overwrite: true}) ``` ```javascript Write jsonResult to default action result file, overwrite existing file. theme={null} WriteToFile({text: jsonResult, overwrite: true}) ``` **Parameters** **text** Text to write to a file. **path** path of the file, default at /Library/Caches/com.simular.Simular-Pro/SimularActionResult/.txt. If path contains "/", treat it as full path **overwrite** Whether or not to overwrite the contents if filePath points to an existing file. ## Google Sheet control ### GetGoogleSheetCellValue Gets the value of a cell in a Google Sheet. Returns: Value of the cell ```javascript function theme={null} function GetGoogleSheetCellValue({ cell: String }) ``` ```javascript get the description of cell B42. theme={null} var cellValue = GetGoogleSheetCellValue({cell: "B42"}) ``` **Parameters** **cell** Label of a cell. Column is indicated by a capital letter and row is indicated by a number. For example "B42" is the cell at column B row 42. ### SetGoogleSheetCellValue Sets the value of a Google Sheet cell. Returns: None ```javascript function theme={null} function SetGoogleSheetCellValue({ cell: String, value: String }) ``` ```javascript write "Simular" into cell B42 theme={null} SetGoogleSheetCellValue({cell: "B42", value: "Simular"}) ``` **Parameters** **cell** Label of a cell. Column is indicated by a capital letter and row is indicated by a number. For example "B42" is the cell at column B row 42. **value** value to write to the cell ### GetGoogleSheetColumns Gets the column ids of each header in a given array of column headers in a Google Sheet. For example, if the sheet has column headers "website", "description", "date" in cells A1, B1, C1, respectively, then `GetGoogleSheetColumns(headers: ["website", "description", "date"])` returns \["A", "B", "C"] Note: This function currently assumes that the table headers are on row 1. Returns: Array of column id, each is a capital letter from A to Z ```javascript function theme={null} function GetGoogleSheetColumns({ headers: [String] }) ``` ```javascript get the columns for the headers "description" and "website" theme={null} var columns = GetGoogleSheetColumns({headers: ["description", "website"]}) ``` **Parameters** **headers** Array of column header ## Advanced GUI functions ### GetElements Get elements that satisfy some conditions inside the current frontmost application or inside a root element (if given). For disambiguation, one can constrain the search to elements that satisfy certain spatial relations to anchor elements. This function supports multiple return types according to `returnType`. Returns: Depending on returnType: \[UIElement], String, \[String], \[String: UIElement] ```javascript function theme={null} function GetElements({ elementRoles: [String] = [], elementOverallDescription: String = "", threshold: Double = 0.75, root: UIElement = null, spatialRelation: String = "", anchorRole: String = "", anchorOverallDescription: String = "", anchorElements: [UIElement] = [], horizontalRank: Int = null, verticalRank: Int = null, sortBy: String = "", useNeighborForMissingDescription: Bool = false, returnType: String = "elementArray" }) ``` ```javascript get all links from the page theme={null} var allLinks = GetElements({elementRoles: ["link"]}) ``` ```javascript Get all comboBox elements to the right of text "state selection" theme={null} var comboBoxes = GetElements({elementRoles: ["comboBox"], spatialRelation: "right", anchorRole: "staticText", anchorOverallDescription: "state selection"}) ``` ```javascript Get all cells in the table and return as dictionary theme={null} var cellDict = GetElements({elementRoles: ["cell"], spatialRelation: "containedIn", anchorRole: "table", returnType: "strToElemDict"}) ``` **Parameters** **elementRoles** Constrains the search to elements whose role is included in this array of roles. Required if elementOverallDescription is not given. **elementOverallDescription** Description of elements to get from the page. Required if elementRoles are not provided. **threshold** If `elementOverallDescription` is given, then accept candidate elements whose normalized string similarity to `elementOverallDescription` is above this threshold value. **root** If given, then the search is limited to elements contained within this root element. **spatialRelation** A comma-separated String of spatial relationships between the target elements and the anchor. Available options are: "closest", "furthest", "above", "right", "below", "left", "contains", "containedIn", "sameRow", "sameColumn" **anchorRole** Role of element(s) used as anchor for spatial relation. **anchorOverallDescription** Description of an object used as an anchor with spatialRelation. **anchorElements** Elements to use as anchor for spatial relation constraints. If `anchorElements` is provided, then anchorRole and anchorOverallDescription are ignored. **horizontalRank** If given, sorts the elements by x-coordinate of frame midpoint and returns the element with this rank. Left-most element has rank 1. **verticalRank** If given, sorts the elements by y-coordinate of frame midpoint and returns the element with this rank. Top-most element has rank 1. **sortBy** Returns the found elements in sorted order, by "x" (left to right) or "y" (top to bottom). Used only if `returnType` is "elementArray". **useNeighborForMissingDescription** Whether or not to use the description of an element's neighbor as a substitute if the element's description is empty. This is only used if returnType involves returning element descriptions. **returnType** Options are: "elementArray" (default), "string", "stringArray", "strToElemDict". * elementArray: returns an array of UIElements * string: returns a semicolon-separated string of descriptions of found elements * stringArray: returns an array of String descriptions of found elements * strToElemDict: returns a \[String: Element] dictionary with element description as keys and corresponding element as value ### GetAttributeOfElement Searches for an element that matches the input criteria and gets the element's value for a specified attribute. Returns: String value of an attribute of an element ```javascript function theme={null} function GetAttributeOfElement({ elementRole: String = "", elementOverallDescription: String = "", attribute: String = "", threshold: Double = 0.75, root: UIElement = null, spatialRelation: String = "", anchorRole: String = "", anchorOverallDescription: String = "", anchorElements: [UIElement] = [], horizontalRank: Int = null, verticalRank: Int = null }) ``` ```javascript Get the value of the radioButton element with description "radioButton tab point & click" theme={null} var value = GetAttributeOfElement({elementRole: "radioButton", elementOverallDescription: "radioButton tab point & click", attribute: "value"}) ``` ```javascript Get the value of the valueIndicator element closest to and on the right of "statictext text double-click speed" theme={null} var value = GetAttributeOfElement({elementRole: "valueIndicator", attribute: "value", spatialRelation: "closest,right", anchorOverallDescription: "statictext text double-click speed"}) ``` **Parameters** **elementRole** Role of the target element. Required if elementOverallDescription is not given. **elementOverallDescription** Description of the element. Required if elementRoles are not provided. **attribute** Valid options are: "role", "description", "title", "value". For example, use "value" to get the value of text elements. **threshold** If `elementOverallDescription` is given, then accept candidate elements whose normalized string similarity with `elementOverallDescription` is above this threshold value. **root** If given, then the search is limited to elements contained within this root element. **spatialRelation** A comma-separated String of spatial relationships between the target elements and the anchor. **anchorRole** Role of element(s) used as anchor for spatial relation. **anchorOverallDescription** Description of an object used as an anchor with spatialRelation. **anchorElements** Elements to use as anchor for spatial relation constraints. If `anchorElements` is provided, then anchorRole and anchorOverallDescription are ignored. **horizontalRank** If given, sorts the elements by x-coordinate of frame midpoint and returns the element with this rank. Left-most element has rank 1. **verticalRank** If given, sorts the elements by y-coordinate of frame midpoint and returns the element with this rank. Top-most element has rank 1. ### GetContent Get text content from the current frontmost window or a region corresponding to the provided concept or element. Returns: If `inElement` argument is given or the frontmost window was used (because neither `inConcept` nor `inElement` was given), then returns a single String. Otherwise, returns a \[String] array with one String per root element. ```javascript function theme={null} function GetContent({ inConcept: String = "", inElement: UIElement = null, format: String = "flat" }) ``` ```javascript get content from page in json format theme={null} var pageContent = GetContent({format: "json"}) ``` ```javascript get content from the table element in XML slim format theme={null} var tableContent = GetContent({inElement: table, format: "xmlSlim"}) ``` ```javascript get content inside group job post details theme={null} var groupContent = GetContent({inConcept: "group job post details"}) ``` **Parameters** **inConcept** Gets content in elements that match this concept. **inElement** Get content in this element. **format** Format of the returned content. Options are: "flat" (unformatted text), "json", "xml", "xmlSlim" (same as XML, with empty tags removed) ### GetCells Get all cells from a row or column element. Either row or column must be given. Returns: An array of cell elements contained in the given row or column. If input is a row, the output array is sorted by increasing x-coordinate (left to right). If input is a column, the output array is sorted by increasing y-coordinate (top to bottom). ```javascript function theme={null} function GetCells({ row: UIElement = null, column: UIElement = null }) ``` ```javascript get all cells in the first row theme={null} var rows = GetElements({elementRoles: ["row"], sortBy: "y"}) var cells = GetCells({row: rows[0]}) ``` **Parameters** **row** A row element that contains one or more cells. **column** A column element that contains one or more cells. ### GetCellValue Get the value of a given cell element. Returns: Value contained in the cell. ```javascript function theme={null} function GetCellValue({ cell: UIElement }) ``` ```javascript Get the value of the cell theme={null} var cellValue = GetCellValue({cell: cell}) ``` **Parameters** **cell** A cell element. ### GetCellLabel Get the label of the given cell element in Excel. Returns: cell's label String. Example: "A1" ```javascript function theme={null} function GetCellLabel({ cell: UIElement }) ``` ```javascript Get the label of the cell theme={null} var label = GetCellLabel({cell: cell}) ``` **Parameters** **cell** A cell element ### GetCellIndices Given an array of table cell values, return a corresponding array of cell indices. For example, suppose the table has value1 in cell A10, then `GetCellIndices(cellValues: ["value1"])` returns \["A10"] Returns: \[String] array of cell indices ```javascript function theme={null} function GetCellIndices({ cellValues: [String] }) ``` ```javascript Get the indices of the cells containing value1 and value2 theme={null} var cellIndices = GetCellIndices({cellValues: ["value1", "value2"]}) ``` **Parameters** **cellValues** values of the cell ### GetTableColumn Given a header or a index String, return the column under it as \[index: Element] dictionary If the table has a column with header "Website" in cell A1, and elements elem1 and elem2 under it, then this function returns \["A2": elem1, "A3": elem2]. Returns: Dictionary of \[String: UIElement] pair for all information in the column under header ```javascript function theme={null} function GetTableColumn({ header: String = null, index: String = null }) ``` ```javascript Get the columns under Website theme={null} var websiteColumn = GetTableColumn({header: "Website"}) ``` ```javascript Get the columns under index A1 theme={null} var A1Column = GetTableColumn({index: "A1"}) ``` **Parameters** **header** value of column header. **index** index of column header, e.g. "B42". ### GetStructuredDescription Gets XML-formatted description of the contents in each element. Returns: An array of String `[s_1, ..., s_n]`, where each `s_i` is an XML-formatted description of the contents rooted at `u_i`. ```javascript function theme={null} function GetStructuredDescription({ fromElements: [UIElement] }) ``` ```javascript get the elements with role "group" and description "group under plan progress", then get description of the elements in XML format theme={null} var elements = GetElements({elementRoles: ["group"], elemOverallDescription: "group under plan progress"}) var description = GetStructuredDescription({fromElements: elements}) ``` **Parameters** **fromElements** An array of UIElements `[u_1, ..., u_n]`.