Skip to content

Computer use CLI for AI agents

feat(ffi): ship C-ABI cdylib with review hardening and release pipeline (#26)

Lahfir3cffbd67f6b2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 082e22bc1..fb65f4524 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -4,7 +4,7 @@ on:
push:
branches: [main, master]
pull_request:
- branches: [main, master]
+ workflow_dispatch:
# Cancel in-progress runs for the same ref so stale PR builds don't burn minutes.
concurrency:
@@ -75,6 +75,13 @@ jobs:
- name: Unit tests
run: cargo test --lib --workspace
+ # The FFI crate ships integration harnesses under crates/ffi/tests/ that
+ # exercise the C-ABI from outside the crate (raw extern "C" decls, enum
+ # fuzzing, out-param zeroing, last-error lifetimes). The workspace --lib
+ # run skips them, so wire them in explicitly so regressions fail PR CI.
+ - name: FFI integration tests
+ run: cargo test -p agent-desktop-ffi --tests
+
# Use the ci profile (no LTO, opt-level 1) — fast compile, still checks the binary builds.
- name: Build binary (ci profile)
run: cargo build --profile ci
@@ -89,3 +96,29 @@ jobs:
exit 1
fi
echo "OK: binary within 15MB limit"
+
+ - name: FFI cdylib build (release-ffi profile)
+ run: cargo build --profile release-ffi -p agent-desktop-ffi
+
+ - name: FFI header drift check
+ run: |
+ # build.rs stamps target/ffi-header-path.txt with the absolute path
+ # to the header produced by the most recent build, so the drift
+ # check always compares against the just-generated artifact rather
+ # than an arbitrary match from `find | head -1` over a warm cache.
+ STAMP=target/ffi-header-path.txt
+ if [ ! -f "$STAMP" ]; then
+ echo "FAIL: $STAMP missing; build.rs did not stamp header path"
+ exit 1
+ fi
+ GENERATED=$(cat "$STAMP")
+ if [ ! -f "$GENERATED" ]; then
+ echo "FAIL: stamped header path does not exist: $GENERATED"
+ exit 1
+ fi
+ if ! diff -u crates/ffi/include/agent_desktop.h "$GENERATED"; then
+ echo "FAIL: crates/ffi/include/agent_desktop.h is out of date"
+ echo "Run 'scripts/update-ffi-header.sh' locally and commit the regenerated header."
+ exit 1
+ fi
+ echo "OK: FFI header is in sync with source"
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 8736528e5..14064d1d7 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -41,7 +41,6 @@ jobs:
timeout-minutes: 30
permissions:
contents: read
- # Both arch targets build in parallel; one failure doesn't block the other.
strategy:
fail-fast: false
matrix:
@@ -97,24 +96,146 @@ jobs:
agent-desktop-v*.tar.gz.sha256
retention-days: 1
+ # FFI cdylib for language-binding consumers (Python/Swift/Go/Ruby/Node/C).
+ # Ships alongside CLI tarballs on the same release tag; npm stays CLI-only.
+ build-ffi:
+ name: Build FFI (${{ matrix.target }})
+ needs: release-please
+ if: needs.release-please.outputs.release_created == 'true'
+ runs-on: ${{ matrix.runner }}
+ timeout-minutes: 30
+ permissions:
+ contents: read
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - target: aarch64-apple-darwin
+ runner: macos-latest
+ archive: tar.gz
+ lib_name: libagent_desktop_ffi.dylib
+ - target: x86_64-apple-darwin
+ runner: macos-latest
+ archive: tar.gz
+ lib_name: libagent_desktop_ffi.dylib
+ - target: x86_64-unknown-linux-gnu
+ runner: ubuntu-22.04
+ archive: tar.gz
+ lib_name: libagent_desktop_ffi.so
+ - target: aarch64-unknown-linux-gnu
+ runner: ubuntu-22.04-arm
+ archive: tar.gz
+ lib_name: libagent_desktop_ffi.so
+ - target: x86_64-pc-windows-msvc
+ runner: windows-latest
+ archive: zip
+ lib_name: agent_desktop_ffi.dll
+ steps:
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ ref: ${{ needs.release-please.outputs.tag_name }}
+
+ - name: Install Rust toolchain
+ run: |
+ rustup show
+ rustup target add ${{ matrix.target }}
+
+ - name: Cache cargo registry
+ uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5
+ with:
+ path: |
+ ~/.cargo/registry/index/
+ ~/.cargo/registry/cache/
+ ~/.cargo/git/db/
+ key: ${{ runner.os }}-${{ matrix.target }}-ffi-cargo-${{ hashFiles('**/Cargo.toml') }}
+ restore-keys: ${{ runner.os }}-${{ matrix.target }}-ffi-cargo-
+
+ - name: Build FFI cdylib (release-ffi profile)
+ run: cargo build --profile release-ffi -p agent-desktop-ffi --target ${{ matrix.target }}
+
+ # build.rs bakes install_name=@rpath/... ; a regression here silently
+ # breaks Swift/SPM consumers, so verify before shipping.
+ - name: Verify macOS install_name
+ if: runner.os == 'macOS'
+ shell: bash
+ run: |
+ ACTUAL=$(otool -D target/${{ matrix.target }}/release-ffi/${{ matrix.lib_name }} | tail -1)
+ EXPECTED="@rpath/libagent_desktop_ffi.dylib"
+ if [ "$ACTUAL" != "$EXPECTED" ]; then
+ echo "FAIL: install_name is '$ACTUAL', expected '$EXPECTED'"
+ exit 1
+ fi
+ echo "OK: install_name = $ACTUAL"
+
+ - name: Stage tarball contents
+ shell: bash
+ run: |
+ VERSION=${{ needs.release-please.outputs.version }}
+ STAGE="agent-desktop-ffi-v${VERSION}-${{ matrix.target }}"
+ mkdir -p "$STAGE/lib" "$STAGE/include"
+ cp "target/${{ matrix.target }}/release-ffi/${{ matrix.lib_name }}" "$STAGE/lib/"
+ cp crates/ffi/include/agent_desktop.h "$STAGE/include/"
+ cp LICENSE "$STAGE/"
+ cat > "$STAGE/README.md" <<EOF
+ # agent-desktop FFI cdylib — v${VERSION} (${{ matrix.target }})
+
+ - \`lib/${{ matrix.lib_name }}\` — shared library
+ - \`include/agent_desktop.h\` — cbindgen header
+ - \`LICENSE\` — Apache-2.0
+
+ Docs: https://github.com/lahfir/agent-desktop/tree/main/skills/agent-desktop-ffi
+
+ macOS \`install_name\` is \`@rpath/libagent_desktop_ffi.dylib\` — linking
+ consumers need \`-rpath\` pointing at the dylib's directory; \`dlopen\` /
+ ctypes callers resolve by path and need nothing.
+ EOF
+ echo "STAGE=$STAGE" >> "$GITHUB_ENV"
+
+ - name: Create archive (Unix)
+ if: runner.os != 'Windows'
+ shell: bash
+ run: |
+ tar -czf "${STAGE}.tar.gz" "${STAGE}"
+ shasum -a 256 "${STAGE}.tar.gz" > "${STAGE}.tar.gz.sha256"
+
+ - name: Create archive (Windows)
+ if: runner.os == 'Windows'
+ shell: pwsh
+ run: |
+ Compress-Archive -Path "${env:STAGE}" -DestinationPath "${env:STAGE}.zip"
+ $hash = (Get-FileHash "${env:STAGE}.zip" -Algorithm SHA256).Hash.ToLower()
+ "$hash ${env:STAGE}.zip" | Out-File -Encoding ascii "${env:STAGE}.zip.sha256"
+
+ - name: Upload artifact
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: ffi-${{ matrix.target }}
+ path: |
+ agent-desktop-ffi-v*.tar.gz
+ agent-desktop-ffi-v*.tar.gz.sha256
+ agent-desktop-ffi-v*.zip
+ agent-desktop-ffi-v*.zip.sha256
+ retention-days: 1
+
publish-github:
name: Publish to GitHub Release
- needs: [release-please, build]
+ needs: [release-please, build, build-ffi]
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write
+ id-token: write # Sigstore OIDC exchange
+ attestations: write # write provenance bundle back to GitHub
steps:
- name: Download all artifacts
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
- pattern: binary-*
+ pattern: "{binary,ffi}-*"
merge-multiple: true
- name: Create checksums file
run: |
cat *.sha256 > checksums.txt
- echo "Checksums:"
cat checksums.txt
- name: Upload assets to GitHub Release
@@ -123,9 +244,19 @@ jobs:
GH_REPO: ${{ github.repository }}
run: |
gh release upload ${{ needs.release-please.outputs.tag_name }} \
- *.tar.gz checksums.txt \
+ *.tar.gz *.zip checksums.txt \
--clobber
+ # Keyless Sigstore provenance. Verify with:
+ # gh attestation verify <file> --repo lahfir/agent-desktop
+ - name: Attest build provenance
+ uses: actions/attest-build-provenance@a2bbfa25375fe432b6a289bc6b6cd05ecd0c4c32 # v4.1.0
+ with:
+ subject-path: |
+ *.tar.gz
+ *.zip
+ checksums.txt
+
publish-npm:
name: Publish to npm
needs: [release-please, publish-github]
@@ -148,9 +279,10 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
run: |
+ # Expected: 2 CLI tarballs + 4 FFI tarballs + 1 FFI zip + checksums = 8.
ASSETS=$(gh release view ${{ needs.release-please.outputs.tag_name }} --json assets --jq '.assets | length')
- if [ "$ASSETS" -lt 3 ]; then
- echo "FAIL: expected at least 3 assets (2 tarballs + checksums), found ${ASSETS}"
+ if [ "$ASSETS" -lt 8 ]; then
+ echo "FAIL: expected at least 8 assets, found ${ASSETS}"
exit 1
fi
echo "OK: ${ASSETS} assets found on release"
diff --git a/.gitignore b/.gitignore
index 1410af567..c7f031318 100644
--- a/.gitignore
+++ b/.gitignore
@@ -23,6 +23,7 @@ Cargo.lock
# Claude Code
.claude/
.agents/
+AGENTS.md
# Environment
.env
diff --git a/CLAUDE.md b/CLAUDE.md
index 3b0ea7878..042088a47 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -73,7 +73,8 @@ agent-desktop/
│ │ └── commands/ # one file per command
│ ├── macos/ # agent-desktop-macos (Phase 1)
│ ├── windows/ # agent-desktop-windows (stub → Phase 2)
-│ └── linux/ # agent-desktop-linux (stub → Phase 2)
+│ ├── linux/ # agent-desktop-linux (stub → Phase 2)
+│ └── ffi/ # agent-desktop-ffi (cdylib + cbindgen C ABI)
├── src/ # agent-desktop binary (entry point)
│ ├── main.rs # entry point, permission check, JSON envelope
│ ├── cli.rs # clap derive enum (Commands)
@@ -92,8 +93,10 @@ agent-desktop/
- `agent-desktop-core` defines the `PlatformAdapter` trait and all shared types
- Platform crates (`macos`, `windows`, `linux`) implement the trait
- **Core NEVER imports platform crates.** Platform crates NEVER import each other.
-- The binary crate (`src/`) is the only place that wires platform → core
-- CI enforces this: `cargo tree -p agent-desktop-core` must contain zero platform crate names
+- Two legitimate wiring points bring platform → core together:
+ 1. The binary crate (`src/`) — CLI consumers
+ 2. The FFI crate (`crates/ffi/`) — cdylib consumers (Python, Swift, Go, Node, C++)
+- CI enforces core isolation: `cargo tree -p agent-desktop-core` must contain zero platform crate names
### Platform Selection
diff --git a/Cargo.toml b/Cargo.toml
index f27ebc91d..3b0f34b6b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,5 +1,5 @@
[workspace]
-members = ["crates/core", "crates/macos", "crates/windows", "crates/linux", "src"]
+members = ["crates/core", "crates/macos", "crates/windows", "crates/linux", "crates/ffi", "src"]
resolver = "2"
[workspace.package]
@@ -35,3 +35,10 @@ lto = false
codegen-units = 16
strip = false
debug = 1
+
+# Dedicated profile for the FFI cdylib. Overrides panic = "abort" so
+# catch_unwind actually catches at the extern "C" boundary — the CLI
+# release profile stays abort for size reasons.
+[profile.release-ffi]
+inherits = "release"
+panic = "unwind"
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 000000000..d64569567
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/README.md b/README.md
index 5066a169f..c0ae63ba6 100644
--- a/README.md
+++ b/README.md
@@ -11,6 +11,7 @@
## Key Features
- **Native Rust CLI**: Fast, single binary, no runtime dependencies
+- **C-ABI cdylib** (`libagent_desktop_ffi`): Load once from Python / Swift / Go / Ruby / Node / C instead of forking the CLI per call
- **53 commands**: Observation, interaction, keyboard, mouse, notifications, clipboard, window management
- **Progressive skeleton traversal**: 78–96% token reduction on dense apps via shallow overview + targeted drill-down
- **Snapshot & refs**: AI-optimized workflow using deterministic element references (`@e1`, `@e2`)
@@ -51,6 +52,38 @@ macOS requires Accessibility permission. Grant it in **System Settings > Privacy
agent-desktop permissions --request # trigger system dialog
```
+## Language bindings (FFI)
+
+Every GitHub Release ships a prebuilt C-ABI cdylib alongside the CLI tarballs. Hosts that need in-process calls (Python agents, Swift apps, Go services, Node tools, Ruby scripts, C/C++ code) `dlopen` the dylib and call the functions declared in `agent_desktop.h` — no fork-exec per command.
+
+| Platform | Artifact |
+|----------------------|----------|
+| macOS arm64 | `agent-desktop-ffi-v<ver>-aarch64-apple-darwin.tar.gz` |
+| macOS x86_64 | `agent-desktop-ffi-v<ver>-x86_64-apple-darwin.tar.gz` |
+| Linux x86_64 (glibc) | `agent-desktop-ffi-v<ver>-x86_64-unknown-linux-gnu.tar.gz` |
+| Linux arm64 (glibc) | `agent-desktop-ffi-v<ver>-aarch64-unknown-linux-gnu.tar.gz` |
+| Windows x86_64 (MSVC)| `agent-desktop-ffi-v<ver>-x86_64-pc-windows-msvc.zip` |
+
+Each archive contains `lib/libagent_desktop_ffi.{dylib,so,dll}`, `include/agent_desktop.h`, `LICENSE`, and a short README. Verify the download with the release's `checksums.txt`:
+
+```bash
+shasum -a 256 -c checksums.txt
+gh attestation verify agent-desktop-ffi-v*.tar.gz --repo lahfir/agent-desktop # Sigstore provenance
+```
+
+Minimal Python round-trip:
+
+```python
+import ctypes
+lib = ctypes.CDLL("./lib/libagent_desktop_ffi.dylib")
+lib.ad_adapter_create.restype = ctypes.c_void_p
+adapter = lib.ad_adapter_create()
+# ... call ad_list_apps / ad_get_tree / ad_execute_action, see docs below
+lib.ad_adapter_destroy(adapter)
+```
+
+Full consumer guide — error-handling contract, ownership rules, threading constraints, every entrypoint with Safety docs: [`skills/agent-desktop-ffi/`](skills/agent-desktop-ffi/).
+
## Core Workflow for AI
For dense apps (Slack, VS Code, Notion), use **progressive skeleton traversal** to minimize token usage:
diff --git a/crates/core/src/adapter.rs b/crates/core/src/adapter.rs
index fdea318ea..28b03956d 100644
--- a/crates/core/src/adapter.rs
+++ b/crates/core/src/adapter.rs
@@ -2,7 +2,7 @@ use crate::{
action::{Action, ActionResult, DragParams, MouseEvent, WindowOp},
error::AdapterError,
node::{AccessibilityNode, AppInfo, Rect, SurfaceInfo, WindowInfo},
- notification::{NotificationFilter, NotificationInfo},
+ notification::{NotificationFilter, NotificationIdentity, NotificationInfo},
refs::RefEntry,
};
use std::marker::PhantomData;
@@ -143,6 +143,15 @@ pub trait PlatformAdapter: Send + Sync {
Err(AdapterError::not_supported("resolve_element"))
}
+ /// Releases a platform-specific element handle returned from
+ /// `resolve_element`. macOS implementations must `CFRelease` the
+ /// underlying `AXUIElementRef` to balance the `CFRetain` that
+ /// happened during resolve. Windows/Linux consumers can leave this
+ /// as the default `not_supported` no-op.
+ fn release_handle(&self, _handle: &NativeHandle) -> Result<(), AdapterError> {
+ Err(AdapterError::not_supported("release_handle"))
+ }
+
fn check_permissions(&self) -> PermissionStatus {
PermissionStatus::Denied {
suggestion: "Platform adapter not available".into(),
@@ -239,9 +248,21 @@ pub trait PlatformAdapter: Send + Sync {
Err(AdapterError::not_supported("dismiss_all_notifications"))
}
+ /// Press a named action button on the notification at `index`.
+ ///
+ /// `identity` lets the caller pin the targeted notification to an
+ /// expected app / title fingerprint. Notification Center reindexes
+ /// entries between listings, so index-only targeting can press the
+ /// wrong button if a notification arrives or is dismissed between
+ /// `list_notifications` and this call. When any identity field is
+ /// `Some`, implementations must return
+ /// `ErrorCode::NotificationNotFound` if the row at `index` does not
+ /// match. Passing an empty identity (or `None`) preserves legacy
+ /// index-only behavior for callers that reconcile themselves.
fn notification_action(
&self,
_index: usize,
+ _identity: Option<&NotificationIdentity>,
_action_name: &str,
) -> Result<ActionResult, AdapterError> {
Err(AdapterError::not_supported("notification_action"))
diff --git a/crates/core/src/commands/notification_action.rs b/crates/core/src/commands/notification_action.rs
index 8923a603e..5e49b2781 100644
--- a/crates/core/src/commands/notification_action.rs
+++ b/crates/core/src/commands/notification_action.rs
@@ -1,16 +1,26 @@
-use crate::{adapter::PlatformAdapter, error::AppError};
+use crate::{adapter::PlatformAdapter, error::AppError, notification::NotificationIdentity};
use serde_json::{json, Value};
pub struct NotificationActionArgs {
pub index: usize,
pub action: String,
+ pub expected_app: Option<String>,
+ pub expected_title: Option<String>,
}
pub fn execute(
args: NotificationActionArgs,
adapter: &dyn PlatformAdapter,
) -> Result<Value, AppError> {
- let result = adapter.notification_action(args.index, &args.action)?;
+ let identity = if args.expected_app.is_some() || args.expected_title.is_some() {
+ Some(NotificationIdentity {
+ expected_app: args.expected_app,
+ expected_title: args.expected_title,
+ })
+ } else {
+ None
+ };
+ let result = adapter.notification_action(args.index, identity.as_ref(), &args.action)?;
Ok(json!({
"action": result.action,
}))
diff --git a/crates/core/src/notification.rs b/crates/core/src/notification.rs
index adfb4249b..82618cc6b 100644
--- a/crates/core/src/notification.rs
+++ b/crates/core/src/notification.rs
@@ -18,6 +18,50 @@ pub struct NotificationFilter {
pub limit: Option<usize>,
}
+/// Identity fingerprint used to verify that a notification-action call
+/// targets the same notification a host observed via `list_notifications`.
+///
+/// Notification Center reindexes entries on every listing: opening,
+/// dismissing, or receiving a new notification shifts what sits at any
+/// given `index`. Calling `notification_action(index, ...)` without
+/// verification can therefore press the action button on a different
+/// notification than the host intended (confused-deputy at the OS
+/// boundary).
+///
+/// The host should pass the `app_name` and/or `title` observed on the
+/// notification at the moment of listing. If either field is `Some` and
+/// the row currently at `index` does not match, the action is rejected
+/// with `ErrorCode::NotificationNotFound`. Leaving both `None` preserves
+/// the legacy index-only behavior for callers that have already done
+/// their own reconciliation.
+#[derive(Debug, Clone, Default)]
+pub struct NotificationIdentity {
+ pub expected_app: Option<String>,
+ pub expected_title: Option<String>,
+}
+
+impl NotificationIdentity {
+ pub fn is_empty(&self) -> bool {
+ self.expected_app.is_none() && self.expected_title.is_none()
+ }
+
+ /// Returns true when `info` matches every field that is `Some` on
+ /// this identity. `None` fields are treated as wildcards.
+ pub fn matches(&self, info: &NotificationInfo) -> bool {
+ if let Some(ref app) = self.expected_app {
+ if app != &info.app_name {
+ return false;
+ }
+ }
+ if let Some(ref title) = self.expected_title {
+ if title != &info.title {
+ return false;
+ }
+ }
+ true
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -57,4 +101,54 @@ mod tests {
assert!(filter.text.is_none());
assert!(filter.limit.is_none());
}
+
+ fn sample_info(app: &str, title: &str) -> NotificationInfo {
+ NotificationInfo {
+ index: 1,
+ app_name: app.into(),
+ title: title.into(),
+ body: None,
+ actions: vec![],
+ }
+ }
+
+ #[test]
+ fn identity_default_is_empty_and_matches_everything() {
+ let id = NotificationIdentity::default();
+ assert!(id.is_empty());
+ assert!(id.matches(&sample_info("Messages", "Hi")));
+ assert!(id.matches(&sample_info("Slack", "New")));
+ }
+
+ #[test]
+ fn identity_with_only_app_matches_any_title_on_that_app() {
+ let id = NotificationIdentity {
+ expected_app: Some("Messages".into()),
+ expected_title: None,
+ };
+ assert!(!id.is_empty());
+ assert!(id.matches(&sample_info("Messages", "anything")));
+ assert!(!id.matches(&sample_info("Slack", "anything")));
+ }
+
+ #[test]
+ fn identity_with_only_title_matches_any_app_with_that_title() {
+ let id = NotificationIdentity {
+ expected_app: None,
+ expected_title: Some("Meeting starting".into()),
+ };
+ assert!(id.matches(&sample_info("Calendar", "Meeting starting")));
+ assert!(!id.matches(&sample_info("Calendar", "Reminder")));
+ }
+
+ #[test]
+ fn identity_with_both_requires_both_to_match() {
+ let id = NotificationIdentity {
+ expected_app: Some("Calendar".into()),
+ expected_title: Some("Meeting".into()),
+ };
+ assert!(id.matches(&sample_info("Calendar", "Meeting")));
+ assert!(!id.matches(&sample_info("Calendar", "Other")));
+ assert!(!id.matches(&sample_info("Other", "Meeting")));
+ }
}
diff --git a/crates/core/src/ref_alloc.rs b/crates/core/src/ref_alloc.rs
index 7580c6df5..95e60e54b 100644
--- a/crates/core/src/ref_alloc.rs
+++ b/crates/core/src/ref_alloc.rs
@@ -62,6 +62,51 @@ pub(crate) fn is_collapsible(node: &AccessibilityNode) -> bool {
&& node.children.len() == 1
}
+/// Applies `include_bounds`, `interactive_only`, and `compact` semantics
+/// to a raw adapter tree **without** allocating refs. Used by the FFI
+/// `ad_get_tree` path, which exposes a raw tree (no CLI/JSON ref pipeline).
+///
+/// - `include_bounds = false` strips `bounds` from every node.
+/// - `compact = true` collapses single-child chains whose own node has
+/// no semantic payload (same criterion `allocate_refs` uses).
+/// - `interactive_only = true` prunes leaves whose role is not in
+/// `INTERACTIVE_ROLES` and that have no children and no
+/// `children_count` marker. Unlike the ref-allocating variant, the
+/// decision is role-based (no ref_id to check), which matches the FFI
+/// contract that refs are never set on raw trees.
+pub fn transform_tree(
+ mut node: AccessibilityNode,
+ include_bounds: bool,
+ interactive_only: bool,
+ compact: bool,
+) -> AccessibilityNode {
+ if !include_bounds {
+ node.bounds = None;
+ }
+
+ node.children = node
+ .children
+ .into_iter()
+ .filter_map(|child| {
+ let child = transform_tree(child, include_bounds, interactive_only, compact);
+ if compact && is_collapsible(&child) {
+ return child.children.into_iter().next();
+ }
+ if interactive_only
+ && !INTERACTIVE_ROLES.contains(&child.role.as_str())
+ && child.children.is_empty()
+ && child.children_count.is_none()
+ {
+ None
+ } else {
+ Some(child)
+ }
+ })
+ .collect();
+
+ node
+}
+
pub(crate) struct RefAllocConfig<'a> {
pub include_bounds: bool,
pub interactive_only: bool,
@@ -124,3 +169,88 @@ pub(crate) fn allocate_refs(
node
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::node::{AccessibilityNode, Rect};
+
+ fn node(role: &str, name: Option<&str>) -> AccessibilityNode {
+ AccessibilityNode {
+ ref_id: None,
+ role: role.into(),
+ name: name.map(str::to_string),
+ value: None,
+ description: None,
+ hint: None,
+ states: vec![],
+ bounds: Some(Rect {
+ x: 0.0,
+ y: 0.0,
+ width: 10.0,
+ height: 10.0,
+ }),
+ children_count: None,
+ children: vec![],
+ }
+ }
+
+ #[test]
+ fn transform_tree_include_bounds_false_strips_bounds() {
+ let n = node("group", None);
+ let out = transform_tree(n, false, false, false);
+ assert!(out.bounds.is_none());
+ }
+
+ #[test]
+ fn transform_tree_include_bounds_true_preserves_bounds() {
+ let n = node("group", None);
+ let out = transform_tree(n, true, false, false);
+ assert!(out.bounds.is_some());
+ }
+
+ #[test]
+ fn transform_tree_interactive_only_prunes_noninteractive_leaves() {
+ let mut root = node("window", Some("w"));
+ root.children = vec![node("group", None), node("button", Some("OK"))];
+ let out = transform_tree(root, true, true, false);
+ assert_eq!(out.children.len(), 1);
+ assert_eq!(out.children[0].role, "button");
+ }
+
+ #[test]
+ fn transform_tree_interactive_only_keeps_named_containers_with_children() {
+ let mut labeled = node("group", Some("Toolbar"));
+ labeled.children = vec![node("button", Some("Save"))];
+ let mut root = node("window", Some("w"));
+ root.children = vec![labeled];
+ let out = transform_tree(root, true, true, false);
+ assert_eq!(out.children.len(), 1);
+ assert_eq!(out.children[0].children.len(), 1);
+ }
+
+ #[test]
+ fn transform_tree_compact_collapses_empty_single_child_chain() {
+ let mut outer = node("group", None);
+ let mut inner = node("group", None);
+ inner.children = vec![node("button", Some("Go"))];
+ outer.children = vec![inner];
+ let mut root = node("window", Some("w"));
+ root.children = vec![outer];
+ let out = transform_tree(root, true, false, true);
+ assert_eq!(out.children.len(), 1);
+ assert_eq!(out.children[0].role, "button");
+ }
+
+ #[test]
+ fn transform_tree_compact_preserves_labeled_containers() {
+ let mut named = node("group", Some("Toolbar"));
+ named.children = vec![node("button", Some("Save"))];
+ let mut root = node("window", Some("w"));
+ root.children = vec![named];
+ let out = transform_tree(root, true, false, true);
+ assert_eq!(out.children.len(), 1);
+ assert_eq!(out.children[0].role, "group");
+ assert_eq!(out.children[0].name.as_deref(), Some("Toolbar"));
+ }
+}
diff --git a/crates/ffi/Cargo.toml b/crates/ffi/Cargo.toml
new file mode 100644
index 000000000..8dea5554e
--- /dev/null
+++ b/crates/ffi/Cargo.toml
@@ -0,0 +1,25 @@
+[package]
+name = "agent-desktop-ffi"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+publish = false
+
+[lib]
+crate-type = ["cdylib", "rlib"]
+
+[dependencies]
+agent-desktop-core.workspace = true
+
+[target.'cfg(target_os = "macos")'.dependencies]
+agent-desktop-macos = { path = "../macos" }
+libc = "0.2"
+
+[target.'cfg(target_os = "windows")'.dependencies]
+agent-desktop-windows = { path = "../windows" }
+
+[target.'cfg(target_os = "linux")'.dependencies]
+agent-desktop-linux = { path = "../linux" }
+
+[build-dependencies]
+cbindgen = "= 0.27.0"
diff --git a/crates/ffi/build.rs b/crates/ffi/build.rs
new file mode 100644
index 000000000..687d6eca5
--- /dev/null
+++ b/crates/ffi/build.rs
@@ -0,0 +1,81 @@
+use std::env;
+use std::path::{Path, PathBuf};
+
+fn main() {
+ println!("cargo:rerun-if-changed=cbindgen.toml");
+ println!("cargo:rerun-if-changed=src/");
+
+ // Cargo's default install_name is the absolute build-machine path,
+ // which breaks linking consumers (Swift/SPM, clang) once the dylib
+ // is extracted from a release tarball. @rpath is the portable form.
+ if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
+ println!("cargo:rustc-cdylib-link-arg=-Wl,-install_name,@rpath/libagent_desktop_ffi.dylib");
+ }
+
+ let crate_dir = match env::var("CARGO_MANIFEST_DIR") {
+ Ok(d) => d,
+ Err(_) => {
+ println!("cargo:warning=CARGO_MANIFEST_DIR not set; skipping cbindgen");
+ return;
+ }
+ };
+ let out_dir = match env::var("OUT_DIR") {
+ Ok(d) => d,
+ Err(_) => {
+ println!("cargo:warning=OUT_DIR not set; skipping cbindgen");
+ return;
+ }
+ };
+
+ let config = match cbindgen::Config::from_file("cbindgen.toml") {
+ Ok(c) => c,
+ Err(err) => panic!("cbindgen.toml parse error: {}", err),
+ };
+
+ let out_path = Path::new(&out_dir).join("agent_desktop.h");
+
+ let bindings = match cbindgen::Builder::new()
+ .with_crate(&crate_dir)
+ .with_config(config)
+ .generate()
+ {
+ Ok(b) => b,
+ Err(err) => panic!("cbindgen generation failed: {}", err),
+ };
+
+ bindings.write_to_file(&out_path);
+ if !out_path.exists() {
+ panic!("cbindgen produced no header at {:?}", out_path);
+ }
+
+ // Deliberately NOT copying into crates/ffi/include/ — the committed
+ // header is the ABI contract. Auto-copy would self-heal CI drift checks.
+ // Developers refresh it via scripts/update-ffi-header.sh.
+
+ // Stamp the absolute path of the generated header at a stable location
+ // so CI and scripts don't have to `find target | head -1` (ambiguous
+ // under warm caches with multiple pkg-hash dirs).
+ if let Some(target_root) = target_root_from_out_dir(Path::new(&out_dir)) {
+ let stamp = target_root.join("ffi-header-path.txt");
+ if let Err(err) = std::fs::write(&stamp, out_path.to_string_lossy().as_bytes()) {
+ println!(
+ "cargo:warning=failed to stamp FFI header path at {:?}: {}",
+ stamp, err
+ );
+ }
+ } else {
+ println!(
+ "cargo:warning=could not infer cargo target root from OUT_DIR={}; skipping ffi-header-path.txt",
+ out_dir
+ );
+ }
+}
+
+fn target_root_from_out_dir(out_dir: &Path) -> Option<PathBuf> {
+ // OUT_DIR = .../target/<profile>/build/<pkg-hash>/out
+ let mut current = out_dir;
+ for _ in 0..4 {
+ current = current.parent()?;
+ }
+ Some(current.to_path_buf())
+}
diff --git a/crates/ffi/cbindgen.toml b/crates/ffi/cbindgen.toml
new file mode 100644
index 000000000..a35a9bf51
--- /dev/null
+++ b/crates/ffi/cbindgen.toml
@@ -0,0 +1,29 @@
+language = "C"
+include_guard = "AGENT_DESKTOP_H"
+no_includes = true
+sys_includes = ["stdint.h", "stdbool.h", "stddef.h"]
+style = "both"
+usize_is_size_t = true
+
+[export]
+# Force-emit the enums whose discriminants are the valid values for
+# public `int32_t` fields (AdAction.kind, AdScrollParams.direction, etc.).
+# cbindgen would otherwise drop these because no struct/function field
+# names them directly — we intentionally store the raw i32 on the ABI so
+# foreign callers can't UB with an invalid bit pattern, but C consumers
+# still need the named constants (AD_ACTION_KIND_CLICK etc.) to keep the
+# contract documented and type-checkable.
+include = [
+ "AdActionKind",
+ "AdDirection",
+ "AdModifier",
+ "AdMouseButton",
+ "AdMouseEventKind",
+ "AdScreenshotKind",
+ "AdSnapshotSurface",
+ "AdWindowOpKind",
+]
+
+[enum]
+rename_variants = "ScreamingSnakeCase"
+prefix_with_name = true
diff --git a/crates/ffi/examples/panic_spike.rs b/crates/ffi/examples/panic_spike.rs
new file mode 100644
index 000000000..89299cfca
--- /dev/null
+++ b/crates/ffi/examples/panic_spike.rs
@@ -0,0 +1,32 @@
+//! Regression example proving the custom `release-ffi` profile keeps
+//! `catch_unwind` effective under the optimized cdylib build.
+//!
+//! Build and run with:
+//! cargo run --profile release-ffi --example panic_spike -p agent-desktop-ffi
+//!
+//! Expected: prints "PANIC CAUGHT OK (code = -1)" and exits with code 0.
+//!
+//! If someone accidentally flips `panic = "abort"` back on the `release-ffi`
+//! profile (or removes the profile), this example will SIGABRT instead of
+//! catching — a loud regression signal.
+
+use std::panic::AssertUnwindSafe;
+
+#[no_mangle]
+pub extern "C" fn spike_panicking_entry() -> i32 {
+ std::panic::catch_unwind(AssertUnwindSafe(|| -> i32 {
+ panic!("synthetic panic inside extern C fn");
+ }))
+ .unwrap_or(-1)
+}
+
+fn main() {
+ let code = spike_panicking_entry();
+ if code == -1 {
+ println!("PANIC CAUGHT OK (code = -1)");
+ std::process::exit(0);
+ } else {
+ println!("UNEXPECTED: got code {}", code);
+ std::process::exit(2);
+ }
+}
diff --git a/crates/ffi/include/agent_desktop.h b/crates/ffi/include/agent_desktop.h
new file mode 100644
index 000000000..daf857708
--- /dev/null
+++ b/crates/ffi/include/agent_desktop.h
@@ -0,0 +1,1054 @@
+#ifndef AGENT_DESKTOP_H
+#define AGENT_DESKTOP_H
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <stddef.h>
+
+enum AdActionKind {
+ AD_ACTION_KIND_CLICK = 0,
+ AD_ACTION_KIND_DOUBLE_CLICK = 1,
+ AD_ACTION_KIND_RIGHT_CLICK = 2,
+ AD_ACTION_KIND_TRIPLE_CLICK = 3,
+ AD_ACTION_KIND_SET_VALUE = 4,
+ AD_ACTION_KIND_SET_FOCUS = 5,
+ AD_ACTION_KIND_EXPAND = 6,
+ AD_ACTION_KIND_COLLAPSE = 7,
+ AD_ACTION_KIND_SELECT = 8,
+ AD_ACTION_KIND_TOGGLE = 9,
+ AD_ACTION_KIND_CHECK = 10,
+ AD_ACTION_KIND_UNCHECK = 11,
+ AD_ACTION_KIND_SCROLL = 12,
+ AD_ACTION_KIND_SCROLL_TO = 13,
+ AD_ACTION_KIND_PRESS_KEY = 14,
+ AD_ACTION_KIND_KEY_DOWN = 15,
+ AD_ACTION_KIND_KEY_UP = 16,
+ AD_ACTION_KIND_TYPE_TEXT = 17,
+ AD_ACTION_KIND_CLEAR = 18,
+ AD_ACTION_KIND_HOVER = 19,
+ AD_ACTION_KIND_DRAG = 20,
+};
+typedef int32_t AdActionKind;
+
+enum AdDirection {
+ AD_DIRECTION_UP = 0,
+ AD_DIRECTION_DOWN = 1,
+ AD_DIRECTION_LEFT = 2,
+ AD_DIRECTION_RIGHT = 3,
+};
+typedef int32_t AdDirection;
+
+enum AdImageFormat {
+ AD_IMAGE_FORMAT_PNG = 0,
+ AD_IMAGE_FORMAT_JPG = 1,
+};
+typedef int32_t AdImageFormat;
+
+enum AdModifier {
+ AD_MODIFIER_CMD = 0,
+ AD_MODIFIER_CTRL = 1,
+ AD_MODIFIER_ALT = 2,
+ AD_MODIFIER_SHIFT = 3,
+};
+typedef int32_t AdModifier;
+
+enum AdMouseButton {
+ AD_MOUSE_BUTTON_LEFT = 0,
+ AD_MOUSE_BUTTON_RIGHT = 1,
+ AD_MOUSE_BUTTON_MIDDLE = 2,
+};
+typedef int32_t AdMouseButton;
+
+enum AdMouseEventKind {
+ AD_MOUSE_EVENT_KIND_MOVE = 0,
+ AD_MOUSE_EVENT_KIND_DOWN = 1,
+ AD_MOUSE_EVENT_KIND_UP = 2,
+ AD_MOUSE_EVENT_KIND_CLICK = 3,
+};
+typedef int32_t AdMouseEventKind;
+
+enum AdResult {
+ AD_RESULT_OK = 0,
+ AD_RESULT_ERR_PERM_DENIED = -1,
+ AD_RESULT_ERR_ELEMENT_NOT_FOUND = -2,
+ AD_RESULT_ERR_APP_NOT_FOUND = -3,
+ AD_RESULT_ERR_ACTION_FAILED = -4,
+ AD_RESULT_ERR_ACTION_NOT_SUPPORTED = -5,
+ AD_RESULT_ERR_STALE_REF = -6,
+ AD_RESULT_ERR_WINDOW_NOT_FOUND = -7,
+ AD_RESULT_ERR_PLATFORM_NOT_SUPPORTED = -8,
+ AD_RESULT_ERR_TIMEOUT = -9,
+ AD_RESULT_ERR_INVALID_ARGS = -10,
+ AD_RESULT_ERR_NOTIFICATION_NOT_FOUND = -11,
+ AD_RESULT_ERR_INTERNAL = -12,
+};
+typedef int32_t AdResult;
+
+enum AdScreenshotKind {
+ AD_SCREENSHOT_KIND_SCREEN = 0,
+ AD_SCREENSHOT_KIND_WINDOW = 1,
+ AD_SCREENSHOT_KIND_FULL_SCREEN = 2,
+};
+typedef int32_t AdScreenshotKind;
+
+enum AdSnapshotSurface {
+ AD_SNAPSHOT_SURFACE_WINDOW = 0,
+ AD_SNAPSHOT_SURFACE_FOCUSED = 1,
+ AD_SNAPSHOT_SURFACE_MENU = 2,
+ AD_SNAPSHOT_SURFACE_MENUBAR = 3,
+ AD_SNAPSHOT_SURFACE_SHEET = 4,
+ AD_SNAPSHOT_SURFACE_POPOVER = 5,
+ AD_SNAPSHOT_SURFACE_ALERT = 6,
+};
+typedef int32_t AdSnapshotSurface;
+
+enum AdWindowOpKind {
+ AD_WINDOW_OP_KIND_RESIZE = 0,
+ AD_WINDOW_OP_KIND_MOVE = 1,
+ AD_WINDOW_OP_KIND_MINIMIZE = 2,
+ AD_WINDOW_OP_KIND_MAXIMIZE = 3,
+ AD_WINDOW_OP_KIND_RESTORE = 4,
+};
+typedef int32_t AdWindowOpKind;
+
+typedef struct AdAdapter AdAdapter;
+
+/**
+ * Opaque list handle emitted by `ad_list_apps`. See
+ * [`crate::types::window_list::AdWindowList`] for the pattern.
+ */
+typedef struct AdAppList AdAppList;
+
+/**
+ * Opaque image-buffer handle returned by `ad_screenshot`. The backing
+ * byte buffer and its length live inside the Rust-owned struct — a
+ * consumer cannot accidentally desynchronize the pair and trigger a
+ * heap-corruption double-free. Walk it through `ad_image_buffer_*`
+ * accessors and free it with `ad_image_buffer_free`.
+ */
+typedef struct AdImageBuffer AdImageBuffer;
+
+typedef struct AdNotificationList AdNotificationList;
+
+/**
+ * Opaque list handle emitted by `ad_list_surfaces`. See
+ * [`crate::types::window_list::AdWindowList`] for the pattern.
+ */
+typedef struct AdSurfaceList AdSurfaceList;
+
+/**
+ * Opaque list handle emitted by `ad_list_windows`.
+ *
+ * The struct intentionally has no `#[repr(C)]` so cbindgen emits a
+ * forward declaration only (`typedef struct AdWindowList AdWindowList;`).
+ * Consumers cannot read the backing pointer or length and cannot
+ * construct a count mismatch — they walk the list through
+ * `ad_window_list_count`, `ad_window_list_get`, and free it with
+ * `ad_window_list_free`.
+ */
+typedef struct AdWindowList AdWindowList;
+
+typedef struct AdNativeHandle {
+ const void *ptr;
+} AdNativeHandle;
+
+/**
+ * Scroll parameters embedded in `AdAction` when `kind == SCROLL`.
+ *
+ * `direction` is stored as `int32_t` for the same boundary-safety
+ * reason `AdAction.kind` is. Valid values are the discriminants of
+ * `AdDirection`.
+ */
+typedef struct AdScrollParams {
+ int32_t direction;
+ uint32_t amount;
+} AdScrollParams;
+
+/**
+ * Key combination: a named key plus optional modifier list.
+ *
+ * `modifiers` points to an array of `int32_t` values (not a typed Rust
+ * enum array) so the C boundary cannot be tricked into writing an
+ * out-of-range discriminant into a Rust enum slot. Each entry is
+ * validated against `AdModifier` before use; an invalid discriminant
+ * returns `AD_RESULT_ERR_INVALID_ARGS`.
+ */
+typedef struct AdKeyCombo {
+ const char *key;
+ const int32_t *modifiers;
+ uint32_t modifier_count;
+} AdKeyCombo;
+
+typedef struct AdPoint {
+ double x;
+ double y;
+} AdPoint;
+
+typedef struct AdDragParams {
+ struct AdPoint from;
+ struct AdPoint to;
+ uint64_t duration_ms;
+} AdDragParams;
+
+/**
+ * Action dispatched by `ad_execute_action`.
+ *
+ * `kind` is stored as `int32_t` so a buggy or malicious C caller
+ * cannot write an out-of-range discriminant into a Rust enum slot —
+ * an out-of-range value is rejected with
+ * `AD_RESULT_ERR_INVALID_ARGS` at the boundary. Valid values are the
+ * discriminants of `AdActionKind`.
+ */
+typedef struct AdAction {
+ int32_t kind;
+ const char *text;
+ struct AdScrollParams scroll;
+ struct AdKeyCombo key;
+ struct AdDragParams drag;
+} AdAction;
+
+typedef struct AdElementState {
+ const char *role;
+ char **states;
+ uint32_t state_count;
+ const char *value;
+} AdElementState;
+
+typedef struct AdActionResult {
+ const char *action;
+ const char *ref_id;
+ struct AdElementState *post_state;
+} AdActionResult;
+
+typedef struct AdRefEntry {
+ int32_t pid;
+ const char *role;
+ const char *name;
+ uint64_t bounds_hash;
+ bool has_bounds_hash;
+} AdRefEntry;
+
+typedef struct AdRect {
+ double x;
+ double y;
+ double width;
+ double height;
+} AdRect;
+
+typedef struct AdWindowInfo {
+ const char *id;
+ const char *title;
+ const char *app_name;
+ int32_t pid;
+ struct AdRect bounds;
+ bool has_bounds;
+ bool is_focused;
+} AdWindowInfo;
+
+typedef struct AdAppInfo {
+ const char *name;
+ int32_t pid;
+ const char *bundle_id;
+} AdAppInfo;
+
+/**
+ * Mouse event dispatched by `ad_mouse_event`.
+ *
+ * `kind` and `button` are stored as `int32_t` for the same reason
+ * `AdAction.kind` is — foreign callers cannot place invalid
+ * discriminants into Rust enum slots. Valid values are the
+ * discriminants of `AdMouseEventKind` and `AdMouseButton`.
+ */
+typedef struct AdMouseEvent {
+ int32_t kind;
+ struct AdPoint point;
+ int32_t button;
+ uint32_t click_count;
+} AdMouseEvent;
+
+typedef struct AdNotificationFilter {
+ const char *app;
+ const char *text;
+ uint32_t limit;
+ bool has_limit;
+} AdNotificationFilter;
+
+typedef struct AdNotificationInfo {
+ uint32_t index;
+ const char *app_name;
+ const char *title;
+ const char *body;
+ char **actions;
+ uint32_t action_count;
+} AdNotificationInfo;
+
+typedef struct AdFindQuery {
+ const char *role;
+ const char *name_substring;
+ const char *value_substring;
+} AdFindQuery;
+
+/**
+ * Screenshot target for `ad_screenshot`.
+ *
+ * `kind` is stored as `int32_t` to keep the enum-discriminant check
+ * at the boundary. Valid values are the discriminants of
+ * `AdScreenshotKind`. `screen_index` is only consulted when kind is
+ * `SCREEN`; `pid` only when kind is `WINDOW`.
+ */
+typedef struct AdScreenshotTarget {
+ int32_t kind;
+ uint64_t screen_index;
+ int32_t pid;
+} AdScreenshotTarget;
+
+typedef struct AdSurfaceInfo {
+ const char *kind;
+ const char *title;
+ int64_t item_count;
+} AdSurfaceInfo;
+
+typedef struct AdNode {
+ const char *ref_id;
+ const char *role;
+ const char *name;
+ const char *value;
+ const char *description;
+ const char *hint;
+ char **states;
+ uint32_t state_count;
+ struct AdRect bounds;
+ bool has_bounds;
+ int32_t parent_index;
+ uint32_t child_start;
+ uint32_t child_count;
+} AdNode;
+
+typedef struct AdNodeTree {
+ struct AdNode *nodes;
+ uint32_t count;
+} AdNodeTree;
+
+/**
+ * Options for `ad_get_tree`.
+ *
+ * `surface` is stored as `int32_t` so foreign callers cannot write
+ * an invalid discriminant into a Rust enum slot. Valid values are the
+ * discriminants of `AdSnapshotSurface`; out-of-range values return
+ * `AD_RESULT_ERR_INVALID_ARGS`.
+ */
+typedef struct AdTreeOptions {
+ uint8_t max_depth;
+ bool include_bounds;
+ bool interactive_only;
+ bool compact;
+ int32_t surface;
+} AdTreeOptions;
+
+/**
+ * Window-manager operation dispatched by `ad_window_op`.
+ *
+ * `kind` is stored as `int32_t` to keep the enum-discriminant check at
+ * the boundary — out-of-range values return
+ * `AD_RESULT_ERR_INVALID_ARGS`. Valid values are the discriminants of
+ * `AdWindowOpKind`. `width`/`height`/`x`/`y` are only consulted for
+ * the variants that use them.
+ */
+typedef struct AdWindowOp {
+ int32_t kind;
+ double width;
+ double height;
+ double x;
+ double y;
+} AdWindowOp;
+
+/**
+ * # Safety
+ *
+ * `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+ * `handle` must be a non-null pointer to a valid `AdNativeHandle`.
+ * `action` must be a non-null pointer to a valid `AdAction`.
+ * `out` must be a non-null pointer to an `AdActionResult` to write the result into.
+ */
+AdResult ad_execute_action(const struct AdAdapter *adapter,
+ const struct AdNativeHandle *handle,
+ const struct AdAction *action,
+ struct AdActionResult *out);
+
+/**
+ * Releases a handle previously returned by `ad_resolve_element` and
+ * zeroes the caller's struct so accidentally calling this twice is
+ * a deterministic no-op instead of a double-free on the underlying
+ * `CFRelease`.
+ *
+ * On macOS this calls `CFRelease` on the underlying `AXUIElementRef`,
+ * balancing the `CFRetain` that happened during `ad_resolve_element`.
+ * On Windows/Linux the call is a no-op that returns `AD_RESULT_OK`
+ * (platform adapters inherit the default `not_supported` impl; the
+ * FFI surface translates it so callers apply the same release
+ * pattern everywhere).
+ *
+ * Ownership contract: the FFI owns the handle from the moment
+ * `ad_resolve_element` writes `ptr`. Copying the struct after that
+ * point and calling `ad_free_handle` on either copy is undefined —
+ * there is no way for the library to detect forged non-null pointers.
+ * Callers that legitimately need a "copy" should re-resolve.
+ *
+ * # Safety
+ *
+ * `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+ * `handle` must be null or a `*mut AdNativeHandle` previously
+ * populated by `ad_resolve_element`. On return `(*handle).ptr` is
+ * `NULL` so a double-call is a no-op instead of a double-free.
+ */
+AdResult ad_free_handle(const struct AdAdapter *adapter, struct AdNativeHandle *handle);
+
+/**
+ * # Safety
+ *
+ * `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+ * `entry` must be a non-null pointer to a valid `AdRefEntry`.
+ * `out` must be a non-null pointer to an `AdNativeHandle` to write the result into.
+ */
+AdResult ad_resolve_element(const struct AdAdapter *adapter,
+ const struct AdRefEntry *entry,
+ struct AdNativeHandle *out);
+
+/**
+ * # Safety
+ *
+ * `result` must be a pointer to an `AdActionResult` previously written by `ad_execute_action`,
+ * or null. After this call all pointers inside the struct are invalid.
+ */
+void ad_free_action_result(struct AdActionResult *result);
+
+/**
+ * Builds a platform adapter for the current OS and returns an opaque
+ * handle. Returns null on allocation failure or if a Rust panic is
+ * caught at the FFI boundary (inspect `ad_last_error_*` for details).
+ *
+ * The returned pointer is owned by the caller and must be released with
+ * `ad_adapter_destroy`. Creating and destroying adapters is cheap; the
+ * common pattern is one adapter per process lifetime.
+ */
+struct AdAdapter *ad_adapter_create(void);
+
+/**
+ * # Safety
+ *
+ * `adapter` must be a pointer returned by `ad_adapter_create`, or null.
+ * After this call the pointer is invalid and must not be used.
+ */
+void ad_adapter_destroy(struct AdAdapter *adapter);
+
+/**
+ * # Safety
+ *
+ * `adapter` must be a non-null pointer returned by `ad_adapter_create` that
+ * has not yet been destroyed.
+ */
+AdResult ad_check_permissions(const struct AdAdapter *adapter);
+
+/**
+ * Closes the application identified by `id` (bundle id on macOS,
+ * executable path on other platforms). `force = true` skips the
+ * graceful-shutdown path (equivalent to `kill -9`).
+ *
+ * # Safety
+ * `adapter` must be non-null. `id` must be a non-null UTF-8 C string.
+ */
+AdResult ad_close_app(const struct AdAdapter *adapter, const char *id, bool force);
+
+/**
+ * Launches the application identified by `id` (bundle id on macOS,
+ * executable path on other platforms) and, on success, writes the
+ * first window that becomes available into `*out`. Waits up to
+ * `timeout_ms` for the window to appear; zero means "no wait".
+ *
+ * The returned `AdWindowInfo` owns heap-allocated interior strings that
+ * must be released with `ad_release_window_fields` once done. On error
+ * the out-param is zero-initialized, so calling the release fn on it
+ * is a safe no-op.
+ *
+ * # Safety
+ * `adapter` must be non-null. `id` must be a non-null UTF-8 C string.
+ * `out` must be a non-null writable `*mut AdWindowInfo`.
+ */
+AdResult ad_launch_app(const struct AdAdapter *adapter,
+ const char *id,
+ uint64_t timeout_ms,
+ struct AdWindowInfo *out);
+
+/**
+ * # Safety
+ * `adapter` must be a valid pointer from `ad_adapter_create`.
+ * `out` must be a valid writable `*mut *mut AdAppList`.
+ * On success, `*out` is a newly-allocated opaque list freed with
+ * `ad_app_list_free`. On error, `*out` is null and last-error is set.
+ */
+AdResult ad_list_apps(const struct AdAdapter *adapter, struct AdAppList **out);
+
+/**
+ * # Safety
+ * `list` must be null or a pointer returned by `ad_list_apps`.
+ */
+uint32_t ad_app_list_count(const struct AdAppList *list);
+
+/**
+ * Returns a borrowed pointer into the list; valid until the list is freed.
+ * Out-of-range `index` returns null.
+ *
+ * # Safety
+ * `list` must be null or a pointer returned by `ad_list_apps`.
+ */
+const struct AdAppInfo *ad_app_list_get(const struct AdAppList *list, uint32_t index);
+
+/**
+ * Frees the list and every `AdAppInfo` it owns, including the interior
+ * C-strings.
+ *
+ * # Safety
+ * `list` must be null or a pointer returned by `ad_list_apps`.
+ */
+void ad_app_list_free(struct AdAppList *list);
+
+/**
+ * Last-error lifetime — errno-style.
+ *
+ * The pointer returned by `ad_last_error_message`,
+ * `ad_last_error_suggestion`, and `ad_last_error_platform_detail`
+ * remains valid across any number of subsequent **successful** FFI
+ * calls on the same thread. Only the next FFI call that itself **fails**
+ * (returns a non-`AD_RESULT_OK` code) invalidates the previous pointers.
+ *
+ * Consumers can therefore read an error once, cache the pointer, and
+ * keep reading it back across follow-up work that clears or re-fetches
+ * state before handing control to the user.
+ *
+ * This matches the POSIX `errno` / `strerror` contract and is scoped
+ * per-thread via thread-local storage — Thread A's last-error never
+ * leaks to Thread B.
+ * Returns the `AdResult` code of the last error on the calling thread,
+ * or `AD_RESULT_OK` if no error has been recorded.
+ */
+AdResult ad_last_error_code(void);
+
+/**
+ * Returns a borrowed C string describing the last error, or null if no
+ * error has been recorded on the calling thread. The pointer remains
+ * valid across any number of subsequent *successful* FFI calls; only
+ * the next failing call overwrites it.
+ */
+const char *ad_last_error_message(void);
+
+/**
+ * Returns a borrowed C string with a human-readable suggestion for how
+ * to recover from the last error, or null if the adapter didn't emit
+ * one. Same lifetime rules as `ad_last_error_message`.
+ */
+const char *ad_last_error_suggestion(void);
+
+/**
+ * Returns a borrowed C string carrying a platform-specific diagnostic
+ * for the last error (AX error codes, COM HRESULTs, AT-SPI messages,
+ * etc.), or null if the adapter didn't supply one. Same lifetime rules
+ * as `ad_last_error_message`.
+ */
+const char *ad_last_error_platform_detail(void);
+
+/**
+ * Reads the current clipboard text and writes an owned C string into
+ * `*out`. The caller must free the returned pointer with
+ * `ad_free_string`. On error `*out` is left null.
+ *
+ * # Safety
+ * `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+ * `out` must be a non-null writable `*mut *mut c_char`.
+ */
+AdResult ad_get_clipboard(const struct AdAdapter *adapter, char **out);
+
+/**
+ * Writes UTF-8 `text` to the clipboard. Null or non-UTF-8 input returns
+ * `AD_RESULT_ERR_INVALID_ARGS` with a diagnostic last-error.
+ *
+ * # Safety
+ * `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+ * `text` must be a non-null, NUL-terminated UTF-8 C string.
+ */
+AdResult ad_set_clipboard(const struct AdAdapter *adapter, const char *text);
+
+/**
+ * Clears the clipboard.
+ *
+ * # Safety
+ * `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+ */
+AdResult ad_clear_clipboard(const struct AdAdapter *adapter);
+
+/**
+ * Frees a C string previously returned by `ad_get_clipboard` or any
+ * other FFI call documented as allocating a C string for the caller.
+ * Null-tolerant — safe to call on `NULL`. Double-free is undefined.
+ *
+ * # Safety
+ * `s` must be null or a pointer previously handed out by this crate.
+ * After this call the pointer is invalid and must not be used.
+ */
+void ad_free_string(char *s);
+
+/**
+ * Synthesizes a mouse drag from `params.from` to `params.to`. When
+ * `params.duration_ms` is zero the drag is instantaneous; a non-zero
+ * value asks the platform adapter to interpolate.
+ *
+ * # Safety
+ * `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+ * `params` must be a non-null pointer to a valid `AdDragParams`.
+ */
+AdResult ad_drag(const struct AdAdapter *adapter, const struct AdDragParams *params);
+
+/**
+ * Dispatches a mouse event (move / down / up / click) at the given
+ * screen point. Click count is only consulted when `event.kind` is
+ * `CLICK` (e.g., `click_count == 2` for a double-click).
+ *
+ * # Safety
+ * `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+ * `event` must be a non-null pointer to a valid `AdMouseEvent`.
+ */
+AdResult ad_mouse_event(const struct AdAdapter *adapter, const struct AdMouseEvent *event);
+
+/**
+ * Triggers the named action on the notification at `index`. Typical
+ * action names are those reported in `AdNotificationInfo.actions`
+ * (e.g. `"Reply"`, `"Open"`).
+ *
+ * ## Identity / reorder safety
+ *
+ * Notification Center reindexes entries on every listing — a new
+ * notification arriving (or another one being dismissed) shifts which
+ * notification sits at any given `index`. Calling this function with
+ * an index obtained from a prior `ad_list_notifications` can therefore
+ * press the action button on a different notification than the host
+ * intended.
+ *
+ * `expected_app` and `expected_title` let the host pin the targeted
+ * notification to an observed fingerprint. If either pointer is
+ * non-null, the row currently at `index` must match that field or the
+ * call fails closed with `AD_RESULT_ERR_NOTIFICATION_NOT_FOUND`. Both
+ * null preserves the legacy index-only behavior for hosts that do
+ * their own reconciliation.
+ *
+ * # Safety
+ * `adapter` must be valid. `action_name` must be a non-null UTF-8
+ * C string. `expected_app` and `expected_title` must each be null
+ * or a NUL-terminated UTF-8 C string. Invalid UTF-8 in either field
+ * is rejected with `AD_RESULT_ERR_INVALID_ARGS` rather than silently
+ * treated as "no fingerprint". `out` must be a valid writable
+ * `*mut AdActionResult`; on error it is zero-initialized.
+ */
+AdResult ad_notification_action(const struct AdAdapter *adapter,
+ uint32_t index,
+ const char *expected_app,
+ const char *expected_title,
+ const char *action_name,
+ struct AdActionResult *out);
+
+/**
+ * Dismisses the notification at `index`. Indexes are only valid within
+ * the response to the most recent `ad_list_notifications` call on this
+ * thread — the adapter re-queries internally, so dismissing by a stale
+ * index returns `AD_RESULT_ERR_NOTIFICATION_NOT_FOUND`.
+ *
+ * # Safety
+ * `adapter` must be valid. `app_filter` may be null.
+ */
+AdResult ad_dismiss_notification(const struct AdAdapter *adapter,
+ uint32_t index,
+ const char *app_filter);
+
+/**
+ * Dismisses every notification matching `app_filter` (null = all apps).
+ *
+ * Returns two lists: `dismissed_out` carries the notifications that
+ * were successfully dismissed; `failed_out` holds error strings for
+ * notifications where the platform rejected the dismiss. Partial
+ * failures do not set last-error — inspect `failed_out` for details.
+ *
+ * `failed_out` uses the notification-list handle to stay ABI-consistent
+ * with the other list-returning FFI calls; the entries carry the
+ * original notification shape with `body` populated by the platform
+ * error message.
+ *
+ * # Safety
+ * `adapter` must be valid. `app_filter` may be null. `dismissed_out`
+ * and `failed_out` must both be valid writable `*mut *mut AdNotificationList`.
+ */
+AdResult ad_dismiss_all_notifications(const struct AdAdapter *adapter,
+ const char *app_filter,
+ struct AdNotificationList **dismissed_out,
+ struct AdNotificationList **failed_out);
+
+/**
+ * Convenience wrapper: free both lists returned by
+ * `ad_dismiss_all_notifications`. Equivalent to calling
+ * `ad_notification_list_free` on each; provided for symmetry.
+ *
+ * # Safety
+ * Both arguments must be null or pointers from
+ * `ad_dismiss_all_notifications`.
+ */
+void ad_dismiss_all_notifications_free(struct AdNotificationList *dismissed,
+ struct AdNotificationList *failed);
+
+/**
+ * Lists the notifications currently on-screen.
+ *
+ * Notification indexes are only stable within a single list response.
+ * Pass them straight to `ad_dismiss_notification` /
+ * `ad_notification_action` without caching across ticks — the adapter
+ * re-queries Notification Center internally on every call.
+ *
+ * # Safety
+ * `adapter` must be valid. `filter` may be null. `out` must be a valid
+ * writable `*mut *mut AdNotificationList`. On success `*out` is a
+ * non-null handle freed with `ad_notification_list_free`.
+ */
+AdResult ad_list_notifications(const struct AdAdapter *adapter,
+ const struct AdNotificationFilter *filter,
+ struct AdNotificationList **out);
+
+/**
+ * # Safety
+ * `list` must be null or a pointer returned by `ad_list_notifications`.
+ */
+uint32_t ad_notification_list_count(const struct AdNotificationList *list);
+
+/**
+ * Borrows a notification entry. Null if `index` is out of range.
+ *
+ * # Safety
+ * `list` must be null or a pointer returned by `ad_list_notifications`.
+ */
+const struct AdNotificationInfo *ad_notification_list_get(const struct AdNotificationList *list,
+ uint32_t index);
+
+/**
+ * Frees the list and each entry's interior strings.
+ *
+ * # Safety
+ * `list` must be null or a pointer returned by `ad_list_notifications`.
+ */
+void ad_notification_list_free(struct AdNotificationList *list);
+
+/**
+ * Finds the first element in `win`'s accessibility tree matching the
+ * query and resolves it to an opaque `AdNativeHandle`. The caller owns
+ * the handle and must release it with `ad_free_handle(adapter, handle)`
+ * once done.
+ *
+ * Matching is DFS order, first hit wins. All query fields are optional
+ * (null = "don't care") and case-insensitive substring matches:
+ * - `role` against `AccessibilityNode.role`
+ * - `name_substring` against `AccessibilityNode.name`
+ * - `value_substring` against `AccessibilityNode.value`
+ *
+ * # Safety
+ * `adapter`, `win`, and `query` must be valid pointers. `out_handle`
+ * must be a valid writable `*mut AdNativeHandle`. On
+ * `AD_RESULT_ERR_ELEMENT_NOT_FOUND` the out-handle is zero-initialized.
+ */
+AdResult ad_find(const struct AdAdapter *adapter,
+ const struct AdWindowInfo *win,
+ const struct AdFindQuery *query,
+ struct AdNativeHandle *out_handle);
+
+/**
+ * Reads a single property off a previously-resolved element handle.
+ *
+ * Supported properties:
+ * - `"value"` — live textual value (text fields, sliders, progress
+ * indicators). Null out-string when the element has no value.
+ * - `"bounds"` — JSON-encoded `{"x":..,"y":..,"width":..,"height":..}`.
+ * Null out-string when bounds are unavailable.
+ *
+ * The returned string must be freed with `ad_free_string`.
+ *
+ * # Safety
+ * `adapter` must be valid. `handle` must be a non-null `AdNativeHandle`.
+ * `property` must be a non-null UTF-8 C string. `out` must be a valid
+ * writable `*mut *mut c_char`; it is null-initialized on entry.
+ */
+AdResult ad_get(const struct AdAdapter *adapter,
+ const struct AdNativeHandle *handle,
+ const char *property,
+ char **out);
+
+/**
+ * Checks whether a named boolean state is set on the first element
+ * matching `query` inside `win`'s accessibility tree. Intended for
+ * the common agent idiom `find → is("focused") → if yes, act`.
+ *
+ * Supported property names reflect the strings the macOS tree
+ * builder actually emits in `AccessibilityNode.states`:
+ *
+ * - `"focused"` — true when the node carries the `focused` state.
+ * - `"disabled"` — true when the adapter surfaced `disabled`.
+ * - `"enabled"` — derived: true iff `disabled` is NOT present. There
+ * is no `enabled` string in the adapter output; asking for it
+ * returns the logical negation so agents don't have to invert
+ * themselves.
+ *
+ * `"selected"`, `"checked"`, and `"expanded"` are not currently
+ * emitted by any platform adapter; asking for them returns
+ * `AD_RESULT_ERR_INVALID_ARGS` with a diagnostic last-error rather
+ * than silently answering `false`. The set will widen as adapters
+ * grow support; future additions stay backwards-compatible
+ * (unknown → InvalidArgs, known → deterministic answer).
+ *
+ * On entry `*out` is always cleared to `false` so a caller inspecting
+ * the slot after an error sees a predictable sentinel, not whatever
+ * was there before. If the query matches nothing, returns
+ * `AD_RESULT_ERR_ELEMENT_NOT_FOUND` with `*out` still `false`.
+ *
+ * # Safety
+ * All pointers must be valid. `property` must be a non-null UTF-8
+ * C string. `out` must be a valid writable `*mut bool`.
+ */
+AdResult ad_is(const struct AdAdapter *adapter,
+ const struct AdWindowInfo *win,
+ const struct AdFindQuery *query,
+ const char *property,
+ bool *out);
+
+/**
+ * Borrowed pointer to the image bytes; valid until the buffer is freed.
+ * Returns null if `buf` is null.
+ *
+ * # Safety
+ * `buf` must be null or returned by `ad_screenshot`.
+ */
+const uint8_t *ad_image_buffer_data(const struct AdImageBuffer *buf);
+
+/**
+ * Byte length of the buffer returned by `ad_image_buffer_data`.
+ * Always consistent with the actual allocation (no C-mutable mismatch).
+ *
+ * # Safety
+ * `buf` must be null or returned by `ad_screenshot`.
+ */
+uint64_t ad_image_buffer_size(const struct AdImageBuffer *buf);
+
+/**
+ * Pixel width of the image.
+ *
+ * # Safety
+ * `buf` must be null or returned by `ad_screenshot`.
+ */
+uint32_t ad_image_buffer_width(const struct AdImageBuffer *buf);
+
+/**
+ * Pixel height of the image.
+ *
+ * # Safety
+ * `buf` must be null or returned by `ad_screenshot`.
+ */
+uint32_t ad_image_buffer_height(const struct AdImageBuffer *buf);
+
+/**
+ * Encoding format of the image bytes. Defaults to `PNG` on a null
+ * handle — callers must still null-check.
+ *
+ * # Safety
+ * `buf` must be null or returned by `ad_screenshot`.
+ */
+AdImageFormat ad_image_buffer_format(const struct AdImageBuffer *buf);
+
+/**
+ * Allocates and returns an opaque `AdImageBuffer`. The handle owns its
+ * byte buffer; inspect it through `ad_image_buffer_data` /
+ * `ad_image_buffer_size` / `ad_image_buffer_format` / `_width` / `_height`
+ * and free it with `ad_image_buffer_free`.
+ *
+ * # Safety
+ * `adapter` and `target` must be valid pointers. `out` must be a valid
+ * writable `*mut *mut AdImageBuffer`. On error `*out` is null and
+ * last-error is set.
+ */
+AdResult ad_screenshot(const struct AdAdapter *adapter,
+ const struct AdScreenshotTarget *target,
+ struct AdImageBuffer **out);
+
+/**
+ * Frees the image buffer allocated by `ad_screenshot`.
+ *
+ * # Safety
+ * `buf` must be null or a pointer previously returned by `ad_screenshot`.
+ * Double-free is undefined behavior.
+ */
+void ad_image_buffer_free(struct AdImageBuffer *buf);
+
+/**
+ * # Safety
+ * `adapter` must be valid. `out` must be a valid writable
+ * `*mut *mut AdSurfaceList`. Success produces a list handle freed via
+ * `ad_surface_list_free`.
+ */
+AdResult ad_list_surfaces(const struct AdAdapter *adapter, int32_t pid, struct AdSurfaceList **out);
+
+/**
+ * # Safety
+ * `list` must be null or a pointer returned by `ad_list_surfaces`.
+ */
+uint32_t ad_surface_list_count(const struct AdSurfaceList *list);
+
+/**
+ * Borrow a surface info entry. Null if `index` is out of range.
+ *
+ * # Safety
+ * `list` must be null or a pointer returned by `ad_list_surfaces`.
+ */
+const struct AdSurfaceInfo *ad_surface_list_get(const struct AdSurfaceList *list, uint32_t index);
+
+/**
+ * Frees the list and each entry's interior strings.
+ *
+ * # Safety
+ * `list` must be null or a pointer returned by `ad_list_surfaces`.
+ */
+void ad_surface_list_free(struct AdSurfaceList *list);
+
+/**
+ * # Safety
+ * `tree` must be null or point to a valid `AdNodeTree` previously returned
+ * by `flatten_tree` or `ad_get_tree`. After this call the tree is zeroed.
+ */
+void ad_free_tree(struct AdNodeTree *tree);
+
+/**
+ * Snapshots `win`'s accessibility tree into the flat BFS layout
+ * described in the types module. The result is written into `*out`
+ * and must be freed with `ad_free_tree`. Direct children of any node
+ * live contiguously at `nodes[child_start..child_start + child_count]`.
+ *
+ * `opts.max_depth` caps tree depth. `opts.surface` selects which
+ * surface to snapshot (window body, menu, menubar, sheet, popover,
+ * alert, or focused subtree); see `AdSnapshotSurface`.
+ * `opts.interactive_only` prunes non-interactive nodes; `opts.compact`
+ * collapses containers with no semantic payload.
+ *
+ * # Raw-tree contract
+ *
+ * This is a **raw adapter tree**, not the snapshot the CLI `snapshot`
+ * subcommand returns. Differences the caller must know about:
+ *
+ * - `ref_id` is always null on every `AdNode`. The FFI surface does
+ * not run `ref_alloc::allocate_refs`; refs are a CLI/JSON pipeline
+ * concern, so agent-facing code that needs them should drive them
+ * externally (resolve via `ad_find` + `ad_free_handle`, or call the
+ * CLI if refs are required).
+ * - `include_bounds`, `interactive_only`, and `compact` are honored
+ * after the adapter returns the raw tree, using
+ * `ref_alloc::transform_tree`. Because refs are not allocated here,
+ * the `interactive_only` cut is role-based rather than ref-based;
+ * otherwise the semantics match the CLI snapshot path.
+ * - No skeleton/drill-down pipeline is wired through — `skeleton` is
+ * always false on the underlying `TreeOptions`.
+ *
+ * If parity with the CLI snapshot is important to your consumer,
+ * either use `ad_find` + `ad_get` / `ad_is` for point lookups (which
+ * bypass tree shape entirely) or invoke the CLI binary for the
+ * snapshot call. A future revision may layer a "normalized snapshot"
+ * FFI function on top of this raw path.
+ *
+ * On error `*out` is zeroed so `ad_free_tree` on it is a safe no-op.
+ *
+ * # Safety
+ * All pointers must be non-null. `win.id` and `win.title` must be
+ * valid UTF-8 C strings. `out` must be writable.
+ */
+AdResult ad_get_tree(const struct AdAdapter *adapter,
+ const struct AdWindowInfo *win,
+ const struct AdTreeOptions *opts,
+ struct AdNodeTree *out);
+
+/**
+ * Brings `win` to the foreground on the current space. Returns
+ * `AD_RESULT_ERR_WINDOW_NOT_FOUND` when the referenced window no longer
+ * exists (the caller should re-list and retry).
+ *
+ * # Safety
+ * `adapter` must be a non-null pointer from `ad_adapter_create`. `win`
+ * must be a non-null pointer to an `AdWindowInfo` whose `id` and
+ * `title` fields are non-null, valid UTF-8 C strings.
+ */
+AdResult ad_focus_window(const struct AdAdapter *adapter, const struct AdWindowInfo *win);
+
+/**
+ * Releases the heap-allocated string fields (`id`, `title`, `app_name`)
+ * inside a single `AdWindowInfo` previously written by `ad_launch_app`
+ * or returned through a list accessor. Does not free the `AdWindowInfo`
+ * struct itself — that memory is owned by the caller's stack or by the
+ * enclosing list.
+ *
+ * Named `ad_release_window_fields` (not `ad_free_window`) to disambiguate
+ * from the now-removed list-free function and make the semantics clear
+ * in the header.
+ *
+ * # Safety
+ * `win` must be null or point to a valid `AdWindowInfo` whose string
+ * fields were allocated by this crate. Do not call on pointers inside
+ * an `AdWindowList` — free the list instead.
+ */
+void ad_release_window_fields(struct AdWindowInfo *win);
+
+/**
+ * # Safety
+ * `adapter` must be valid. `out` must be a valid writable
+ * `*mut *mut AdWindowList`. `app_filter` may be null or a C string.
+ * Success produces a list handle freed via `ad_window_list_free`.
+ */
+AdResult ad_list_windows(const struct AdAdapter *adapter,
+ const char *app_filter,
+ bool focused_only,
+ struct AdWindowList **out);
+
+/**
+ * # Safety
+ * `list` must be null or a pointer returned by `ad_list_windows`.
+ */
+uint32_t ad_window_list_count(const struct AdWindowList *list);
+
+/**
+ * Borrow a window info entry. Null if `index` is out of range.
+ *
+ * # Safety
+ * `list` must be null or a pointer returned by `ad_list_windows`.
+ */
+const struct AdWindowInfo *ad_window_list_get(const struct AdWindowList *list, uint32_t index);
+
+/**
+ * Frees the list and each entry's interior strings.
+ *
+ * # Safety
+ * `list` must be null or a pointer returned by `ad_list_windows`.
+ */
+void ad_window_list_free(struct AdWindowList *list);
+
+/**
+ * Performs a window-manager operation (`Resize`, `Move`, `Minimize`,
+ * `Maximize`, `Restore`) on `win`. Width / height / x / y are consulted
+ * only for the variants that use them; other kinds ignore them.
+ *
+ * An invalid `op.kind` discriminant is rejected with
+ * `AD_RESULT_ERR_INVALID_ARGS` before any adapter call.
+ *
+ * # Safety
+ * `adapter` and `win` must be non-null pointers. `win.id` and
+ * `win.title` must be non-null valid UTF-8 C strings.
+ */
+AdResult ad_window_op(const struct AdAdapter *adapter,
+ const struct AdWindowInfo *win,
+ struct AdWindowOp op);
+
+#endif /* AGENT_DESKTOP_H */
diff --git a/crates/ffi/src/actions/conversion.rs b/crates/ffi/src/actions/conversion.rs
new file mode 100644
index 000000000..ab698bcf1
--- /dev/null
+++ b/crates/ffi/src/actions/conversion.rs
@@ -0,0 +1,233 @@
+use crate::convert::string::c_to_string;
+use crate::types::{AdAction, AdActionKind, AdDirection, AdKeyCombo, AdModifier};
+use agent_desktop_core::action::{
+ Action, Direction, DragParams as CoreDragParams, KeyCombo as CoreKeyCombo, Modifier,
+ Point as CorePoint,
+};
+
+fn direction_from_c(d: AdDirection) -> Direction {
+ match d {
+ AdDirection::Up => Direction::Up,
+ AdDirection::Down => Direction::Down,
+ AdDirection::Left => Direction::Left,
+ AdDirection::Right => Direction::Right,
+ }
+}
+
+/// Four modifier keys exist (`AdModifier::{Cmd, Ctrl, Alt, Shift}`),
+/// so a combo can name at most four. Anything larger must be bogus
+/// input — bail out instead of trusting it into `from_raw_parts`.
+const MAX_MODIFIERS_PER_COMBO: u32 = 4;
+
+pub(crate) unsafe fn key_combo_from_c(k: &AdKeyCombo) -> Result<CoreKeyCombo, &'static str> {
+ let key = c_to_string(k.key).ok_or("key is null or invalid UTF-8")?;
+
+ if k.modifier_count > MAX_MODIFIERS_PER_COMBO {
+ return Err("modifier_count exceeds MAX_MODIFIERS_PER_COMBO (4)");
+ }
+ if k.modifier_count > 0 && k.modifiers.is_null() {
+ return Err("modifier_count > 0 but modifiers pointer is null");
+ }
+
+ let mut modifiers = Vec::with_capacity(k.modifier_count as usize);
+ if k.modifier_count > 0 {
+ let slice = std::slice::from_raw_parts(k.modifiers, k.modifier_count as usize);
+ for raw_modifier in slice {
+ let m = AdModifier::from_c(*raw_modifier).ok_or("invalid modifier discriminant")?;
+ let modifier = match m {
+ AdModifier::Cmd => Modifier::Cmd,
+ AdModifier::Ctrl => Modifier::Ctrl,
+ AdModifier::Alt => Modifier::Alt,
+ AdModifier::Shift => Modifier::Shift,
+ };
+ modifiers.push(modifier);
+ }
+ }
+ Ok(CoreKeyCombo { key, modifiers })
+}
+
+pub(crate) unsafe fn action_from_c(action: &AdAction) -> Result<Action, &'static str> {
+ let kind = AdActionKind::from_c(action.kind).ok_or("invalid action kind discriminant")?;
+ match kind {
+ AdActionKind::Click => Ok(Action::Click),
+ AdActionKind::DoubleClick => Ok(Action::DoubleClick),
+ AdActionKind::RightClick => Ok(Action::RightClick),
+ AdActionKind::TripleClick => Ok(Action::TripleClick),
+ AdActionKind::SetFocus => Ok(Action::SetFocus),
+ AdActionKind::Expand => Ok(Action::Expand),
+ AdActionKind::Collapse => Ok(Action::Collapse),
+ AdActionKind::Toggle => Ok(Action::Toggle),
+ AdActionKind::Check => Ok(Action::Check),
+ AdActionKind::Uncheck => Ok(Action::Uncheck),
+ AdActionKind::ScrollTo => Ok(Action::ScrollTo),
+ AdActionKind::Clear => Ok(Action::Clear),
+ AdActionKind::Hover => Ok(Action::Hover),
+ AdActionKind::SetValue => {
+ let text = c_to_string(action.text).ok_or("text is null or invalid UTF-8")?;
+ Ok(Action::SetValue(text))
+ }
+ AdActionKind::Select => {
+ let text = c_to_string(action.text).ok_or("text is null or invalid UTF-8")?;
+ Ok(Action::Select(text))
+ }
+ AdActionKind::TypeText => {
+ let text = c_to_string(action.text).ok_or("text is null or invalid UTF-8")?;
+ Ok(Action::TypeText(text))
+ }
+ AdActionKind::Scroll => {
+ let raw_dir = AdDirection::from_c(action.scroll.direction)
+ .ok_or("invalid scroll direction discriminant")?;
+ let dir = direction_from_c(raw_dir);
+ Ok(Action::Scroll(dir, action.scroll.amount))
+ }
+ AdActionKind::PressKey => {
+ let combo = key_combo_from_c(&action.key)?;
+ Ok(Action::PressKey(combo))
+ }
+ AdActionKind::KeyDown => {
+ let combo = key_combo_from_c(&action.key)?;
+ Ok(Action::KeyDown(combo))
+ }
+ AdActionKind::KeyUp => {
+ let combo = key_combo_from_c(&action.key)?;
+ Ok(Action::KeyUp(combo))
+ }
+ AdActionKind::Drag => {
+ let params = CoreDragParams {
+ from: CorePoint {
+ x: action.drag.from.x,
+ y: action.drag.from.y,
+ },
+ to: CorePoint {
+ x: action.drag.to.x,
+ y: action.drag.to.y,
+ },
+ duration_ms: if action.drag.duration_ms == 0 {
+ None
+ } else {
+ Some(action.drag.duration_ms)
+ },
+ };
+ Ok(Action::Drag(params))
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::convert::string::{free_c_string, string_to_c};
+ use crate::types::{AdDragParams, AdPoint, AdScrollParams};
+ use std::ptr;
+
+ fn make_scroll_params() -> AdScrollParams {
+ AdScrollParams {
+ direction: AdDirection::Down as i32,
+ amount: 3,
+ }
+ }
+
+ fn make_key_combo() -> AdKeyCombo {
+ AdKeyCombo {
+ key: ptr::null(),
+ modifiers: ptr::null(),
+ modifier_count: 0,
+ }
+ }
+
+ fn make_drag_params() -> AdDragParams {
+ AdDragParams {
+ from: AdPoint { x: 0.0, y: 0.0 },
+ to: AdPoint { x: 0.0, y: 0.0 },
+ duration_ms: 0,
+ }
+ }
+
+ #[test]
+ fn test_simple_action_roundtrip() {
+ let action = AdAction {
+ kind: AdActionKind::Click as i32,
+ text: ptr::null(),
+ scroll: make_scroll_params(),
+ key: make_key_combo(),
+ drag: make_drag_params(),
+ };
+ let result = unsafe { action_from_c(&action) };
+ assert!(result.is_ok());
+ assert!(matches!(result.unwrap(), Action::Click));
+ }
+
+ #[test]
+ fn test_set_value_action() {
+ let text = string_to_c("hello world");
+ let action = AdAction {
+ kind: AdActionKind::SetValue as i32,
+ text,
+ scroll: make_scroll_params(),
+ key: make_key_combo(),
+ drag: make_drag_params(),
+ };
+ let result = unsafe { action_from_c(&action) };
+ assert!(result.is_ok());
+ assert!(matches!(result.unwrap(), Action::SetValue(ref s) if s == "hello world"));
+ unsafe { free_c_string(text as *mut _) };
+ }
+
+ #[test]
+ fn test_scroll_action() {
+ let action = AdAction {
+ kind: AdActionKind::Scroll as i32,
+ text: ptr::null(),
+ scroll: AdScrollParams {
+ direction: AdDirection::Up as i32,
+ amount: 5,
+ },
+ key: make_key_combo(),
+ drag: make_drag_params(),
+ };
+ let result = unsafe { action_from_c(&action) };
+ assert!(result.is_ok());
+ assert!(matches!(result.unwrap(), Action::Scroll(Direction::Up, 5)));
+ }
+
+ #[test]
+ fn key_combo_rejects_modifier_count_exceeding_cap() {
+ let key = string_to_c("a");
+ let combo = AdKeyCombo {
+ key,
+ modifiers: ptr::null(),
+ modifier_count: 5,
+ };
+ let result = unsafe { key_combo_from_c(&combo) };
+ assert!(result.is_err());
+ unsafe { free_c_string(key as *mut _) };
+ }
+
+ #[test]
+ fn key_combo_rejects_positive_count_with_null_pointer() {
+ let key = string_to_c("a");
+ let combo = AdKeyCombo {
+ key,
+ modifiers: ptr::null(),
+ modifier_count: 2,
+ };
+ let result = unsafe { key_combo_from_c(&combo) };
+ assert!(result.is_err());
+ unsafe { free_c_string(key as *mut _) };
+ }
+
+ #[test]
+ fn key_combo_accepts_valid_modifier_slice() {
+ let key = string_to_c("s");
+ let mods: [i32; 2] = [AdModifier::Cmd as i32, AdModifier::Shift as i32];
+ let combo = AdKeyCombo {
+ key,
+ modifiers: mods.as_ptr(),
+ modifier_count: 2,
+ };
+ let result = unsafe { key_combo_from_c(&combo) }.unwrap();
+ assert_eq!(result.key, "s");
+ assert_eq!(result.modifiers.len(), 2);
+ unsafe { free_c_string(key as *mut _) };
+ }
+}
diff --git a/crates/ffi/src/actions/execute.rs b/crates/ffi/src/actions/execute.rs
new file mode 100644
index 000000000..8d2464261
--- /dev/null
+++ b/crates/ffi/src/actions/execute.rs
@@ -0,0 +1,63 @@
+use crate::actions::conversion::action_from_c;
+use crate::actions::result::action_result_to_c;
+use crate::error::{self, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::types::{AdAction, AdActionResult, AdNativeHandle};
+use crate::AdAdapter;
+use agent_desktop_core::adapter::NativeHandle;
+
+/// # Safety
+///
+/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+/// `handle` must be a non-null pointer to a valid `AdNativeHandle`.
+/// `action` must be a non-null pointer to a valid `AdAction`.
+/// `out` must be a non-null pointer to an `AdActionResult` to write the result into.
+#[no_mangle]
+pub unsafe extern "C" fn ad_execute_action(
+ adapter: *const AdAdapter,
+ handle: *const AdNativeHandle,
+ action: *const AdAction,
+ out: *mut AdActionResult,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ crate::pointer_guard::guard_non_null!(out, c"out is null");
+ *out = std::mem::zeroed();
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ crate::pointer_guard::guard_non_null!(handle, c"handle is null");
+ crate::pointer_guard::guard_non_null!(action, c"action is null");
+ let adapter = &*adapter;
+ let handle_ref = &*handle;
+ if handle_ref.ptr.is_null() {
+ error::set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "handle.ptr is null — the handle has already been freed or was never resolved",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ let action_ref = &*action;
+ let core_action = match action_from_c(action_ref) {
+ Ok(a) => a,
+ Err(msg) => {
+ error::set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ msg,
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+ let native_handle = NativeHandle::from_ptr(handle_ref.ptr);
+ match adapter.inner.execute_action(&native_handle, core_action) {
+ Ok(result) => {
+ *out = action_result_to_c(&result);
+ AdResult::Ok
+ }
+ Err(e) => {
+ error::set_last_error(&e);
+ error::last_error_code()
+ }
+ }
+ })
+}
diff --git a/crates/ffi/src/actions/mod.rs b/crates/ffi/src/actions/mod.rs
new file mode 100644
index 000000000..c2d211989
--- /dev/null
+++ b/crates/ffi/src/actions/mod.rs
@@ -0,0 +1,5 @@
+pub(crate) mod conversion;
+pub(crate) mod execute;
+pub(crate) mod native_handle;
+pub(crate) mod resolve;
+pub(crate) mod result;
diff --git a/crates/ffi/src/actions/native_handle.rs b/crates/ffi/src/actions/native_handle.rs
new file mode 100644
index 000000000..8095e7d46
--- /dev/null
+++ b/crates/ffi/src/actions/native_handle.rs
@@ -0,0 +1,72 @@
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::types::AdNativeHandle;
+use crate::AdAdapter;
+use agent_desktop_core::adapter::NativeHandle;
+
+/// Releases a handle previously returned by `ad_resolve_element` and
+/// zeroes the caller's struct so accidentally calling this twice is
+/// a deterministic no-op instead of a double-free on the underlying
+/// `CFRelease`.
+///
+/// On macOS this calls `CFRelease` on the underlying `AXUIElementRef`,
+/// balancing the `CFRetain` that happened during `ad_resolve_element`.
+/// On Windows/Linux the call is a no-op that returns `AD_RESULT_OK`
+/// (platform adapters inherit the default `not_supported` impl; the
+/// FFI surface translates it so callers apply the same release
+/// pattern everywhere).
+///
+/// Ownership contract: the FFI owns the handle from the moment
+/// `ad_resolve_element` writes `ptr`. Copying the struct after that
+/// point and calling `ad_free_handle` on either copy is undefined —
+/// there is no way for the library to detect forged non-null pointers.
+/// Callers that legitimately need a "copy" should re-resolve.
+///
+/// # Safety
+///
+/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+/// `handle` must be null or a `*mut AdNativeHandle` previously
+/// populated by `ad_resolve_element`. On return `(*handle).ptr` is
+/// `NULL` so a double-call is a no-op instead of a double-free.
+#[no_mangle]
+pub unsafe extern "C" fn ad_free_handle(
+ adapter: *const AdAdapter,
+ handle: *mut AdNativeHandle,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ if adapter.is_null() {
+ set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "adapter is null",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ if handle.is_null() {
+ return AdResult::Ok;
+ }
+ let raw = (*handle).ptr;
+ if raw.is_null() {
+ return AdResult::Ok;
+ }
+ // Zero the caller-visible pointer *before* the platform release
+ // so a concurrent or accidental double-call through the same
+ // struct cannot re-enter CFRelease on the same underlying ref.
+ (*handle).ptr = std::ptr::null();
+ let adapter = &*adapter;
+ let native = NativeHandle::from_ptr(raw);
+ match adapter.inner.release_handle(&native) {
+ Ok(()) => AdResult::Ok,
+ Err(e) => {
+ if matches!(
+ e.code,
+ agent_desktop_core::error::ErrorCode::ActionNotSupported
+ | agent_desktop_core::error::ErrorCode::PlatformNotSupported
+ ) {
+ return AdResult::Ok;
+ }
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ }
+ })
+}
diff --git a/crates/ffi/src/actions/resolve.rs b/crates/ffi/src/actions/resolve.rs
new file mode 100644
index 000000000..5c50dfcf4
--- /dev/null
+++ b/crates/ffi/src/actions/resolve.rs
@@ -0,0 +1,82 @@
+use crate::convert::string::{c_to_string, try_c_to_string};
+use crate::error::{self, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::types::{AdNativeHandle, AdRefEntry};
+use crate::AdAdapter;
+use agent_desktop_core::refs::RefEntry as CoreRefEntry;
+
+/// # Safety
+///
+/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+/// `entry` must be a non-null pointer to a valid `AdRefEntry`.
+/// `out` must be a non-null pointer to an `AdNativeHandle` to write the result into.
+#[no_mangle]
+pub unsafe extern "C" fn ad_resolve_element(
+ adapter: *const AdAdapter,
+ entry: *const AdRefEntry,
+ out: *mut AdNativeHandle,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ crate::pointer_guard::guard_non_null!(out, c"out is null");
+ (*out).ptr = std::ptr::null();
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ crate::pointer_guard::guard_non_null!(entry, c"entry is null");
+ let adapter = &*adapter;
+ let entry = &*entry;
+ let role = match c_to_string(entry.role) {
+ Some(s) => s,
+ None => {
+ error::set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "role is null or invalid UTF-8",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+ // Fail closed on invalid UTF-8 for `name`: conflating "null" with
+ // "bad bytes" would widen a caller-specified filter into an
+ // unfiltered re-resolution. try_c_to_string keeps null → None and
+ // promotes invalid UTF-8 to an explicit InvalidArgs, matching the
+ // optional-filter contract used by ad_list_* entrypoints.
+ let name = match try_c_to_string(entry.name) {
+ Ok(value) => value,
+ Err(()) => {
+ error::set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "name is not valid UTF-8",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+ let bounds_hash = if entry.has_bounds_hash {
+ Some(entry.bounds_hash)
+ } else {
+ None
+ };
+ let core_entry = CoreRefEntry {
+ pid: entry.pid,
+ role,
+ name,
+ value: None,
+ states: vec![],
+ bounds: None,
+ bounds_hash,
+ available_actions: vec![],
+ source_app: None,
+ root_ref: None,
+ };
+ match adapter.inner.resolve_element(&core_entry) {
+ Ok(handle) => {
+ (*out).ptr = handle.as_raw();
+ AdResult::Ok
+ }
+ Err(e) => {
+ error::set_last_error(&e);
+ error::last_error_code()
+ }
+ }
+ })
+}
diff --git a/crates/ffi/src/actions/result.rs b/crates/ffi/src/actions/result.rs
new file mode 100644
index 000000000..b2902b6a3
--- /dev/null
+++ b/crates/ffi/src/actions/result.rs
@@ -0,0 +1,112 @@
+use crate::convert::string::{free_c_string, opt_string_to_c, string_to_c_lossy};
+use crate::types::{AdActionResult, AdElementState};
+use agent_desktop_core::action::ActionResult as CoreActionResult;
+use std::ptr;
+
+pub(crate) fn action_result_to_c(r: &CoreActionResult) -> AdActionResult {
+ let action = string_to_c_lossy(&r.action);
+ let ref_id = opt_string_to_c(r.ref_id.as_deref());
+ let post_state = match &r.post_state {
+ None => ptr::null_mut(),
+ Some(state) => {
+ let role = string_to_c_lossy(&state.role);
+ let value = opt_string_to_c(state.value.as_deref());
+ let state_count = state.states.len() as u32;
+ let states = if state.states.is_empty() {
+ ptr::null_mut()
+ } else {
+ let ptrs: Vec<*mut std::os::raw::c_char> =
+ state.states.iter().map(|s| string_to_c_lossy(s)).collect();
+ let mut boxed = ptrs.into_boxed_slice();
+ let raw = boxed.as_mut_ptr();
+ std::mem::forget(boxed);
+ raw
+ };
+ let elem = Box::new(AdElementState {
+ role,
+ states,
+ state_count,
+ value,
+ });
+ Box::into_raw(elem)
+ }
+ };
+ AdActionResult {
+ action,
+ ref_id,
+ post_state,
+ }
+}
+
+/// # Safety
+///
+/// `result` must be a pointer to an `AdActionResult` previously written by `ad_execute_action`,
+/// or null. After this call all pointers inside the struct are invalid.
+#[no_mangle]
+pub unsafe extern "C" fn ad_free_action_result(result: *mut AdActionResult) {
+ crate::ffi_try::trap_panic_void(|| unsafe {
+ if result.is_null() {
+ return;
+ }
+ let r = &mut *result;
+ free_c_string(r.action as *mut _);
+ free_c_string(r.ref_id as *mut _);
+ if !r.post_state.is_null() {
+ let state = &mut *r.post_state;
+ free_c_string(state.role as *mut _);
+ free_c_string(state.value as *mut _);
+ if !state.states.is_null() && state.state_count > 0 {
+ let slice =
+ std::slice::from_raw_parts_mut(state.states, state.state_count as usize);
+ for ptr in slice.iter() {
+ free_c_string(*ptr);
+ }
+ drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(
+ state.states,
+ state.state_count as usize,
+ )));
+ }
+ drop(Box::from_raw(r.post_state));
+ r.post_state = ptr::null_mut();
+ }
+ r.action = ptr::null();
+ r.ref_id = ptr::null();
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::convert::string::c_to_string;
+ use agent_desktop_core::action::ElementState;
+
+ #[test]
+ fn test_action_result_to_c_with_state() {
+ let core_result = CoreActionResult {
+ action: "click".to_owned(),
+ ref_id: Some("@e3".to_owned()),
+ post_state: Some(ElementState {
+ role: "button".to_owned(),
+ states: vec!["focused".to_owned(), "enabled".to_owned()],
+ value: Some("OK".to_owned()),
+ }),
+ };
+ let c_result = action_result_to_c(&core_result);
+ unsafe {
+ assert_eq!(c_to_string(c_result.action).as_deref(), Some("click"));
+ assert_eq!(c_to_string(c_result.ref_id).as_deref(), Some("@e3"));
+ assert!(!c_result.post_state.is_null());
+ let state = &*c_result.post_state;
+ assert_eq!(c_to_string(state.role).as_deref(), Some("button"));
+ assert_eq!(c_to_string(state.value).as_deref(), Some("OK"));
+ assert_eq!(state.state_count, 2);
+ }
+ let mut c_result = c_result;
+ unsafe { ad_free_action_result(&mut c_result) };
+ }
+
+ #[test]
+ fn test_free_null_action_result() {
+ unsafe { ad_free_action_result(ptr::null_mut()) };
+ }
+}
diff --git a/crates/ffi/src/adapter.rs b/crates/ffi/src/adapter.rs
new file mode 100644
index 000000000..46af26d95
--- /dev/null
+++ b/crates/ffi/src/adapter.rs
@@ -0,0 +1,99 @@
+use crate::error::{self, AdResult};
+use crate::ffi_try::{trap_panic, trap_panic_ptr, trap_panic_void};
+use agent_desktop_core::adapter::PlatformAdapter;
+
+pub struct AdAdapter {
+ pub(crate) inner: Box<dyn PlatformAdapter>,
+}
+
+fn build_adapter() -> Box<dyn PlatformAdapter> {
+ #[cfg(target_os = "macos")]
+ {
+ Box::new(agent_desktop_macos::MacOSAdapter::new())
+ }
+
+ #[cfg(target_os = "windows")]
+ {
+ Box::new(agent_desktop_windows::WindowsAdapter::new())
+ }
+
+ #[cfg(target_os = "linux")]
+ {
+ Box::new(agent_desktop_linux::LinuxAdapter::new())
+ }
+
+ #[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
+ compile_error!("Unsupported platform")
+}
+
+/// Builds a platform adapter for the current OS and returns an opaque
+/// handle. Returns null on allocation failure or if a Rust panic is
+/// caught at the FFI boundary (inspect `ad_last_error_*` for details).
+///
+/// The returned pointer is owned by the caller and must be released with
+/// `ad_adapter_destroy`. Creating and destroying adapters is cheap; the
+/// common pattern is one adapter per process lifetime.
+#[no_mangle]
+pub extern "C" fn ad_adapter_create() -> *mut AdAdapter {
+ trap_panic_ptr(|| {
+ let adapter = AdAdapter {
+ inner: build_adapter(),
+ };
+ Box::into_raw(Box::new(adapter))
+ })
+}
+
+/// # Safety
+///
+/// `adapter` must be a pointer returned by `ad_adapter_create`, or null.
+/// After this call the pointer is invalid and must not be used.
+#[no_mangle]
+pub unsafe extern "C" fn ad_adapter_destroy(adapter: *mut AdAdapter) {
+ trap_panic_void(|| {
+ if !adapter.is_null() {
+ drop(unsafe { Box::from_raw(adapter) });
+ }
+ })
+}
+
+/// # Safety
+///
+/// `adapter` must be a non-null pointer returned by `ad_adapter_create` that
+/// has not yet been destroyed.
+#[no_mangle]
+pub unsafe extern "C" fn ad_check_permissions(adapter: *const AdAdapter) -> AdResult {
+ trap_panic(|| {
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ let adapter = unsafe { &*adapter };
+ match adapter.inner.check_permissions() {
+ agent_desktop_core::adapter::PermissionStatus::Granted => AdResult::Ok,
+ agent_desktop_core::adapter::PermissionStatus::Denied { suggestion } => {
+ error::set_last_error(
+ &agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::PermDenied,
+ "Accessibility permission not granted",
+ )
+ .with_suggestion(suggestion),
+ );
+ AdResult::ErrPermDenied
+ }
+ }
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_adapter_create_destroy() {
+ let ptr = ad_adapter_create();
+ assert!(!ptr.is_null());
+ unsafe { ad_adapter_destroy(ptr) };
+ }
+
+ #[test]
+ fn test_destroy_null_is_noop() {
+ unsafe { ad_adapter_destroy(std::ptr::null_mut()) };
+ }
+}
diff --git a/crates/ffi/src/apps/close.rs b/crates/ffi/src/apps/close.rs
new file mode 100644
index 000000000..4b600f365
--- /dev/null
+++ b/crates/ffi/src/apps/close.rs
@@ -0,0 +1,44 @@
+use crate::convert::string::c_to_string;
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::AdAdapter;
+use std::os::raw::c_char;
+
+/// Closes the application identified by `id` (bundle id on macOS,
+/// executable path on other platforms). `force = true` skips the
+/// graceful-shutdown path (equivalent to `kill -9`).
+///
+/// # Safety
+/// `adapter` must be non-null. `id` must be a non-null UTF-8 C string.
+#[no_mangle]
+pub unsafe extern "C" fn ad_close_app(
+ adapter: *const AdAdapter,
+ id: *const c_char,
+ force: bool,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ let adapter = &*adapter;
+ let id_str = match c_to_string(id) {
+ Some(s) => s,
+ None => {
+ set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "app id is null or invalid UTF-8",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+
+ match adapter.inner.close_app(&id_str, force) {
+ Ok(()) => AdResult::Ok,
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ }
+ })
+}
diff --git a/crates/ffi/src/apps/launch.rs b/crates/ffi/src/apps/launch.rs
new file mode 100644
index 000000000..9e52ff784
--- /dev/null
+++ b/crates/ffi/src/apps/launch.rs
@@ -0,0 +1,59 @@
+use crate::convert::string::c_to_string;
+use crate::convert::window::window_info_to_c;
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::types::AdWindowInfo;
+use crate::AdAdapter;
+use std::os::raw::c_char;
+
+/// Launches the application identified by `id` (bundle id on macOS,
+/// executable path on other platforms) and, on success, writes the
+/// first window that becomes available into `*out`. Waits up to
+/// `timeout_ms` for the window to appear; zero means "no wait".
+///
+/// The returned `AdWindowInfo` owns heap-allocated interior strings that
+/// must be released with `ad_release_window_fields` once done. On error
+/// the out-param is zero-initialized, so calling the release fn on it
+/// is a safe no-op.
+///
+/// # Safety
+/// `adapter` must be non-null. `id` must be a non-null UTF-8 C string.
+/// `out` must be a non-null writable `*mut AdWindowInfo`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_launch_app(
+ adapter: *const AdAdapter,
+ id: *const c_char,
+ timeout_ms: u64,
+ out: *mut AdWindowInfo,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ crate::pointer_guard::guard_non_null!(out, c"out is null");
+ *out = std::mem::zeroed();
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ let id_str = match c_to_string(id) {
+ Some(s) => s,
+ None => {
+ set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "app id is null or invalid UTF-8",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+
+ let adapter = &*adapter;
+ match adapter.inner.launch_app(&id_str, timeout_ms) {
+ Ok(win) => {
+ *out = window_info_to_c(&win);
+ AdResult::Ok
+ }
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ }
+ })
+}
diff --git a/crates/ffi/src/apps/list.rs b/crates/ffi/src/apps/list.rs
new file mode 100644
index 000000000..676765783
--- /dev/null
+++ b/crates/ffi/src/apps/list.rs
@@ -0,0 +1,87 @@
+use crate::convert::app::{app_info_to_c, free_app_info_fields};
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::{trap_panic, trap_panic_void};
+use crate::types::{AdAppInfo, AdAppList};
+use crate::AdAdapter;
+use std::ptr;
+
+/// # Safety
+/// `adapter` must be a valid pointer from `ad_adapter_create`.
+/// `out` must be a valid writable `*mut *mut AdAppList`.
+/// On success, `*out` is a newly-allocated opaque list freed with
+/// `ad_app_list_free`. On error, `*out` is null and last-error is set.
+#[no_mangle]
+pub unsafe extern "C" fn ad_list_apps(
+ adapter: *const AdAdapter,
+ out: *mut *mut AdAppList,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ crate::pointer_guard::guard_non_null!(out, c"out is null");
+ *out = ptr::null_mut();
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ let adapter = &*adapter;
+ match adapter.inner.list_apps() {
+ Ok(apps) => {
+ let items: Vec<AdAppInfo> = apps.iter().map(app_info_to_c).collect();
+ let list = Box::new(AdAppList {
+ items: items.into_boxed_slice(),
+ });
+ *out = Box::into_raw(list);
+ AdResult::Ok
+ }
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ }
+ })
+}
+
+/// # Safety
+/// `list` must be null or a pointer returned by `ad_list_apps`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_app_list_count(list: *const AdAppList) -> u32 {
+ if list.is_null() {
+ return 0;
+ }
+ let list_ref: &AdAppList = unsafe { &*list };
+ list_ref.items.len() as u32
+}
+
+/// Returns a borrowed pointer into the list; valid until the list is freed.
+/// Out-of-range `index` returns null.
+///
+/// # Safety
+/// `list` must be null or a pointer returned by `ad_list_apps`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_app_list_get(list: *const AdAppList, index: u32) -> *const AdAppInfo {
+ if list.is_null() {
+ return ptr::null();
+ }
+ let list_ref: &AdAppList = unsafe { &*list };
+ match list_ref.items.get(index as usize) {
+ Some(item) => item as *const AdAppInfo,
+ None => ptr::null(),
+ }
+}
+
+/// Frees the list and every `AdAppInfo` it owns, including the interior
+/// C-strings.
+///
+/// # Safety
+/// `list` must be null or a pointer returned by `ad_list_apps`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_app_list_free(list: *mut AdAppList) {
+ trap_panic_void(|| unsafe {
+ if list.is_null() {
+ return;
+ }
+ let mut list = Box::from_raw(list);
+ for item in list.items.iter_mut() {
+ free_app_info_fields(item);
+ }
+ })
+}
diff --git a/crates/ffi/src/apps/mod.rs b/crates/ffi/src/apps/mod.rs
new file mode 100644
index 000000000..34893d1ff
--- /dev/null
+++ b/crates/ffi/src/apps/mod.rs
@@ -0,0 +1,3 @@
+pub(crate) mod close;
+pub(crate) mod launch;
+pub(crate) mod list;
diff --git a/crates/ffi/src/convert/app.rs b/crates/ffi/src/convert/app.rs
new file mode 100644
index 000000000..1adaa4198
--- /dev/null
+++ b/crates/ffi/src/convert/app.rs
@@ -0,0 +1,43 @@
+use crate::convert::string::{free_c_string, opt_string_to_c, string_to_c_lossy};
+use crate::types::AdAppInfo;
+use agent_desktop_core::node::AppInfo;
+use std::os::raw::c_char;
+use std::ptr;
+
+pub(crate) fn app_info_to_c(a: &AppInfo) -> AdAppInfo {
+ AdAppInfo {
+ name: string_to_c_lossy(&a.name),
+ pid: a.pid,
+ bundle_id: opt_string_to_c(a.bundle_id.as_deref()),
+ }
+}
+
+pub(crate) unsafe fn free_app_info_fields(a: &mut AdAppInfo) {
+ free_c_string(a.name as *mut c_char);
+ free_c_string(a.bundle_id as *mut c_char);
+ a.name = ptr::null();
+ a.bundle_id = ptr::null();
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::convert::string::c_to_string;
+
+ #[test]
+ fn test_app_info_roundtrip() {
+ let a = AppInfo {
+ name: "Finder".into(),
+ pid: 42,
+ bundle_id: Some("com.apple.finder".into()),
+ };
+ let c = app_info_to_c(&a);
+ assert_eq!(unsafe { c_to_string(c.name) }.as_deref(), Some("Finder"));
+ assert_eq!(
+ unsafe { c_to_string(c.bundle_id) }.as_deref(),
+ Some("com.apple.finder")
+ );
+ let mut c = c;
+ unsafe { free_app_info_fields(&mut c) };
+ }
+}
diff --git a/crates/ffi/src/convert/mod.rs b/crates/ffi/src/convert/mod.rs
new file mode 100644
index 000000000..deece1678
--- /dev/null
+++ b/crates/ffi/src/convert/mod.rs
@@ -0,0 +1,8 @@
+pub(crate) mod app;
+pub(crate) mod notification;
+pub(crate) mod rect;
+pub(crate) mod string;
+pub(crate) mod surface;
+pub(crate) mod window;
+
+pub(crate) use rect::rect_to_c;
diff --git a/crates/ffi/src/convert/notification.rs b/crates/ffi/src/convert/notification.rs
new file mode 100644
index 000000000..9f3a0edb3
--- /dev/null
+++ b/crates/ffi/src/convert/notification.rs
@@ -0,0 +1,55 @@
+use crate::convert::string::{free_c_string, opt_string_to_c, string_to_c_lossy};
+use crate::types::AdNotificationInfo;
+use agent_desktop_core::notification::NotificationInfo;
+use std::os::raw::c_char;
+use std::ptr;
+
+pub(crate) fn notification_info_to_c(info: &NotificationInfo) -> AdNotificationInfo {
+ let (actions_ptr, action_count) = strings_to_c_array(&info.actions);
+ AdNotificationInfo {
+ index: info.index as u32,
+ app_name: string_to_c_lossy(&info.app_name),
+ title: string_to_c_lossy(&info.title),
+ body: opt_string_to_c(info.body.as_deref()),
+ actions: actions_ptr,
+ action_count,
+ }
+}
+
+pub(crate) unsafe fn free_notification_info_fields(info: &mut AdNotificationInfo) {
+ free_c_string(info.app_name as *mut c_char);
+ free_c_string(info.title as *mut c_char);
+ free_c_string(info.body as *mut c_char);
+ free_c_string_array(info.actions, info.action_count);
+ info.app_name = ptr::null();
+ info.title = ptr::null();
+ info.body = ptr::null();
+ info.actions = ptr::null_mut();
+ info.action_count = 0;
+}
+
+fn strings_to_c_array(strings: &[String]) -> (*mut *mut c_char, u32) {
+ if strings.is_empty() {
+ return (ptr::null_mut(), 0);
+ }
+ let ptrs: Vec<*mut c_char> = strings.iter().map(|s| string_to_c_lossy(s)).collect();
+ let count = ptrs.len() as u32;
+ let mut boxed = ptrs.into_boxed_slice();
+ let ptr = boxed.as_mut_ptr();
+ std::mem::forget(boxed);
+ (ptr, count)
+}
+
+unsafe fn free_c_string_array(arr: *mut *mut c_char, count: u32) {
+ if arr.is_null() {
+ return;
+ }
+ let slice = std::slice::from_raw_parts_mut(arr, count as usize);
+ for p in slice.iter_mut() {
+ free_c_string(*p);
+ }
+ drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(
+ arr,
+ count as usize,
+ )));
+}
diff --git a/crates/ffi/src/convert/rect.rs b/crates/ffi/src/convert/rect.rs
new file mode 100644
index 000000000..33131da7b
--- /dev/null
+++ b/crates/ffi/src/convert/rect.rs
@@ -0,0 +1,11 @@
+use crate::types::AdRect;
+use agent_desktop_core::node::Rect;
+
+pub(crate) fn rect_to_c(r: &Rect) -> AdRect {
+ AdRect {
+ x: r.x,
+ y: r.y,
+ width: r.width,
+ height: r.height,
+ }
+}
diff --git a/crates/ffi/src/convert/string.rs b/crates/ffi/src/convert/string.rs
new file mode 100644
index 000000000..91b4b93a8
--- /dev/null
+++ b/crates/ffi/src/convert/string.rs
@@ -0,0 +1,168 @@
+use std::ffi::{CStr, CString};
+use std::os::raw::c_char;
+use std::ptr;
+
+pub(crate) fn string_to_c(s: &str) -> *mut c_char {
+ match CString::new(s) {
+ Ok(cs) => cs.into_raw(),
+ Err(_) => ptr::null_mut(),
+ }
+}
+
+/// Lossy variant for **mandatory** C-string fields. Replaces any interior
+/// NUL byte with U+FFFD (3-byte UTF-8) before `CString::new`, so the
+/// result is never null on NUL-containing input. Use for fields the
+/// ABI contract forbids from being null (role, app_name, kind, ...).
+/// Optional fields should keep using `opt_string_to_c`.
+pub(crate) fn string_to_c_lossy(s: &str) -> *mut c_char {
+ if !s.bytes().any(|b| b == 0) {
+ return string_to_c(s);
+ }
+ let cleaned: String = s
+ .chars()
+ .map(|c| if c == '\0' { '\u{FFFD}' } else { c })
+ .collect();
+ match CString::new(cleaned) {
+ Ok(cs) => cs.into_raw(),
+ Err(_) => ptr::null_mut(),
+ }
+}
+
+pub(crate) fn opt_string_to_c(s: Option<&str>) -> *mut c_char {
+ match s {
+ Some(s) => string_to_c(s),
+ None => ptr::null_mut(),
+ }
+}
+
+pub(crate) unsafe fn free_c_string(ptr: *mut c_char) {
+ if !ptr.is_null() {
+ drop(CString::from_raw(ptr));
+ }
+}
+
+pub(crate) unsafe fn c_to_string(ptr: *const c_char) -> Option<String> {
+ if ptr.is_null() {
+ return None;
+ }
+ CStr::from_ptr(ptr).to_str().ok().map(str::to_owned)
+}
+
+/// Tri-state decode of a foreign C string used for optional filter
+/// fields where conflating null with invalid UTF-8 would silently widen
+/// an operation (e.g. treat "bad bytes" as "no filter").
+///
+/// - `Ok(None)` — pointer is null. Caller should treat as "filter
+/// absent".
+/// - `Ok(Some(s))` — pointer is non-null and decodes as valid UTF-8.
+/// - `Err(())` — pointer is non-null but the bytes are not UTF-8.
+/// Caller should surface `AD_RESULT_ERR_INVALID_ARGS` instead of
+/// treating this as missing.
+///
+/// # Safety
+/// `ptr` must be null or a NUL-terminated C string.
+pub(crate) unsafe fn try_c_to_string(ptr: *const c_char) -> Result<Option<String>, ()> {
+ if ptr.is_null() {
+ return Ok(None);
+ }
+ match CStr::from_ptr(ptr).to_str() {
+ Ok(s) => Ok(Some(s.to_owned())),
+ Err(_) => Err(()),
+ }
+}
+
+/// Decode an optional filter string, short-circuiting the enclosing
+/// `AdResult`-returning fn with `AD_RESULT_ERR_INVALID_ARGS` (and a
+/// tailored last-error diagnostic) when the pointer is non-null but
+/// the bytes are not UTF-8. Null → `None` (treated as "no filter").
+macro_rules! decode_optional_filter {
+ ($ptr:expr, $label:expr) => {{
+ match $crate::convert::string::try_c_to_string($ptr) {
+ Ok(value) => value,
+ Err(()) => {
+ $crate::error::set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ concat!($label, " is not valid UTF-8"),
+ ));
+ return $crate::error::AdResult::ErrInvalidArgs;
+ }
+ }
+ }};
+}
+
+pub(crate) use decode_optional_filter;
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_string_roundtrip() {
+ let c = string_to_c("hello");
+ assert!(!c.is_null());
+ let back = unsafe { c_to_string(c) };
+ assert_eq!(back.as_deref(), Some("hello"));
+ unsafe { free_c_string(c) };
+ }
+
+ #[test]
+ fn test_null_string() {
+ let c = opt_string_to_c(None);
+ assert!(c.is_null());
+ let back = unsafe { c_to_string(c) };
+ assert_eq!(back, None);
+ }
+
+ #[test]
+ fn test_free_null_is_noop() {
+ unsafe { free_c_string(ptr::null_mut()) };
+ }
+
+ #[test]
+ fn test_lossy_no_nul_same_as_string_to_c() {
+ let c = string_to_c_lossy("hello");
+ assert!(!c.is_null());
+ let back = unsafe { c_to_string(c) };
+ assert_eq!(back.as_deref(), Some("hello"));
+ unsafe { free_c_string(c) };
+ }
+
+ #[test]
+ fn test_lossy_replaces_interior_nul() {
+ let c = string_to_c_lossy("foo\0\0bar");
+ assert!(!c.is_null());
+ let back = unsafe { c_to_string(c) }.unwrap();
+ assert_eq!(back, "foo\u{FFFD}\u{FFFD}bar");
+ unsafe { free_c_string(c) };
+ }
+
+ #[test]
+ fn test_lossy_handles_all_nul_input() {
+ let c = string_to_c_lossy("\0\0\0");
+ assert!(!c.is_null());
+ let back = unsafe { c_to_string(c) }.unwrap();
+ assert_eq!(back, "\u{FFFD}\u{FFFD}\u{FFFD}");
+ unsafe { free_c_string(c) };
+ }
+
+ #[test]
+ fn try_c_to_string_null_is_ok_none() {
+ let result = unsafe { try_c_to_string(ptr::null()) };
+ assert!(matches!(result, Ok(None)));
+ }
+
+ #[test]
+ fn try_c_to_string_valid_utf8_is_some() {
+ let c = string_to_c("agent");
+ let result = unsafe { try_c_to_string(c) };
+ assert!(matches!(result, Ok(Some(ref s)) if s == "agent"));
+ unsafe { free_c_string(c) };
+ }
+
+ #[test]
+ fn try_c_to_string_invalid_utf8_is_err() {
+ let bad: [u8; 3] = [0xC3, 0xFF, 0x00];
+ let result = unsafe { try_c_to_string(bad.as_ptr() as *const c_char) };
+ assert!(matches!(result, Err(())));
+ }
+}
diff --git a/crates/ffi/src/convert/surface.rs b/crates/ffi/src/convert/surface.rs
new file mode 100644
index 000000000..882261b30
--- /dev/null
+++ b/crates/ffi/src/convert/surface.rs
@@ -0,0 +1,41 @@
+use crate::convert::string::{free_c_string, opt_string_to_c, string_to_c_lossy};
+use crate::types::AdSurfaceInfo;
+use agent_desktop_core::node::SurfaceInfo;
+use std::os::raw::c_char;
+use std::ptr;
+
+pub(crate) fn surface_info_to_c(s: &SurfaceInfo) -> AdSurfaceInfo {
+ AdSurfaceInfo {
+ kind: string_to_c_lossy(&s.kind),
+ title: opt_string_to_c(s.title.as_deref()),
+ item_count: s.item_count.map(|c| c as i64).unwrap_or(-1),
+ }
+}
+
+pub(crate) unsafe fn free_surface_info_fields(s: &mut AdSurfaceInfo) {
+ free_c_string(s.kind as *mut c_char);
+ free_c_string(s.title as *mut c_char);
+ s.kind = ptr::null();
+ s.title = ptr::null();
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::convert::string::c_to_string;
+
+ #[test]
+ fn test_surface_info_no_title() {
+ let s = SurfaceInfo {
+ kind: "menu".into(),
+ title: None,
+ item_count: Some(3),
+ };
+ let c = surface_info_to_c(&s);
+ assert_eq!(unsafe { c_to_string(c.kind) }.as_deref(), Some("menu"));
+ assert!(c.title.is_null());
+ assert_eq!(c.item_count, 3);
+ let mut c = c;
+ unsafe { free_surface_info_fields(&mut c) };
+ }
+}
diff --git a/crates/ffi/src/convert/window.rs b/crates/ffi/src/convert/window.rs
new file mode 100644
index 000000000..bc3347c3f
--- /dev/null
+++ b/crates/ffi/src/convert/window.rs
@@ -0,0 +1,79 @@
+use crate::convert::rect::rect_to_c;
+use crate::convert::string::{free_c_string, string_to_c_lossy};
+use crate::types::{AdRect, AdWindowInfo};
+use agent_desktop_core::node::WindowInfo;
+use std::os::raw::c_char;
+use std::ptr;
+
+pub(crate) fn window_info_to_c(w: &WindowInfo) -> AdWindowInfo {
+ let (bounds, has_bounds) = match &w.bounds {
+ Some(r) => (rect_to_c(r), true),
+ None => (
+ AdRect {
+ x: 0.0,
+ y: 0.0,
+ width: 0.0,
+ height: 0.0,
+ },
+ false,
+ ),
+ };
+ AdWindowInfo {
+ id: string_to_c_lossy(&w.id),
+ title: string_to_c_lossy(&w.title),
+ app_name: string_to_c_lossy(&w.app),
+ pid: w.pid,
+ bounds,
+ has_bounds,
+ is_focused: w.is_focused,
+ }
+}
+
+pub(crate) unsafe fn free_window_info_fields(w: &mut AdWindowInfo) {
+ free_c_string(w.id as *mut c_char);
+ free_c_string(w.title as *mut c_char);
+ free_c_string(w.app_name as *mut c_char);
+ w.id = ptr::null();
+ w.title = ptr::null();
+ w.app_name = ptr::null();
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::convert::string::c_to_string;
+ use agent_desktop_core::node::Rect;
+
+ #[test]
+ fn test_window_info_roundtrip() {
+ let w = WindowInfo {
+ id: "w-123".into(),
+ title: "Documents".into(),
+ app: "Finder".into(),
+ pid: 42,
+ bounds: Some(Rect {
+ x: 10.0,
+ y: 20.0,
+ width: 800.0,
+ height: 600.0,
+ }),
+ is_focused: true,
+ };
+ let c = window_info_to_c(&w);
+ assert_eq!(unsafe { c_to_string(c.id) }.as_deref(), Some("w-123"));
+ assert_eq!(
+ unsafe { c_to_string(c.title) }.as_deref(),
+ Some("Documents")
+ );
+ assert_eq!(
+ unsafe { c_to_string(c.app_name) }.as_deref(),
+ Some("Finder")
+ );
+ assert_eq!(c.pid, 42);
+ assert!(c.has_bounds);
+ assert_eq!(c.bounds.x, 10.0);
+ assert!(c.is_focused);
+ let mut c = c;
+ unsafe { free_window_info_fields(&mut c) };
+ }
+}
diff --git a/crates/ffi/src/enum_validation.rs b/crates/ffi/src/enum_validation.rs
new file mode 100644
index 000000000..6344d038d
--- /dev/null
+++ b/crates/ffi/src/enum_validation.rs
@@ -0,0 +1,181 @@
+//! C-boundary validation for every `#[repr(i32)]` enum exposed to C.
+//!
+//! Public ABI structs (`AdAction`, `AdMouseEvent`, `AdWindowOp`, etc.)
+//! store their enum-typed fields as raw `int32_t`. A foreign caller
+//! therefore never writes into a Rust enum slot, which would otherwise
+//! be undefined behavior on an out-of-range discriminant. Each raw
+//! value is converted to its typed enum via `<Enum>::from_c(raw: i32)`
+//! (generated by `try_from_c_enum!`); `None` → the FFI entrypoint
+//! returns `AD_RESULT_ERR_INVALID_ARGS`.
+
+use crate::types::{
+ AdActionKind, AdDirection, AdImageFormat, AdModifier, AdMouseButton, AdMouseEventKind,
+ AdScreenshotKind, AdSnapshotSurface, AdWindowOpKind,
+};
+
+macro_rules! try_from_c_enum {
+ ($ty:ty { $($variant:ident = $val:expr),+ $(,)? }) => {
+ impl $ty {
+ #[allow(dead_code)] // not every enum is read from C today; keep the validator uniformly
+ pub(crate) fn from_c(raw: i32) -> Option<Self> {
+ match raw {
+ $($val => Some(<$ty>::$variant),)+
+ _ => None,
+ }
+ }
+ }
+ };
+}
+
+try_from_c_enum! {
+ AdActionKind {
+ Click = 0, DoubleClick = 1, RightClick = 2, TripleClick = 3,
+ SetValue = 4, SetFocus = 5, Expand = 6, Collapse = 7,
+ Select = 8, Toggle = 9, Check = 10, Uncheck = 11,
+ Scroll = 12, ScrollTo = 13, PressKey = 14, KeyDown = 15,
+ KeyUp = 16, TypeText = 17, Clear = 18, Hover = 19, Drag = 20,
+ }
+}
+
+try_from_c_enum! {
+ AdDirection {
+ Up = 0, Down = 1, Left = 2, Right = 3,
+ }
+}
+
+try_from_c_enum! {
+ AdModifier {
+ Cmd = 0, Ctrl = 1, Alt = 2, Shift = 3,
+ }
+}
+
+try_from_c_enum! {
+ AdMouseButton {
+ Left = 0, Right = 1, Middle = 2,
+ }
+}
+
+try_from_c_enum! {
+ AdMouseEventKind {
+ Move = 0, Down = 1, Up = 2, Click = 3,
+ }
+}
+
+try_from_c_enum! {
+ AdWindowOpKind {
+ Resize = 0, Move = 1, Minimize = 2, Maximize = 3, Restore = 4,
+ }
+}
+
+try_from_c_enum! {
+ AdScreenshotKind {
+ Screen = 0, Window = 1, FullScreen = 2,
+ }
+}
+
+try_from_c_enum! {
+ AdImageFormat {
+ Png = 0, Jpg = 1,
+ }
+}
+
+try_from_c_enum! {
+ AdSnapshotSurface {
+ Window = 0, Focused = 1, Menu = 2, Menubar = 3,
+ Sheet = 4, Popover = 5, Alert = 6,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_action_kind_valid_range() {
+ for raw in 0..=20 {
+ assert!(AdActionKind::from_c(raw).is_some(), "raw = {}", raw);
+ }
+ }
+
+ #[test]
+ fn test_action_kind_out_of_range() {
+ assert!(AdActionKind::from_c(-1).is_none());
+ assert!(AdActionKind::from_c(21).is_none());
+ assert!(AdActionKind::from_c(999).is_none());
+ assert!(AdActionKind::from_c(i32::MAX).is_none());
+ assert!(AdActionKind::from_c(i32::MIN).is_none());
+ }
+
+ #[test]
+ fn test_direction_valid_range() {
+ for raw in 0..=3 {
+ assert!(AdDirection::from_c(raw).is_some());
+ }
+ assert!(AdDirection::from_c(4).is_none());
+ }
+
+ #[test]
+ fn test_modifier_valid_range() {
+ for raw in 0..=3 {
+ assert!(AdModifier::from_c(raw).is_some());
+ }
+ assert!(AdModifier::from_c(-5).is_none());
+ }
+
+ #[test]
+ fn test_mouse_button_valid_range() {
+ assert!(AdMouseButton::from_c(0).is_some());
+ assert!(AdMouseButton::from_c(2).is_some());
+ assert!(AdMouseButton::from_c(3).is_none());
+ }
+
+ #[test]
+ fn test_mouse_event_kind_valid_range() {
+ assert!(AdMouseEventKind::from_c(0).is_some());
+ assert!(AdMouseEventKind::from_c(3).is_some());
+ assert!(AdMouseEventKind::from_c(4).is_none());
+ }
+
+ #[test]
+ fn test_window_op_kind_valid_range() {
+ assert!(AdWindowOpKind::from_c(0).is_some());
+ assert!(AdWindowOpKind::from_c(4).is_some());
+ assert!(AdWindowOpKind::from_c(5).is_none());
+ }
+
+ #[test]
+ fn test_screenshot_kind_valid_range() {
+ assert!(AdScreenshotKind::from_c(0).is_some());
+ assert!(AdScreenshotKind::from_c(2).is_some());
+ assert!(AdScreenshotKind::from_c(3).is_none());
+ }
+
+ #[test]
+ fn test_image_format_valid_range() {
+ assert!(AdImageFormat::from_c(0).is_some());
+ assert!(AdImageFormat::from_c(1).is_some());
+ assert!(AdImageFormat::from_c(2).is_none());
+ }
+
+ #[test]
+ fn typed_enum_cast_round_trips_through_raw_i32() {
+ let raw = AdActionKind::Scroll as i32;
+ assert_eq!(raw, 12);
+ let back = AdActionKind::from_c(raw).unwrap();
+ assert!(matches!(back, AdActionKind::Scroll));
+ }
+
+ #[test]
+ fn fuzz_arbitrary_bit_patterns_never_panic_across_all_enums() {
+ for raw in [-1_000_000_i32, -1, 0, 1, 20, 21, 999, i32::MAX, i32::MIN] {
+ let _ = AdActionKind::from_c(raw);
+ let _ = AdDirection::from_c(raw);
+ let _ = AdModifier::from_c(raw);
+ let _ = AdMouseButton::from_c(raw);
+ let _ = AdMouseEventKind::from_c(raw);
+ let _ = AdWindowOpKind::from_c(raw);
+ let _ = AdScreenshotKind::from_c(raw);
+ let _ = AdImageFormat::from_c(raw);
+ }
+ }
+}
diff --git a/crates/ffi/src/error.rs b/crates/ffi/src/error.rs
new file mode 100644
index 000000000..d32998c54
--- /dev/null
+++ b/crates/ffi/src/error.rs
@@ -0,0 +1,324 @@
+use agent_desktop_core::error::{AdapterError, ErrorCode};
+use std::cell::RefCell;
+use std::ffi::{c_char, CStr, CString};
+
+const fn error_code_variant_count() -> usize {
+ let mut count = 0;
+ let variants = [
+ ErrorCode::PermDenied,
+ ErrorCode::ElementNotFound,
+ ErrorCode::AppNotFound,
+ ErrorCode::ActionFailed,
+ ErrorCode::ActionNotSupported,
+ ErrorCode::StaleRef,
+ ErrorCode::WindowNotFound,
+ ErrorCode::PlatformNotSupported,
+ ErrorCode::Timeout,
+ ErrorCode::InvalidArgs,
+ ErrorCode::NotificationNotFound,
+ ErrorCode::Internal,
+ ];
+ let mut i = 0;
+ while i < variants.len() {
+ count += 1;
+ i += 1;
+ }
+ count
+}
+
+const fn ad_result_error_variant_count() -> usize {
+ let variants = [
+ AdResult::ErrPermDenied,
+ AdResult::ErrElementNotFound,
+ AdResult::ErrAppNotFound,
+ AdResult::ErrActionFailed,
+ AdResult::ErrActionNotSupported,
+ AdResult::ErrStaleRef,
+ AdResult::ErrWindowNotFound,
+ AdResult::ErrPlatformNotSupported,
+ AdResult::ErrTimeout,
+ AdResult::ErrInvalidArgs,
+ AdResult::ErrNotificationNotFound,
+ AdResult::ErrInternal,
+ ];
+ let mut count = 0;
+ let mut i = 0;
+ while i < variants.len() {
+ count += 1;
+ i += 1;
+ }
+ count
+}
+
+// Compile-time parity check: every core `ErrorCode` variant must have a
+// matching `AdResult::Err*`. Adding a variant to either enum without
+// updating the other fails the build with the message below — preferable
+// to the silent-drop we'd otherwise see at the FFI boundary.
+const _: () = assert!(
+ error_code_variant_count() == ad_result_error_variant_count(),
+ "ErrorCode variants must match AdResult error-code variants one-to-one"
+);
+
+#[repr(i32)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AdResult {
+ Ok = 0,
+ ErrPermDenied = -1,
+ ErrElementNotFound = -2,
+ ErrAppNotFound = -3,
+ ErrActionFailed = -4,
+ ErrActionNotSupported = -5,
+ ErrStaleRef = -6,
+ ErrWindowNotFound = -7,
+ ErrPlatformNotSupported = -8,
+ ErrTimeout = -9,
+ ErrInvalidArgs = -10,
+ ErrNotificationNotFound = -11,
+ ErrInternal = -12,
+}
+
+enum MessageSource {
+ Owned(CString),
+ Static(&'static CStr),
+}
+
+impl MessageSource {
+ fn as_ptr(&self) -> *const c_char {
+ match self {
+ MessageSource::Owned(cs) => cs.as_ptr(),
+ MessageSource::Static(cs) => cs.as_ptr(),
+ }
+ }
+
+ #[cfg(test)]
+ fn to_owned_string(&self) -> String {
+ match self {
+ MessageSource::Owned(cs) => cs.to_string_lossy().into_owned(),
+ MessageSource::Static(cs) => cs.to_string_lossy().into_owned(),
+ }
+ }
+}
+
+struct StoredError {
+ code: AdResult,
+ message: MessageSource,
+ suggestion: Option<CString>,
+ platform_detail: Option<CString>,
+}
+
+static NUL_BYTE_FALLBACK: &CStr = c"(message contained null byte)";
+
+thread_local! {
+ static LAST_ERROR: RefCell<Option<StoredError>> = const { RefCell::new(None) };
+}
+
+fn error_code_to_result(code: &ErrorCode) -> AdResult {
+ match code {
+ ErrorCode::PermDenied => AdResult::ErrPermDenied,
+ ErrorCode::ElementNotFound => AdResult::ErrElementNotFound,
+ ErrorCode::AppNotFound => AdResult::ErrAppNotFound,
+ ErrorCode::ActionFailed => AdResult::ErrActionFailed,
+ ErrorCode::ActionNotSupported => AdResult::ErrActionNotSupported,
+ ErrorCode::StaleRef => AdResult::ErrStaleRef,
+ ErrorCode::WindowNotFound => AdResult::ErrWindowNotFound,
+ ErrorCode::PlatformNotSupported => AdResult::ErrPlatformNotSupported,
+ ErrorCode::Timeout => AdResult::ErrTimeout,
+ ErrorCode::InvalidArgs => AdResult::ErrInvalidArgs,
+ ErrorCode::NotificationNotFound => AdResult::ErrNotificationNotFound,
+ ErrorCode::Internal => AdResult::ErrInternal,
+ }
+}
+
+pub(crate) fn set_last_error(err: &AdapterError) {
+ let code = error_code_to_result(&err.code);
+ let message = match CString::new(err.message.as_str()) {
+ Ok(cs) => MessageSource::Owned(cs),
+ Err(_) => MessageSource::Static(NUL_BYTE_FALLBACK),
+ };
+ let suggestion = err.suggestion.as_deref().and_then(|s| CString::new(s).ok());
+ let platform_detail = err
+ .platform_detail
+ .as_deref()
+ .and_then(|s| CString::new(s).ok());
+ LAST_ERROR.with(|cell| {
+ *cell.borrow_mut() = Some(StoredError {
+ code,
+ message,
+ suggestion,
+ platform_detail,
+ });
+ });
+}
+
+#[cfg(test)]
+pub(crate) fn clear_last_error() {
+ LAST_ERROR.with(|cell| {
+ *cell.borrow_mut() = None;
+ });
+}
+
+/// Sets the last-error using a `'static CStr` message. Never allocates,
+/// never panics — safe to call from a panic handler.
+pub(crate) fn set_last_error_static(code: AdResult, message: &'static CStr) {
+ LAST_ERROR.with(|cell| {
+ *cell.borrow_mut() = Some(StoredError {
+ code,
+ message: MessageSource::Static(message),
+ suggestion: None,
+ platform_detail: None,
+ });
+ });
+}
+
+pub(crate) fn last_error_code() -> AdResult {
+ LAST_ERROR.with(|cell| {
+ cell.borrow()
+ .as_ref()
+ .map(|e| e.code)
+ .unwrap_or(AdResult::Ok)
+ })
+}
+
+/// Last-error lifetime — errno-style.
+///
+/// The pointer returned by `ad_last_error_message`,
+/// `ad_last_error_suggestion`, and `ad_last_error_platform_detail`
+/// remains valid across any number of subsequent **successful** FFI
+/// calls on the same thread. Only the next FFI call that itself **fails**
+/// (returns a non-`AD_RESULT_OK` code) invalidates the previous pointers.
+///
+/// Consumers can therefore read an error once, cache the pointer, and
+/// keep reading it back across follow-up work that clears or re-fetches
+/// state before handing control to the user.
+///
+/// This matches the POSIX `errno` / `strerror` contract and is scoped
+/// per-thread via thread-local storage — Thread A's last-error never
+/// leaks to Thread B.
+/// Returns the `AdResult` code of the last error on the calling thread,
+/// or `AD_RESULT_OK` if no error has been recorded.
+#[no_mangle]
+pub extern "C" fn ad_last_error_code() -> AdResult {
+ crate::ffi_try::trap_panic(last_error_code)
+}
+
+/// Returns a borrowed C string describing the last error, or null if no
+/// error has been recorded on the calling thread. The pointer remains
+/// valid across any number of subsequent *successful* FFI calls; only
+/// the next failing call overwrites it.
+#[no_mangle]
+pub extern "C" fn ad_last_error_message() -> *const c_char {
+ crate::ffi_try::trap_panic_const_ptr(|| {
+ LAST_ERROR.with(|cell| {
+ cell.borrow()
+ .as_ref()
+ .map(|e| e.message.as_ptr())
+ .unwrap_or(std::ptr::null())
+ })
+ })
+}
+
+/// Returns a borrowed C string with a human-readable suggestion for how
+/// to recover from the last error, or null if the adapter didn't emit
+/// one. Same lifetime rules as `ad_last_error_message`.
+#[no_mangle]
+pub extern "C" fn ad_last_error_suggestion() -> *const c_char {
+ crate::ffi_try::trap_panic_const_ptr(|| {
+ LAST_ERROR.with(|cell| {
+ cell.borrow()
+ .as_ref()
+ .and_then(|e| e.suggestion.as_ref().map(|s| s.as_ptr()))
+ .unwrap_or(std::ptr::null())
+ })
+ })
+}
+
+/// Returns a borrowed C string carrying a platform-specific diagnostic
+/// for the last error (AX error codes, COM HRESULTs, AT-SPI messages,
+/// etc.), or null if the adapter didn't supply one. Same lifetime rules
+/// as `ad_last_error_message`.
+#[no_mangle]
+pub extern "C" fn ad_last_error_platform_detail() -> *const c_char {
+ crate::ffi_try::trap_panic_const_ptr(|| {
+ LAST_ERROR.with(|cell| {
+ cell.borrow()
+ .as_ref()
+ .and_then(|e| e.platform_detail.as_ref().map(|s| s.as_ptr()))
+ .unwrap_or(std::ptr::null())
+ })
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn last_error_message_str() -> Option<String> {
+ LAST_ERROR.with(|cell| cell.borrow().as_ref().map(|e| e.message.to_owned_string()))
+ }
+
+ fn last_error_suggestion_str() -> Option<String> {
+ LAST_ERROR.with(|cell| {
+ cell.borrow().as_ref().and_then(|e| {
+ e.suggestion
+ .as_ref()
+ .map(|s| s.to_string_lossy().into_owned())
+ })
+ })
+ }
+
+ fn last_error_platform_detail_str() -> Option<String> {
+ LAST_ERROR.with(|cell| {
+ cell.borrow().as_ref().and_then(|e| {
+ e.platform_detail
+ .as_ref()
+ .map(|s| s.to_string_lossy().into_owned())
+ })
+ })
+ }
+
+ #[test]
+ fn test_no_error_initially() {
+ clear_last_error();
+ assert!(last_error_message_str().is_none());
+ }
+
+ #[test]
+ fn test_set_and_get_error() {
+ let err = AdapterError::new(ErrorCode::ElementNotFound, "element @e5 gone")
+ .with_suggestion("run snapshot");
+ set_last_error(&err);
+ assert_eq!(last_error_code(), AdResult::ErrElementNotFound);
+ assert_eq!(last_error_message_str().unwrap(), "element @e5 gone");
+ assert_eq!(last_error_suggestion_str().unwrap(), "run snapshot");
+ assert!(last_error_platform_detail_str().is_none());
+ }
+
+ #[test]
+ fn test_clear_error() {
+ let err = AdapterError::internal("oops");
+ set_last_error(&err);
+ clear_last_error();
+ assert!(last_error_message_str().is_none());
+ }
+
+ #[test]
+ fn test_error_isolation_across_threads() {
+ clear_last_error();
+ let err = AdapterError::internal("thread1");
+ set_last_error(&err);
+
+ let handle = std::thread::spawn(|| last_error_message_str().is_none());
+ assert!(handle.join().unwrap(), "other thread should see no error");
+ assert_eq!(last_error_message_str().unwrap(), "thread1");
+ }
+
+ #[test]
+ fn test_interior_nul_falls_back_to_static() {
+ let err = AdapterError::new(ErrorCode::Internal, "before\0after");
+ set_last_error(&err);
+ assert_eq!(
+ last_error_message_str().unwrap(),
+ "(message contained null byte)"
+ );
+ }
+}
diff --git a/crates/ffi/src/ffi_try.rs b/crates/ffi/src/ffi_try.rs
new file mode 100644
index 000000000..2893016db
--- /dev/null
+++ b/crates/ffi/src/ffi_try.rs
@@ -0,0 +1,119 @@
+use crate::error::{set_last_error_static, AdResult};
+use std::ffi::CStr;
+use std::panic::{catch_unwind, AssertUnwindSafe};
+
+static PANIC_MESSAGE: &CStr = c"rust panic in FFI boundary";
+
+/// Runs `body` under a `catch_unwind` boundary. On panic, stashes a
+/// `'static` last-error message and returns `AD_RESULT_ERR_INTERNAL`.
+/// The panic payload is intentionally discarded: allocating inside a
+/// panic handler risks double-panic, and the CLI/SDK caller only needs
+/// to know "a Rust panic escaped the FFI surface" — the full diagnostic
+/// lives in the host crash/trace logs via `tracing`.
+///
+/// The wrapped body must return an `AdResult`. For the (few) FFI
+/// functions that return pointers (`ad_adapter_create`,
+/// `ad_last_error_*`), use `trap_panic_ptr` instead.
+pub(crate) fn trap_panic<F>(body: F) -> AdResult
+where
+ F: FnOnce() -> AdResult,
+{
+ match catch_unwind(AssertUnwindSafe(body)) {
+ Ok(result) => result,
+ Err(_) => {
+ set_last_error_static(AdResult::ErrInternal, PANIC_MESSAGE);
+ AdResult::ErrInternal
+ }
+ }
+}
+
+/// Pointer-returning variant for `*mut T`: on panic, sets a `'static`
+/// last-error and returns null. Used by `ad_adapter_create`.
+pub(crate) fn trap_panic_ptr<T, F>(body: F) -> *mut T
+where
+ F: FnOnce() -> *mut T,
+{
+ match catch_unwind(AssertUnwindSafe(body)) {
+ Ok(ptr) => ptr,
+ Err(_) => {
+ set_last_error_static(AdResult::ErrInternal, PANIC_MESSAGE);
+ std::ptr::null_mut()
+ }
+ }
+}
+
+/// Pointer-returning variant for `*const T`: on panic, sets a `'static`
+/// last-error and returns null. Used by the `ad_last_error_*` readers.
+pub(crate) fn trap_panic_const_ptr<T, F>(body: F) -> *const T
+where
+ F: FnOnce() -> *const T,
+{
+ match catch_unwind(AssertUnwindSafe(body)) {
+ Ok(ptr) => ptr,
+ Err(_) => {
+ set_last_error_static(AdResult::ErrInternal, PANIC_MESSAGE);
+ std::ptr::null()
+ }
+ }
+}
+
+/// Void-return variant: on panic, sets a `'static` last-error and
+/// swallows. Used by `ad_*_destroy`, `ad_free_*` — functions where the
+/// C contract has no channel to signal failure. The caller can still
+/// inspect `ad_last_error_*` if they care.
+pub(crate) fn trap_panic_void<F>(body: F)
+where
+ F: FnOnce(),
+{
+ if catch_unwind(AssertUnwindSafe(body)).is_err() {
+ set_last_error_static(AdResult::ErrInternal, PANIC_MESSAGE);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_happy_path_passes_through() {
+ let r = trap_panic(|| AdResult::Ok);
+ assert_eq!(r, AdResult::Ok);
+ }
+
+ #[test]
+ fn test_error_return_passes_through() {
+ let r = trap_panic(|| AdResult::ErrInvalidArgs);
+ assert_eq!(r, AdResult::ErrInvalidArgs);
+ }
+
+ #[test]
+ fn test_panic_is_caught_and_returns_internal() {
+ let r = trap_panic(|| -> AdResult { panic!("synthetic panic") });
+ assert_eq!(r, AdResult::ErrInternal);
+ }
+
+ #[test]
+ fn test_panic_sets_static_last_error() {
+ crate::error::clear_last_error();
+ let _ = trap_panic(|| -> AdResult { panic!("synthetic panic") });
+ assert_eq!(crate::error::last_error_code(), AdResult::ErrInternal);
+ }
+
+ #[test]
+ fn test_two_sequential_panics_do_not_leak() {
+ let _ = trap_panic(|| -> AdResult { panic!("first") });
+ let r = trap_panic(|| -> AdResult { panic!("second") });
+ assert_eq!(r, AdResult::ErrInternal);
+ }
+
+ #[test]
+ fn test_pointer_panic_returns_null() {
+ let p: *mut u8 = trap_panic_ptr(|| -> *mut u8 { panic!("boom") });
+ assert!(p.is_null());
+ }
+
+ #[test]
+ fn test_void_panic_is_swallowed() {
+ trap_panic_void(|| panic!("boom"));
+ }
+}
diff --git a/crates/ffi/src/input/clipboard.rs b/crates/ffi/src/input/clipboard.rs
new file mode 100644
index 000000000..8fc01e25f
--- /dev/null
+++ b/crates/ffi/src/input/clipboard.rs
@@ -0,0 +1,119 @@
+use crate::convert::string::{c_to_string, free_c_string, string_to_c};
+use crate::error::{self, AdResult};
+use crate::ffi_try::{trap_panic, trap_panic_void};
+use crate::AdAdapter;
+use std::os::raw::c_char;
+
+/// Reads the current clipboard text and writes an owned C string into
+/// `*out`. The caller must free the returned pointer with
+/// `ad_free_string`. On error `*out` is left null.
+///
+/// # Safety
+/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+/// `out` must be a non-null writable `*mut *mut c_char`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_get_clipboard(
+ adapter: *const AdAdapter,
+ out: *mut *mut c_char,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ crate::pointer_guard::guard_non_null!(out, c"out is null");
+ *out = std::ptr::null_mut();
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ let adapter = &*adapter;
+ match adapter.inner.get_clipboard() {
+ Ok(text) => {
+ let c = string_to_c(&text);
+ if c.is_null() {
+ error::set_last_error(
+ &agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::Internal,
+ "clipboard text contains an interior NUL and cannot be represented as a C string",
+ ),
+ );
+ return AdResult::ErrInternal;
+ }
+ *out = c;
+ AdResult::Ok
+ }
+ Err(e) => {
+ error::set_last_error(&e);
+ error::last_error_code()
+ }
+ }
+ })
+}
+
+/// Writes UTF-8 `text` to the clipboard. Null or non-UTF-8 input returns
+/// `AD_RESULT_ERR_INVALID_ARGS` with a diagnostic last-error.
+///
+/// # Safety
+/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+/// `text` must be a non-null, NUL-terminated UTF-8 C string.
+#[no_mangle]
+pub unsafe extern "C" fn ad_set_clipboard(
+ adapter: *const AdAdapter,
+ text: *const c_char,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ let adapter = &*adapter;
+ let text = match c_to_string(text) {
+ Some(s) => s,
+ None => {
+ error::set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "text is null or invalid UTF-8",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+ match adapter.inner.set_clipboard(&text) {
+ Ok(()) => AdResult::Ok,
+ Err(e) => {
+ error::set_last_error(&e);
+ error::last_error_code()
+ }
+ }
+ })
+}
+
+/// Clears the clipboard.
+///
+/// # Safety
+/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_clear_clipboard(adapter: *const AdAdapter) -> AdResult {
+ trap_panic(|| unsafe {
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ let adapter = &*adapter;
+ match adapter.inner.clear_clipboard() {
+ Ok(()) => AdResult::Ok,
+ Err(e) => {
+ error::set_last_error(&e);
+ error::last_error_code()
+ }
+ }
+ })
+}
+
+/// Frees a C string previously returned by `ad_get_clipboard` or any
+/// other FFI call documented as allocating a C string for the caller.
+/// Null-tolerant — safe to call on `NULL`. Double-free is undefined.
+///
+/// # Safety
+/// `s` must be null or a pointer previously handed out by this crate.
+/// After this call the pointer is invalid and must not be used.
+#[no_mangle]
+pub unsafe extern "C" fn ad_free_string(s: *mut c_char) {
+ trap_panic_void(|| unsafe { free_c_string(s) })
+}
diff --git a/crates/ffi/src/input/drag.rs b/crates/ffi/src/input/drag.rs
new file mode 100644
index 000000000..ae808c66d
--- /dev/null
+++ b/crates/ffi/src/input/drag.rs
@@ -0,0 +1,107 @@
+use crate::error::{self, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::types::AdDragParams;
+use crate::AdAdapter;
+use agent_desktop_core::action::{DragParams as CoreDragParams, Point as CorePoint};
+
+/// Synthesizes a mouse drag from `params.from` to `params.to`. When
+/// `params.duration_ms` is zero the drag is instantaneous; a non-zero
+/// value asks the platform adapter to interpolate.
+///
+/// # Safety
+/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+/// `params` must be a non-null pointer to a valid `AdDragParams`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_drag(
+ adapter: *const AdAdapter,
+ params: *const AdDragParams,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ crate::pointer_guard::guard_non_null!(params, c"params is null");
+ let adapter = &*adapter;
+ let p = &*params;
+ let core_params = CoreDragParams {
+ from: CorePoint {
+ x: p.from.x,
+ y: p.from.y,
+ },
+ to: CorePoint {
+ x: p.to.x,
+ y: p.to.y,
+ },
+ duration_ms: if p.duration_ms == 0 {
+ None
+ } else {
+ Some(p.duration_ms)
+ },
+ };
+ match adapter.inner.drag(core_params) {
+ Ok(()) => AdResult::Ok,
+ Err(e) => {
+ error::set_last_error(&e);
+ error::last_error_code()
+ }
+ }
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::types::AdPoint;
+
+ #[test]
+ fn test_drag_zero_duration_becomes_none() {
+ let p = AdDragParams {
+ from: AdPoint { x: 0.0, y: 0.0 },
+ to: AdPoint { x: 100.0, y: 200.0 },
+ duration_ms: 0,
+ };
+ let core = CoreDragParams {
+ from: CorePoint {
+ x: p.from.x,
+ y: p.from.y,
+ },
+ to: CorePoint {
+ x: p.to.x,
+ y: p.to.y,
+ },
+ duration_ms: if p.duration_ms == 0 {
+ None
+ } else {
+ Some(p.duration_ms)
+ },
+ };
+ assert!(core.duration_ms.is_none());
+ assert_eq!(core.to.x, 100.0);
+ }
+
+ #[test]
+ fn test_drag_nonzero_duration() {
+ let p = AdDragParams {
+ from: AdPoint { x: 0.0, y: 0.0 },
+ to: AdPoint { x: 50.0, y: 50.0 },
+ duration_ms: 500,
+ };
+ let core = CoreDragParams {
+ from: CorePoint {
+ x: p.from.x,
+ y: p.from.y,
+ },
+ to: CorePoint {
+ x: p.to.x,
+ y: p.to.y,
+ },
+ duration_ms: if p.duration_ms == 0 {
+ None
+ } else {
+ Some(p.duration_ms)
+ },
+ };
+ assert_eq!(core.duration_ms, Some(500));
+ }
+}
diff --git a/crates/ffi/src/input/mod.rs b/crates/ffi/src/input/mod.rs
new file mode 100644
index 000000000..c2ef5e686
--- /dev/null
+++ b/crates/ffi/src/input/mod.rs
@@ -0,0 +1,3 @@
+pub(crate) mod clipboard;
+pub(crate) mod drag;
+pub(crate) mod mouse;
diff --git a/crates/ffi/src/input/mouse.rs b/crates/ffi/src/input/mouse.rs
new file mode 100644
index 000000000..888ecfedc
--- /dev/null
+++ b/crates/ffi/src/input/mouse.rs
@@ -0,0 +1,136 @@
+use crate::error::{self, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::types::{AdMouseButton, AdMouseEvent, AdMouseEventKind};
+use crate::AdAdapter;
+use agent_desktop_core::action::{
+ MouseButton as CoreMouseButton, MouseEvent as CoreMouseEvent,
+ MouseEventKind as CoreMouseEventKind, Point as CorePoint,
+};
+
+pub(crate) fn mouse_button_from_c(b: AdMouseButton) -> CoreMouseButton {
+ match b {
+ AdMouseButton::Left => CoreMouseButton::Left,
+ AdMouseButton::Right => CoreMouseButton::Right,
+ AdMouseButton::Middle => CoreMouseButton::Middle,
+ }
+}
+
+/// Dispatches a mouse event (move / down / up / click) at the given
+/// screen point. Click count is only consulted when `event.kind` is
+/// `CLICK` (e.g., `click_count == 2` for a double-click).
+///
+/// # Safety
+/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.
+/// `event` must be a non-null pointer to a valid `AdMouseEvent`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_mouse_event(
+ adapter: *const AdAdapter,
+ event: *const AdMouseEvent,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ crate::pointer_guard::guard_non_null!(event, c"event is null");
+ let adapter = &*adapter;
+ let ev = &*event;
+ let validated_button = match AdMouseButton::from_c(ev.button) {
+ Some(b) => b,
+ None => {
+ error::set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "invalid mouse button discriminant",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+ let validated_kind = match AdMouseEventKind::from_c(ev.kind) {
+ Some(k) => k,
+ None => {
+ error::set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "invalid mouse event kind discriminant",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+ let point = CorePoint {
+ x: ev.point.x,
+ y: ev.point.y,
+ };
+ let button = mouse_button_from_c(validated_button);
+ let kind = match validated_kind {
+ AdMouseEventKind::Move => CoreMouseEventKind::Move,
+ AdMouseEventKind::Down => CoreMouseEventKind::Down,
+ AdMouseEventKind::Up => CoreMouseEventKind::Up,
+ AdMouseEventKind::Click => CoreMouseEventKind::Click {
+ count: ev.click_count,
+ },
+ };
+ let core_event = CoreMouseEvent {
+ kind,
+ point,
+ button,
+ };
+ match adapter.inner.mouse_event(core_event) {
+ Ok(()) => AdResult::Ok,
+ Err(e) => {
+ error::set_last_error(&e);
+ error::last_error_code()
+ }
+ }
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::types::AdPoint;
+
+ #[test]
+ fn test_mouse_button_mapping() {
+ assert!(matches!(
+ mouse_button_from_c(AdMouseButton::Left),
+ CoreMouseButton::Left
+ ));
+ assert!(matches!(
+ mouse_button_from_c(AdMouseButton::Right),
+ CoreMouseButton::Right
+ ));
+ assert!(matches!(
+ mouse_button_from_c(AdMouseButton::Middle),
+ CoreMouseButton::Middle
+ ));
+ }
+
+ #[test]
+ fn valid_discriminants_convert_to_typed_enums() {
+ let ev = AdMouseEvent {
+ kind: AdMouseEventKind::Click as i32,
+ point: AdPoint { x: 10.0, y: 20.0 },
+ button: AdMouseButton::Left as i32,
+ click_count: 2,
+ };
+ assert!(matches!(
+ AdMouseButton::from_c(ev.button),
+ Some(AdMouseButton::Left)
+ ));
+ assert!(matches!(
+ AdMouseEventKind::from_c(ev.kind),
+ Some(AdMouseEventKind::Click)
+ ));
+ }
+
+ #[test]
+ fn invalid_discriminants_reject_without_ub() {
+ let ev = AdMouseEvent {
+ kind: 999,
+ point: AdPoint { x: 0.0, y: 0.0 },
+ button: -5,
+ click_count: 0,
+ };
+ assert!(AdMouseButton::from_c(ev.button).is_none());
+ assert!(AdMouseEventKind::from_c(ev.kind).is_none());
+ }
+}
diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rs
new file mode 100644
index 000000000..9c374a2a8
--- /dev/null
+++ b/crates/ffi/src/lib.rs
@@ -0,0 +1,99 @@
+//! # agent-desktop FFI
+//!
+//! C-ABI surface over `PlatformAdapter`. Exposes
+//! `libagent_desktop_ffi.{dylib,so,dll}` to Python / Swift / Go / Node /
+//! C++ consumers.
+//!
+//! ## ⚠ Thread safety (macOS)
+//!
+//! Every adapter-touching FFI entry must be invoked on the process's
+//! main thread. The guard runs at **runtime in every build profile**:
+//! a worker-thread call returns `AD_RESULT_ERR_INTERNAL` with a
+//! `'static` diagnostic message — no silent UB even under
+//! `--profile release-ffi`.
+//!
+//! Operations exempt from the guard (safe from any thread):
+//!
+//! - `ad_adapter_create` / `ad_adapter_destroy`
+//! - `ad_last_error_*` readers
+//! - `ad_check_permissions` (process-wide query, no AX/Cocoa state)
+//! - All `ad_*_list_{count,get,free}` accessors and
+//! `ad_image_buffer_*` accessors
+//! - `ad_release_window_fields`, `ad_free_handle`, `ad_free_tree`,
+//! `ad_free_action_result`, `ad_free_string`
+//!
+//! ## Build profile
+//!
+//! The cdylib must be built with the workspace's `release-ffi` profile:
+//!
+//! ```text
+//! cargo build --profile release-ffi -p agent-desktop-ffi
+//! ```
+//!
+//! The workspace `release` profile keeps `panic = "abort"` to hold the
+//! CLI under its size budget; the cdylib needs `panic = "unwind"` so the
+//! `trap_panic` boundary actually catches. Both profiles coexist.
+//!
+//! ## Error model
+//!
+//! Every `AdResult`-returning fn sets thread-local last-error details on
+//! failure. The pointer returned by `ad_last_error_message()` survives
+//! any number of subsequent successful calls on the same thread; only
+//! the next *failing* call rotates it. Matches POSIX `errno` semantics.
+
+pub(crate) mod actions;
+pub(crate) mod adapter;
+pub(crate) mod apps;
+pub(crate) mod convert;
+pub(crate) mod enum_validation;
+pub mod error;
+pub(crate) mod ffi_try;
+pub(crate) mod input;
+pub(crate) mod main_thread;
+pub(crate) mod notifications;
+pub(crate) mod observation;
+pub(crate) mod pointer_guard;
+pub(crate) mod screenshot;
+pub(crate) mod surfaces;
+pub(crate) mod tree;
+pub mod types;
+pub(crate) mod windows;
+
+pub use adapter::AdAdapter;
+pub use error::AdResult;
+pub use types::action::AdAction;
+pub use types::action_kind::AdActionKind;
+pub use types::action_result::AdActionResult;
+pub use types::app_info::AdAppInfo;
+pub use types::app_list::AdAppList;
+pub use types::direction::AdDirection;
+pub use types::drag_params::AdDragParams;
+pub use types::element_state::AdElementState;
+pub use types::find_query::AdFindQuery;
+pub use types::image_buffer::AdImageBuffer;
+pub use types::image_format::AdImageFormat;
+pub use types::key_combo::AdKeyCombo;
+pub use types::modifier::AdModifier;
+pub use types::mouse_button::AdMouseButton;
+pub use types::mouse_event::AdMouseEvent;
+pub use types::mouse_event_kind::AdMouseEventKind;
+pub use types::native_handle::AdNativeHandle;
+pub use types::node::AdNode;
+pub use types::node_tree::AdNodeTree;
+pub use types::notification_filter::AdNotificationFilter;
+pub use types::notification_info::AdNotificationInfo;
+pub use types::notification_list::AdNotificationList;
+pub use types::point::AdPoint;
+pub use types::rect::AdRect;
+pub use types::ref_entry::AdRefEntry;
+pub use types::screenshot_kind::AdScreenshotKind;
+pub use types::screenshot_target::AdScreenshotTarget;
+pub use types::scroll_params::AdScrollParams;
+pub use types::snapshot_surface::AdSnapshotSurface;
+pub use types::surface_info::AdSurfaceInfo;
+pub use types::surface_list::AdSurfaceList;
+pub use types::tree_options::AdTreeOptions;
+pub use types::window_info::AdWindowInfo;
+pub use types::window_list::AdWindowList;
+pub use types::window_op::AdWindowOp;
+pub use types::window_op_kind::AdWindowOpKind;
diff --git a/crates/ffi/src/main_thread.rs b/crates/ffi/src/main_thread.rs
new file mode 100644
index 000000000..5c04c4e23
--- /dev/null
+++ b/crates/ffi/src/main_thread.rs
@@ -0,0 +1,70 @@
+//! Main-thread enforcement for macOS-sensitive FFI entrypoints.
+//!
+//! macOS accessibility (AX) and Cocoa APIs must run on the process's
+//! main thread. Off-thread calls silently corrupt state or crash, and
+//! the crash looks like memory corruption from the consumer side —
+//! impossible to debug from a Python / Node / Swift host.
+//!
+//! `require_main_thread()` performs a **runtime** check (always, in
+//! every build profile) and returns `AD_RESULT_ERR_INTERNAL` with a
+//! `'static` diagnostic last-error when a worker-thread call is
+//! detected. The check compiles away on non-macOS targets — AT-SPI
+//! and UIA don't impose the same affinity rule.
+//!
+//! Exempt from the rule: `ad_adapter_create`, `ad_adapter_destroy`,
+//! `ad_last_error_*`, and the entire `ad_free_*` / `ad_*_list_free` /
+//! `ad_image_buffer_free` / `ad_release_window_fields` / `ad_free_handle`
+//! / `ad_free_string` / `ad_free_action_result` / `ad_free_tree` family.
+//! Those paths touch no AX/Cocoa state and are safe from any thread.
+
+use crate::error::{set_last_error_static, AdResult};
+use std::ffi::CStr;
+
+static OFF_MAIN_THREAD_MESSAGE: &CStr =
+ c"agent_desktop FFI entry called off the main thread (macOS requires main-thread AX/Cocoa calls)";
+
+#[cfg(target_os = "macos")]
+pub(crate) fn is_main_thread() -> bool {
+ unsafe { libc::pthread_main_np() != 0 }
+}
+
+#[cfg(not(target_os = "macos"))]
+pub(crate) fn is_main_thread() -> bool {
+ true
+}
+
+/// Fail-closed runtime main-thread check. Returns
+/// `Ok(())` on the main thread (always, on non-macOS). Returns
+/// `Err(AdResult::ErrInternal)` on a worker thread with the last-error
+/// slot populated with a `'static` diagnostic message.
+///
+/// Unlike a `debug_assert!`, this variant still fires in
+/// `--profile release-ffi` and other optimized builds.
+#[inline]
+pub(crate) fn require_main_thread() -> Result<(), AdResult> {
+ if is_main_thread() {
+ Ok(())
+ } else {
+ set_last_error_static(AdResult::ErrInternal, OFF_MAIN_THREAD_MESSAGE);
+ Err(AdResult::ErrInternal)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn is_main_thread_call_is_always_safe_even_on_workers() {
+ let _ = is_main_thread();
+ }
+
+ #[test]
+ fn require_main_thread_returns_err_on_worker() {
+ let outcome = std::thread::spawn(require_main_thread).join().unwrap();
+ #[cfg(target_os = "macos")]
+ assert!(matches!(outcome, Err(AdResult::ErrInternal)));
+ #[cfg(not(target_os = "macos"))]
+ assert!(outcome.is_ok());
+ }
+}
diff --git a/crates/ffi/src/notifications/action.rs b/crates/ffi/src/notifications/action.rs
new file mode 100644
index 000000000..29bdef2a6
--- /dev/null
+++ b/crates/ffi/src/notifications/action.rs
@@ -0,0 +1,88 @@
+use crate::actions::result::action_result_to_c;
+use crate::convert::string::{c_to_string, decode_optional_filter};
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::types::AdActionResult;
+use crate::AdAdapter;
+use agent_desktop_core::notification::NotificationIdentity;
+use std::os::raw::c_char;
+
+/// Triggers the named action on the notification at `index`. Typical
+/// action names are those reported in `AdNotificationInfo.actions`
+/// (e.g. `"Reply"`, `"Open"`).
+///
+/// ## Identity / reorder safety
+///
+/// Notification Center reindexes entries on every listing — a new
+/// notification arriving (or another one being dismissed) shifts which
+/// notification sits at any given `index`. Calling this function with
+/// an index obtained from a prior `ad_list_notifications` can therefore
+/// press the action button on a different notification than the host
+/// intended.
+///
+/// `expected_app` and `expected_title` let the host pin the targeted
+/// notification to an observed fingerprint. If either pointer is
+/// non-null, the row currently at `index` must match that field or the
+/// call fails closed with `AD_RESULT_ERR_NOTIFICATION_NOT_FOUND`. Both
+/// null preserves the legacy index-only behavior for hosts that do
+/// their own reconciliation.
+///
+/// # Safety
+/// `adapter` must be valid. `action_name` must be a non-null UTF-8
+/// C string. `expected_app` and `expected_title` must each be null
+/// or a NUL-terminated UTF-8 C string. Invalid UTF-8 in either field
+/// is rejected with `AD_RESULT_ERR_INVALID_ARGS` rather than silently
+/// treated as "no fingerprint". `out` must be a valid writable
+/// `*mut AdActionResult`; on error it is zero-initialized.
+#[no_mangle]
+pub unsafe extern "C" fn ad_notification_action(
+ adapter: *const AdAdapter,
+ index: u32,
+ expected_app: *const c_char,
+ expected_title: *const c_char,
+ action_name: *const c_char,
+ out: *mut AdActionResult,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ crate::pointer_guard::guard_non_null!(out, c"out is null");
+ *out = std::mem::zeroed();
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ let adapter = &*adapter;
+ let action = match c_to_string(action_name) {
+ Some(s) => s,
+ None => {
+ set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "action_name is null or invalid UTF-8",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+ let expected_app = decode_optional_filter!(expected_app, "expected_app");
+ let expected_title = decode_optional_filter!(expected_title, "expected_title");
+ let identity = if expected_app.is_some() || expected_title.is_some() {
+ Some(NotificationIdentity {
+ expected_app,
+ expected_title,
+ })
+ } else {
+ None
+ };
+ match adapter
+ .inner
+ .notification_action(index as usize, identity.as_ref(), &action)
+ {
+ Ok(result) => {
+ *out = action_result_to_c(&result);
+ AdResult::Ok
+ }
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ }
+ })
+}
diff --git a/crates/ffi/src/notifications/dismiss.rs b/crates/ffi/src/notifications/dismiss.rs
new file mode 100644
index 000000000..81269a6b6
--- /dev/null
+++ b/crates/ffi/src/notifications/dismiss.rs
@@ -0,0 +1,39 @@
+use crate::convert::string::decode_optional_filter;
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::AdAdapter;
+use std::os::raw::c_char;
+
+/// Dismisses the notification at `index`. Indexes are only valid within
+/// the response to the most recent `ad_list_notifications` call on this
+/// thread — the adapter re-queries internally, so dismissing by a stale
+/// index returns `AD_RESULT_ERR_NOTIFICATION_NOT_FOUND`.
+///
+/// # Safety
+/// `adapter` must be valid. `app_filter` may be null.
+#[no_mangle]
+pub unsafe extern "C" fn ad_dismiss_notification(
+ adapter: *const AdAdapter,
+ index: u32,
+ app_filter: *const c_char,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ let adapter = &*adapter;
+ let filter = decode_optional_filter!(app_filter, "app_filter");
+ let filter_ref = filter.as_deref();
+ match adapter
+ .inner
+ .dismiss_notification(index as usize, filter_ref)
+ {
+ Ok(_) => AdResult::Ok,
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ }
+ })
+}
diff --git a/crates/ffi/src/notifications/dismiss_all.rs b/crates/ffi/src/notifications/dismiss_all.rs
new file mode 100644
index 000000000..c26d72f58
--- /dev/null
+++ b/crates/ffi/src/notifications/dismiss_all.rs
@@ -0,0 +1,98 @@
+use crate::convert::notification::notification_info_to_c;
+use crate::convert::string::decode_optional_filter;
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::notifications::list::ad_notification_list_free;
+use crate::types::{AdNotificationInfo, AdNotificationList};
+use crate::AdAdapter;
+use std::os::raw::c_char;
+use std::ptr;
+
+/// Dismisses every notification matching `app_filter` (null = all apps).
+///
+/// Returns two lists: `dismissed_out` carries the notifications that
+/// were successfully dismissed; `failed_out` holds error strings for
+/// notifications where the platform rejected the dismiss. Partial
+/// failures do not set last-error — inspect `failed_out` for details.
+///
+/// `failed_out` uses the notification-list handle to stay ABI-consistent
+/// with the other list-returning FFI calls; the entries carry the
+/// original notification shape with `body` populated by the platform
+/// error message.
+///
+/// # Safety
+/// `adapter` must be valid. `app_filter` may be null. `dismissed_out`
+/// and `failed_out` must both be valid writable `*mut *mut AdNotificationList`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_dismiss_all_notifications(
+ adapter: *const AdAdapter,
+ app_filter: *const c_char,
+ dismissed_out: *mut *mut AdNotificationList,
+ failed_out: *mut *mut AdNotificationList,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ crate::pointer_guard::guard_non_null!(dismissed_out, c"dismissed_out is null");
+ crate::pointer_guard::guard_non_null!(failed_out, c"failed_out is null");
+ *dismissed_out = ptr::null_mut();
+ *failed_out = ptr::null_mut();
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ let adapter = &*adapter;
+ let filter = decode_optional_filter!(app_filter, "app_filter");
+ let filter_ref = filter.as_deref();
+ match adapter.inner.dismiss_all_notifications(filter_ref) {
+ Ok((dismissed, failed_messages)) => {
+ let dismissed_items: Vec<AdNotificationInfo> =
+ dismissed.iter().map(notification_info_to_c).collect();
+ let dismissed_list = Box::new(AdNotificationList {
+ items: dismissed_items.into_boxed_slice(),
+ });
+ *dismissed_out = Box::into_raw(dismissed_list);
+
+ let failed_items: Vec<AdNotificationInfo> = failed_messages
+ .into_iter()
+ .enumerate()
+ .map(|(i, msg)| {
+ let info = agent_desktop_core::notification::NotificationInfo {
+ index: i,
+ app_name: String::new(),
+ title: String::from("dismiss failed"),
+ body: Some(msg),
+ actions: Vec::new(),
+ };
+ notification_info_to_c(&info)
+ })
+ .collect();
+ let failed_list = Box::new(AdNotificationList {
+ items: failed_items.into_boxed_slice(),
+ });
+ *failed_out = Box::into_raw(failed_list);
+ AdResult::Ok
+ }
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ }
+ })
+}
+
+/// Convenience wrapper: free both lists returned by
+/// `ad_dismiss_all_notifications`. Equivalent to calling
+/// `ad_notification_list_free` on each; provided for symmetry.
+///
+/// # Safety
+/// Both arguments must be null or pointers from
+/// `ad_dismiss_all_notifications`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_dismiss_all_notifications_free(
+ dismissed: *mut AdNotificationList,
+ failed: *mut AdNotificationList,
+) {
+ unsafe {
+ ad_notification_list_free(dismissed);
+ ad_notification_list_free(failed);
+ }
+}
diff --git a/crates/ffi/src/notifications/filter.rs b/crates/ffi/src/notifications/filter.rs
new file mode 100644
index 000000000..6c3b72a0d
--- /dev/null
+++ b/crates/ffi/src/notifications/filter.rs
@@ -0,0 +1,39 @@
+use crate::convert::string::try_c_to_string;
+use crate::types::AdNotificationFilter;
+use agent_desktop_core::error::{AdapterError, ErrorCode};
+use agent_desktop_core::notification::NotificationFilter;
+
+/// Converts a C `AdNotificationFilter` into the core filter type.
+///
+/// - `null` pointer → `Ok(NotificationFilter::default())` (no filter).
+/// - `has_limit == false` → the numeric limit is cleared regardless of
+/// `limit` contents.
+/// - Non-null `app` / `text` with invalid UTF-8 → `Err` rather than
+/// silently dropping the filter (which would widen operations like
+/// `ad_dismiss_all_notifications` to every app on the system).
+///
+/// # Safety
+/// `filter` must be null or point to a valid `AdNotificationFilter`.
+/// The embedded C strings must outlive this call.
+pub(crate) unsafe fn filter_from_c(
+ filter: *const AdNotificationFilter,
+) -> Result<NotificationFilter, AdapterError> {
+ if filter.is_null() {
+ return Ok(NotificationFilter::default());
+ }
+ let f: &AdNotificationFilter = unsafe { &*filter };
+ let app = unsafe { try_c_to_string(f.app) }
+ .map_err(|()| AdapterError::new(ErrorCode::InvalidArgs, "filter.app is not valid UTF-8"))?;
+ let text = unsafe { try_c_to_string(f.text) }.map_err(|()| {
+ AdapterError::new(ErrorCode::InvalidArgs, "filter.text is not valid UTF-8")
+ })?;
+ Ok(NotificationFilter {
+ app,
+ text,
+ limit: if f.has_limit {
+ Some(f.limit as usize)
+ } else {
+ None
+ },
+ })
+}
diff --git a/crates/ffi/src/notifications/list.rs b/crates/ffi/src/notifications/list.rs
new file mode 100644
index 000000000..0d7aa75ab
--- /dev/null
+++ b/crates/ffi/src/notifications/list.rs
@@ -0,0 +1,104 @@
+use crate::convert::notification::{free_notification_info_fields, notification_info_to_c};
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::{trap_panic, trap_panic_void};
+use crate::notifications::filter::filter_from_c;
+use crate::types::{AdNotificationFilter, AdNotificationInfo, AdNotificationList};
+use crate::AdAdapter;
+use std::ptr;
+
+/// Lists the notifications currently on-screen.
+///
+/// Notification indexes are only stable within a single list response.
+/// Pass them straight to `ad_dismiss_notification` /
+/// `ad_notification_action` without caching across ticks — the adapter
+/// re-queries Notification Center internally on every call.
+///
+/// # Safety
+/// `adapter` must be valid. `filter` may be null. `out` must be a valid
+/// writable `*mut *mut AdNotificationList`. On success `*out` is a
+/// non-null handle freed with `ad_notification_list_free`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_list_notifications(
+ adapter: *const AdAdapter,
+ filter: *const AdNotificationFilter,
+ out: *mut *mut AdNotificationList,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ crate::pointer_guard::guard_non_null!(out, c"out is null");
+ *out = ptr::null_mut();
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ let adapter = &*adapter;
+ let core_filter = match filter_from_c(filter) {
+ Ok(f) => f,
+ Err(e) => {
+ set_last_error(&e);
+ return crate::error::last_error_code();
+ }
+ };
+ match adapter.inner.list_notifications(&core_filter) {
+ Ok(notifications) => {
+ let items: Vec<AdNotificationInfo> =
+ notifications.iter().map(notification_info_to_c).collect();
+ let list = Box::new(AdNotificationList {
+ items: items.into_boxed_slice(),
+ });
+ *out = Box::into_raw(list);
+ AdResult::Ok
+ }
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ }
+ })
+}
+
+/// # Safety
+/// `list` must be null or a pointer returned by `ad_list_notifications`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_notification_list_count(list: *const AdNotificationList) -> u32 {
+ if list.is_null() {
+ return 0;
+ }
+ let list_ref: &AdNotificationList = unsafe { &*list };
+ list_ref.items.len() as u32
+}
+
+/// Borrows a notification entry. Null if `index` is out of range.
+///
+/// # Safety
+/// `list` must be null or a pointer returned by `ad_list_notifications`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_notification_list_get(
+ list: *const AdNotificationList,
+ index: u32,
+) -> *const AdNotificationInfo {
+ if list.is_null() {
+ return ptr::null();
+ }
+ let list_ref: &AdNotificationList = unsafe { &*list };
+ match list_ref.items.get(index as usize) {
+ Some(item) => item as *const AdNotificationInfo,
+ None => ptr::null(),
+ }
+}
+
+/// Frees the list and each entry's interior strings.
+///
+/// # Safety
+/// `list` must be null or a pointer returned by `ad_list_notifications`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_notification_list_free(list: *mut AdNotificationList) {
+ trap_panic_void(|| unsafe {
+ if list.is_null() {
+ return;
+ }
+ let mut list = Box::from_raw(list);
+ for item in list.items.iter_mut() {
+ free_notification_info_fields(item);
+ }
+ })
+}
diff --git a/crates/ffi/src/notifications/mod.rs b/crates/ffi/src/notifications/mod.rs
new file mode 100644
index 000000000..4468e2987
--- /dev/null
+++ b/crates/ffi/src/notifications/mod.rs
@@ -0,0 +1,5 @@
+pub(crate) mod action;
+pub(crate) mod dismiss;
+pub(crate) mod dismiss_all;
+pub(crate) mod filter;
+pub(crate) mod list;
diff --git a/crates/ffi/src/observation/find.rs b/crates/ffi/src/observation/find.rs
new file mode 100644
index 000000000..2f24459f5
--- /dev/null
+++ b/crates/ffi/src/observation/find.rs
@@ -0,0 +1,116 @@
+use crate::convert::string::decode_optional_filter;
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::observation::walk::find_first_match;
+use crate::types::{AdFindQuery, AdNativeHandle, AdWindowInfo};
+use crate::AdAdapter;
+use agent_desktop_core::adapter::{SnapshotSurface, TreeOptions};
+use agent_desktop_core::refs::RefEntry;
+
+/// Finds the first element in `win`'s accessibility tree matching the
+/// query and resolves it to an opaque `AdNativeHandle`. The caller owns
+/// the handle and must release it with `ad_free_handle(adapter, handle)`
+/// once done.
+///
+/// Matching is DFS order, first hit wins. All query fields are optional
+/// (null = "don't care") and case-insensitive substring matches:
+/// - `role` against `AccessibilityNode.role`
+/// - `name_substring` against `AccessibilityNode.name`
+/// - `value_substring` against `AccessibilityNode.value`
+///
+/// # Safety
+/// `adapter`, `win`, and `query` must be valid pointers. `out_handle`
+/// must be a valid writable `*mut AdNativeHandle`. On
+/// `AD_RESULT_ERR_ELEMENT_NOT_FOUND` the out-handle is zero-initialized.
+#[no_mangle]
+pub unsafe extern "C" fn ad_find(
+ adapter: *const AdAdapter,
+ win: *const AdWindowInfo,
+ query: *const AdFindQuery,
+ out_handle: *mut AdNativeHandle,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ crate::pointer_guard::guard_non_null!(out_handle, c"out_handle is null");
+ (*out_handle).ptr = std::ptr::null();
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ crate::pointer_guard::guard_non_null!(win, c"win is null");
+ crate::pointer_guard::guard_non_null!(query, c"query is null");
+ let adapter = &*adapter;
+ let core_win = match crate::windows::ad_window_to_core(&*win) {
+ Ok(w) => w,
+ Err(e) => {
+ set_last_error(&e);
+ return crate::error::last_error_code();
+ }
+ };
+ let q = &*query;
+ let role_filter = decode_optional_filter!(q.role, "query.role");
+ let name_filter = decode_optional_filter!(q.name_substring, "query.name_substring");
+ let value_filter = decode_optional_filter!(q.value_substring, "query.value_substring");
+
+ // include_bounds must be true: the resolver disambiguates
+ // duplicate-label siblings using bounds_hash, and without the
+ // bounds field populated on the matched node we would fall
+ // back to role+name alone and drift to the wrong element.
+ let tree = match adapter.inner.get_tree(
+ &core_win,
+ &TreeOptions {
+ max_depth: 50,
+ include_bounds: true,
+ interactive_only: false,
+ compact: false,
+ surface: SnapshotSurface::Window,
+ skeleton: false,
+ },
+ ) {
+ Ok(t) => t,
+ Err(e) => {
+ set_last_error(&e);
+ return crate::error::last_error_code();
+ }
+ };
+
+ let matched = match find_first_match(
+ &tree,
+ role_filter.as_deref(),
+ name_filter.as_deref(),
+ value_filter.as_deref(),
+ ) {
+ Some(n) => n,
+ None => {
+ set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::ElementNotFound,
+ "no element matched the find query",
+ ));
+ return AdResult::ErrElementNotFound;
+ }
+ };
+
+ let bounds_hash = matched.bounds.as_ref().map(|r| r.bounds_hash());
+ let ref_entry = RefEntry {
+ pid: core_win.pid,
+ role: matched.role.clone(),
+ name: matched.name.clone(),
+ value: matched.value.clone(),
+ states: matched.states.clone(),
+ bounds: matched.bounds,
+ bounds_hash,
+ available_actions: Vec::new(),
+ source_app: None,
+ root_ref: None,
+ };
+ match adapter.inner.resolve_element(&ref_entry) {
+ Ok(handle) => {
+ (*out_handle).ptr = handle.as_raw();
+ AdResult::Ok
+ }
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ }
+ })
+}
diff --git a/crates/ffi/src/observation/get.rs b/crates/ffi/src/observation/get.rs
new file mode 100644
index 000000000..100660775
--- /dev/null
+++ b/crates/ffi/src/observation/get.rs
@@ -0,0 +1,95 @@
+use crate::convert::string::{c_to_string, string_to_c_lossy};
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::types::AdNativeHandle;
+use crate::AdAdapter;
+use agent_desktop_core::adapter::NativeHandle;
+use std::os::raw::c_char;
+
+/// Reads a single property off a previously-resolved element handle.
+///
+/// Supported properties:
+/// - `"value"` — live textual value (text fields, sliders, progress
+/// indicators). Null out-string when the element has no value.
+/// - `"bounds"` — JSON-encoded `{"x":..,"y":..,"width":..,"height":..}`.
+/// Null out-string when bounds are unavailable.
+///
+/// The returned string must be freed with `ad_free_string`.
+///
+/// # Safety
+/// `adapter` must be valid. `handle` must be a non-null `AdNativeHandle`.
+/// `property` must be a non-null UTF-8 C string. `out` must be a valid
+/// writable `*mut *mut c_char`; it is null-initialized on entry.
+#[no_mangle]
+pub unsafe extern "C" fn ad_get(
+ adapter: *const AdAdapter,
+ handle: *const AdNativeHandle,
+ property: *const c_char,
+ out: *mut *mut c_char,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ crate::pointer_guard::guard_non_null!(out, c"out is null");
+ *out = std::ptr::null_mut();
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ crate::pointer_guard::guard_non_null!(handle, c"handle is null");
+ let adapter = &*adapter;
+ let raw = (*handle).ptr;
+ if raw.is_null() {
+ set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "handle.ptr is null — the handle has already been freed or was never resolved",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ let native = NativeHandle::from_ptr(raw);
+ let prop = match c_to_string(property) {
+ Some(s) => s,
+ None => {
+ set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "property is null or invalid UTF-8",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+
+ match prop.as_str() {
+ "value" => match adapter.inner.get_live_value(&native) {
+ Ok(Some(v)) => {
+ *out = string_to_c_lossy(&v);
+ AdResult::Ok
+ }
+ Ok(None) => AdResult::Ok,
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ },
+ "bounds" => match adapter.inner.get_element_bounds(&native) {
+ Ok(Some(r)) => {
+ let json = format!(
+ "{{\"x\":{},\"y\":{},\"width\":{},\"height\":{}}}",
+ r.x, r.y, r.width, r.height
+ );
+ *out = string_to_c_lossy(&json);
+ AdResult::Ok
+ }
+ Ok(None) => AdResult::Ok,
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ },
+ _ => {
+ set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "unknown property — expected one of: value, bounds",
+ ));
+ AdResult::ErrInvalidArgs
+ }
+ }
+ })
+}
diff --git a/crates/ffi/src/observation/is.rs b/crates/ffi/src/observation/is.rs
new file mode 100644
index 000000000..549481560
--- /dev/null
+++ b/crates/ffi/src/observation/is.rs
@@ -0,0 +1,209 @@
+use crate::convert::string::{c_to_string, decode_optional_filter};
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::types::{AdFindQuery, AdWindowInfo};
+use crate::AdAdapter;
+use agent_desktop_core::adapter::{SnapshotSurface, TreeOptions};
+use agent_desktop_core::node::AccessibilityNode;
+use std::os::raw::c_char;
+
+/// Checks whether a named boolean state is set on the first element
+/// matching `query` inside `win`'s accessibility tree. Intended for
+/// the common agent idiom `find → is("focused") → if yes, act`.
+///
+/// Supported property names reflect the strings the macOS tree
+/// builder actually emits in `AccessibilityNode.states`:
+///
+/// - `"focused"` — true when the node carries the `focused` state.
+/// - `"disabled"` — true when the adapter surfaced `disabled`.
+/// - `"enabled"` — derived: true iff `disabled` is NOT present. There
+/// is no `enabled` string in the adapter output; asking for it
+/// returns the logical negation so agents don't have to invert
+/// themselves.
+///
+/// `"selected"`, `"checked"`, and `"expanded"` are not currently
+/// emitted by any platform adapter; asking for them returns
+/// `AD_RESULT_ERR_INVALID_ARGS` with a diagnostic last-error rather
+/// than silently answering `false`. The set will widen as adapters
+/// grow support; future additions stay backwards-compatible
+/// (unknown → InvalidArgs, known → deterministic answer).
+///
+/// On entry `*out` is always cleared to `false` so a caller inspecting
+/// the slot after an error sees a predictable sentinel, not whatever
+/// was there before. If the query matches nothing, returns
+/// `AD_RESULT_ERR_ELEMENT_NOT_FOUND` with `*out` still `false`.
+///
+/// # Safety
+/// All pointers must be valid. `property` must be a non-null UTF-8
+/// C string. `out` must be a valid writable `*mut bool`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_is(
+ adapter: *const AdAdapter,
+ win: *const AdWindowInfo,
+ query: *const AdFindQuery,
+ property: *const c_char,
+ out: *mut bool,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ crate::pointer_guard::guard_non_null!(out, c"out is null");
+ *out = false;
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ crate::pointer_guard::guard_non_null!(win, c"win is null");
+ crate::pointer_guard::guard_non_null!(query, c"query is null");
+ let adapter = &*adapter;
+ let core_win = match crate::windows::ad_window_to_core(&*win) {
+ Ok(w) => w,
+ Err(e) => {
+ set_last_error(&e);
+ return crate::error::last_error_code();
+ }
+ };
+ let q = &*query;
+ let role_filter = decode_optional_filter!(q.role, "query.role");
+ let name_filter = decode_optional_filter!(q.name_substring, "query.name_substring");
+ let value_filter = decode_optional_filter!(q.value_substring, "query.value_substring");
+ let prop = match c_to_string(property) {
+ Some(s) => s,
+ None => {
+ set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "property is null or invalid UTF-8",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+ let property = match SupportedProperty::from_name(&prop) {
+ Some(p) => p,
+ None => {
+ set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "unknown property — expected one of: focused, disabled, enabled",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+
+ let tree = match adapter.inner.get_tree(
+ &core_win,
+ &TreeOptions {
+ max_depth: 50,
+ include_bounds: false,
+ interactive_only: false,
+ compact: false,
+ surface: SnapshotSurface::Window,
+ skeleton: false,
+ },
+ ) {
+ Ok(t) => t,
+ Err(e) => {
+ set_last_error(&e);
+ return crate::error::last_error_code();
+ }
+ };
+
+ let matched = match crate::observation::walk::find_first_match(
+ &tree,
+ role_filter.as_deref(),
+ name_filter.as_deref(),
+ value_filter.as_deref(),
+ ) {
+ Some(n) => n,
+ None => {
+ set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::ElementNotFound,
+ "no element matched the find query",
+ ));
+ return AdResult::ErrElementNotFound;
+ }
+ };
+
+ *out = property.evaluate(matched);
+ AdResult::Ok
+ })
+}
+
+/// Compile-time set of property names `ad_is` answers. Each variant
+/// encodes how the answer is derived from `AccessibilityNode.states`,
+/// which keeps the documented contract and the implementation in
+/// lockstep — an addition here is the only way to add a supported name.
+enum SupportedProperty {
+ Focused,
+ Disabled,
+ EnabledDerivedFromDisabled,
+}
+
+impl SupportedProperty {
+ fn from_name(name: &str) -> Option<Self> {
+ match name {
+ "focused" => Some(SupportedProperty::Focused),
+ "disabled" => Some(SupportedProperty::Disabled),
+ "enabled" => Some(SupportedProperty::EnabledDerivedFromDisabled),
+ _ => None,
+ }
+ }
+
+ fn evaluate(&self, node: &AccessibilityNode) -> bool {
+ match self {
+ SupportedProperty::Focused => has_state(node, "focused"),
+ SupportedProperty::Disabled => has_state(node, "disabled"),
+ SupportedProperty::EnabledDerivedFromDisabled => !has_state(node, "disabled"),
+ }
+ }
+}
+
+fn has_state(node: &AccessibilityNode, state: &str) -> bool {
+ node.states.iter().any(|s| s.eq_ignore_ascii_case(state))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn node_with_states(states: &[&str]) -> AccessibilityNode {
+ AccessibilityNode {
+ ref_id: None,
+ role: "button".into(),
+ name: None,
+ value: None,
+ description: None,
+ hint: None,
+ states: states.iter().map(|s| s.to_string()).collect(),
+ bounds: None,
+ children: vec![],
+ children_count: None,
+ }
+ }
+
+ #[test]
+ fn focused_mirrors_state_presence() {
+ let prop = SupportedProperty::from_name("focused").unwrap();
+ assert!(prop.evaluate(&node_with_states(&["focused"])));
+ assert!(!prop.evaluate(&node_with_states(&[])));
+ }
+
+ #[test]
+ fn disabled_mirrors_state_presence() {
+ let prop = SupportedProperty::from_name("disabled").unwrap();
+ assert!(prop.evaluate(&node_with_states(&["disabled"])));
+ assert!(!prop.evaluate(&node_with_states(&["focused"])));
+ }
+
+ #[test]
+ fn enabled_is_derived_negation_of_disabled() {
+ let prop = SupportedProperty::from_name("enabled").unwrap();
+ assert!(!prop.evaluate(&node_with_states(&["disabled"])));
+ assert!(prop.evaluate(&node_with_states(&[])));
+ assert!(prop.evaluate(&node_with_states(&["focused"])));
+ }
+
+ #[test]
+ fn unsupported_names_do_not_resolve() {
+ assert!(SupportedProperty::from_name("selected").is_none());
+ assert!(SupportedProperty::from_name("checked").is_none());
+ assert!(SupportedProperty::from_name("expanded").is_none());
+ assert!(SupportedProperty::from_name("bogus").is_none());
+ }
+}
diff --git a/crates/ffi/src/observation/mod.rs b/crates/ffi/src/observation/mod.rs
new file mode 100644
index 000000000..43a99425a
--- /dev/null
+++ b/crates/ffi/src/observation/mod.rs
@@ -0,0 +1,4 @@
+pub(crate) mod find;
+pub(crate) mod get;
+pub(crate) mod is;
+pub(crate) mod walk;
diff --git a/crates/ffi/src/observation/walk.rs b/crates/ffi/src/observation/walk.rs
new file mode 100644
index 000000000..95a576032
--- /dev/null
+++ b/crates/ffi/src/observation/walk.rs
@@ -0,0 +1,124 @@
+use agent_desktop_core::node::AccessibilityNode;
+
+/// Finds the first node in DFS order that matches every provided filter.
+/// Filters are ANDed; a `None` filter means "don't care". Substring
+/// matching is case-insensitive to tolerate platform-specific casing
+/// (macOS AX strings vary between "AXButton" and "button").
+pub(crate) fn find_first_match<'a>(
+ node: &'a AccessibilityNode,
+ role: Option<&str>,
+ name: Option<&str>,
+ value: Option<&str>,
+) -> Option<&'a AccessibilityNode> {
+ if matches_all(node, role, name, value) {
+ return Some(node);
+ }
+ for child in &node.children {
+ if let Some(hit) = find_first_match(child, role, name, value) {
+ return Some(hit);
+ }
+ }
+ None
+}
+
+fn matches_all(
+ node: &AccessibilityNode,
+ role: Option<&str>,
+ name: Option<&str>,
+ value: Option<&str>,
+) -> bool {
+ if let Some(r) = role {
+ if !contains_ignore_case(&node.role, r) {
+ return false;
+ }
+ }
+ if let Some(n) = name {
+ match node.name.as_deref() {
+ Some(actual) if contains_ignore_case(actual, n) => {}
+ _ => return false,
+ }
+ }
+ if let Some(v) = value {
+ match node.value.as_deref() {
+ Some(actual) if contains_ignore_case(actual, v) => {}
+ _ => return false,
+ }
+ }
+ true
+}
+
+fn contains_ignore_case(haystack: &str, needle: &str) -> bool {
+ haystack.to_lowercase().contains(&needle.to_lowercase())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use agent_desktop_core::node::Rect;
+
+ fn node(role: &str, name: Option<&str>, value: Option<&str>) -> AccessibilityNode {
+ AccessibilityNode {
+ ref_id: None,
+ role: role.into(),
+ name: name.map(str::to_string),
+ value: value.map(str::to_string),
+ description: None,
+ hint: None,
+ states: vec![],
+ bounds: None,
+ children: vec![],
+ children_count: None,
+ }
+ }
+
+ #[test]
+ fn finds_first_matching_role() {
+ let mut root = node("window", None, None);
+ root.children.push(node("button", Some("OK"), None));
+ root.children.push(node("button", Some("Cancel"), None));
+
+ let hit = find_first_match(&root, Some("button"), None, None).unwrap();
+ assert_eq!(hit.name.as_deref(), Some("OK"));
+ }
+
+ #[test]
+ fn value_substring_disambiguates_duplicate_labels() {
+ let mut root = node("window", None, None);
+ root.children
+ .push(node("button", Some("Save"), Some("pressed")));
+ root.children
+ .push(node("button", Some("Save"), Some("default")));
+
+ let hit = find_first_match(&root, Some("button"), Some("Save"), Some("default")).unwrap();
+ assert_eq!(hit.value.as_deref(), Some("default"));
+ }
+
+ #[test]
+ fn matched_node_bounds_hash_stable_across_calls() {
+ let mut matched = node("button", Some("OK"), None);
+ matched.bounds = Some(Rect {
+ x: 10.0,
+ y: 20.0,
+ width: 80.0,
+ height: 24.0,
+ });
+ let first = matched.bounds.as_ref().map(|r| r.bounds_hash()).unwrap();
+ let second = matched.bounds.as_ref().map(|r| r.bounds_hash()).unwrap();
+ assert_eq!(first, second);
+ }
+
+ #[test]
+ fn missing_filter_field_treats_as_dont_care() {
+ let root = node("button", Some("OK"), Some("enabled"));
+ assert!(find_first_match(&root, None, None, None).is_some());
+ assert!(find_first_match(&root, Some("button"), None, None).is_some());
+ assert!(find_first_match(&root, None, Some("OK"), None).is_some());
+ }
+
+ #[test]
+ fn no_match_returns_none() {
+ let root = node("window", Some("App"), None);
+ assert!(find_first_match(&root, Some("slider"), None, None).is_none());
+ assert!(find_first_match(&root, None, Some("nonexistent"), None).is_none());
+ }
+}
diff --git a/crates/ffi/src/pointer_guard.rs b/crates/ffi/src/pointer_guard.rs
new file mode 100644
index 000000000..faae2546f
--- /dev/null
+++ b/crates/ffi/src/pointer_guard.rs
@@ -0,0 +1,52 @@
+//! Shared pointer-validation helper for FFI entrypoints.
+//!
+//! The FFI contract promises that malformed foreign input (null
+//! pointers) turns into a structured `AD_RESULT_ERR_INVALID_ARGS`
+//! error, not a segfault. `trap_panic` can only catch Rust panics — it
+//! does not recover from raw-pointer UB. Every extern fn therefore
+//! validates its inputs before the first dereference using
+//! [`guard_non_null`].
+
+/// Bail out of the enclosing `AdResult`-returning function with
+/// `AD_RESULT_ERR_INVALID_ARGS` when `$ptr` is null. The `'static`
+/// `$message` is surfaced via the errno-style last-error slot so C
+/// consumers see which pointer was rejected.
+macro_rules! guard_non_null {
+ ($ptr:expr, $message:expr) => {
+ if ($ptr).is_null() {
+ $crate::error::set_last_error_static($crate::error::AdResult::ErrInvalidArgs, $message);
+ return $crate::error::AdResult::ErrInvalidArgs;
+ }
+ };
+}
+
+pub(crate) use guard_non_null;
+
+#[cfg(test)]
+mod tests {
+ use crate::error::AdResult;
+
+ fn null_case() -> AdResult {
+ let null_ptr: *const u8 = std::ptr::null();
+ guard_non_null!(null_ptr, c"null_ptr");
+ AdResult::Ok
+ }
+
+ fn nonnull_case() -> AdResult {
+ let value: u8 = 0;
+ let ptr: *const u8 = &value;
+ guard_non_null!(ptr, c"ptr");
+ AdResult::Ok
+ }
+
+ #[test]
+ fn null_pointer_short_circuits_with_invalid_args() {
+ assert!(matches!(null_case(), AdResult::ErrInvalidArgs));
+ assert_eq!(crate::error::last_error_code(), AdResult::ErrInvalidArgs);
+ }
+
+ #[test]
+ fn non_null_pointer_passes_through() {
+ assert!(matches!(nonnull_case(), AdResult::Ok));
+ }
+}
diff --git a/crates/ffi/src/screenshot/accessors.rs b/crates/ffi/src/screenshot/accessors.rs
new file mode 100644
index 000000000..2aac1b0a0
--- /dev/null
+++ b/crates/ffi/src/screenshot/accessors.rs
@@ -0,0 +1,70 @@
+use crate::types::{AdImageBuffer, AdImageFormat};
+use std::ptr;
+
+/// Borrowed pointer to the image bytes; valid until the buffer is freed.
+/// Returns null if `buf` is null.
+///
+/// # Safety
+/// `buf` must be null or returned by `ad_screenshot`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_image_buffer_data(buf: *const AdImageBuffer) -> *const u8 {
+ if buf.is_null() {
+ return ptr::null();
+ }
+ let buf_ref: &AdImageBuffer = unsafe { &*buf };
+ buf_ref.data.as_ptr()
+}
+
+/// Byte length of the buffer returned by `ad_image_buffer_data`.
+/// Always consistent with the actual allocation (no C-mutable mismatch).
+///
+/// # Safety
+/// `buf` must be null or returned by `ad_screenshot`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_image_buffer_size(buf: *const AdImageBuffer) -> u64 {
+ if buf.is_null() {
+ return 0;
+ }
+ let buf_ref: &AdImageBuffer = unsafe { &*buf };
+ buf_ref.data.len() as u64
+}
+
+/// Pixel width of the image.
+///
+/// # Safety
+/// `buf` must be null or returned by `ad_screenshot`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_image_buffer_width(buf: *const AdImageBuffer) -> u32 {
+ if buf.is_null() {
+ return 0;
+ }
+ let buf_ref: &AdImageBuffer = unsafe { &*buf };
+ buf_ref.width
+}
+
+/// Pixel height of the image.
+///
+/// # Safety
+/// `buf` must be null or returned by `ad_screenshot`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_image_buffer_height(buf: *const AdImageBuffer) -> u32 {
+ if buf.is_null() {
+ return 0;
+ }
+ let buf_ref: &AdImageBuffer = unsafe { &*buf };
+ buf_ref.height
+}
+
+/// Encoding format of the image bytes. Defaults to `PNG` on a null
+/// handle — callers must still null-check.
+///
+/// # Safety
+/// `buf` must be null or returned by `ad_screenshot`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_image_buffer_format(buf: *const AdImageBuffer) -> AdImageFormat {
+ if buf.is_null() {
+ return AdImageFormat::Png;
+ }
+ let buf_ref: &AdImageBuffer = unsafe { &*buf };
+ buf_ref.format
+}
diff --git a/crates/ffi/src/screenshot/capture.rs b/crates/ffi/src/screenshot/capture.rs
new file mode 100644
index 000000000..d6cd18558
--- /dev/null
+++ b/crates/ffi/src/screenshot/capture.rs
@@ -0,0 +1,69 @@
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::types::{AdImageBuffer, AdImageFormat, AdScreenshotKind, AdScreenshotTarget};
+use crate::AdAdapter;
+use agent_desktop_core::adapter::{ImageFormat, ScreenshotTarget as CoreScreenshotTarget};
+use std::ptr;
+
+/// Allocates and returns an opaque `AdImageBuffer`. The handle owns its
+/// byte buffer; inspect it through `ad_image_buffer_data` /
+/// `ad_image_buffer_size` / `ad_image_buffer_format` / `_width` / `_height`
+/// and free it with `ad_image_buffer_free`.
+///
+/// # Safety
+/// `adapter` and `target` must be valid pointers. `out` must be a valid
+/// writable `*mut *mut AdImageBuffer`. On error `*out` is null and
+/// last-error is set.
+#[no_mangle]
+pub unsafe extern "C" fn ad_screenshot(
+ adapter: *const AdAdapter,
+ target: *const AdScreenshotTarget,
+ out: *mut *mut AdImageBuffer,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ crate::pointer_guard::guard_non_null!(out, c"out is null");
+ *out = ptr::null_mut();
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ crate::pointer_guard::guard_non_null!(target, c"target is null");
+ let adapter = &*adapter;
+ let t = &*target;
+ let kind = match AdScreenshotKind::from_c(t.kind) {
+ Some(k) => k,
+ None => {
+ set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "invalid screenshot kind discriminant",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+ let core_target = match kind {
+ AdScreenshotKind::Screen => CoreScreenshotTarget::Screen(t.screen_index as usize),
+ AdScreenshotKind::Window => CoreScreenshotTarget::Window(t.pid),
+ AdScreenshotKind::FullScreen => CoreScreenshotTarget::FullScreen,
+ };
+
+ match adapter.inner.screenshot(core_target) {
+ Ok(img) => {
+ let buffer = Box::new(AdImageBuffer {
+ data: img.data.into_boxed_slice(),
+ width: img.width,
+ height: img.height,
+ format: match img.format {
+ ImageFormat::Png => AdImageFormat::Png,
+ ImageFormat::Jpg => AdImageFormat::Jpg,
+ },
+ });
+ *out = Box::into_raw(buffer);
+ AdResult::Ok
+ }
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ }
+ })
+}
diff --git a/crates/ffi/src/screenshot/free.rs b/crates/ffi/src/screenshot/free.rs
new file mode 100644
index 000000000..4e24dcbd3
--- /dev/null
+++ b/crates/ffi/src/screenshot/free.rs
@@ -0,0 +1,17 @@
+use crate::ffi_try::trap_panic_void;
+use crate::types::AdImageBuffer;
+
+/// Frees the image buffer allocated by `ad_screenshot`.
+///
+/// # Safety
+/// `buf` must be null or a pointer previously returned by `ad_screenshot`.
+/// Double-free is undefined behavior.
+#[no_mangle]
+pub unsafe extern "C" fn ad_image_buffer_free(buf: *mut AdImageBuffer) {
+ trap_panic_void(|| unsafe {
+ if buf.is_null() {
+ return;
+ }
+ drop(Box::from_raw(buf));
+ })
+}
diff --git a/crates/ffi/src/screenshot/mod.rs b/crates/ffi/src/screenshot/mod.rs
new file mode 100644
index 000000000..b307f2d86
--- /dev/null
+++ b/crates/ffi/src/screenshot/mod.rs
@@ -0,0 +1,3 @@
+pub(crate) mod accessors;
+pub(crate) mod capture;
+pub(crate) mod free;
diff --git a/crates/ffi/src/surfaces/list.rs b/crates/ffi/src/surfaces/list.rs
new file mode 100644
index 000000000..009d4dabc
--- /dev/null
+++ b/crates/ffi/src/surfaces/list.rs
@@ -0,0 +1,88 @@
+use crate::convert::surface::{free_surface_info_fields, surface_info_to_c};
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::{trap_panic, trap_panic_void};
+use crate::types::{AdSurfaceInfo, AdSurfaceList};
+use crate::AdAdapter;
+use std::ptr;
+
+/// # Safety
+/// `adapter` must be valid. `out` must be a valid writable
+/// `*mut *mut AdSurfaceList`. Success produces a list handle freed via
+/// `ad_surface_list_free`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_list_surfaces(
+ adapter: *const AdAdapter,
+ pid: i32,
+ out: *mut *mut AdSurfaceList,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ crate::pointer_guard::guard_non_null!(out, c"out is null");
+ *out = ptr::null_mut();
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ let adapter = &*adapter;
+ match adapter.inner.list_surfaces(pid) {
+ Ok(surfaces) => {
+ let items: Vec<AdSurfaceInfo> = surfaces.iter().map(surface_info_to_c).collect();
+ let list = Box::new(AdSurfaceList {
+ items: items.into_boxed_slice(),
+ });
+ *out = Box::into_raw(list);
+ AdResult::Ok
+ }
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ }
+ })
+}
+
+/// # Safety
+/// `list` must be null or a pointer returned by `ad_list_surfaces`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_surface_list_count(list: *const AdSurfaceList) -> u32 {
+ if list.is_null() {
+ return 0;
+ }
+ let list_ref: &AdSurfaceList = unsafe { &*list };
+ list_ref.items.len() as u32
+}
+
+/// Borrow a surface info entry. Null if `index` is out of range.
+///
+/// # Safety
+/// `list` must be null or a pointer returned by `ad_list_surfaces`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_surface_list_get(
+ list: *const AdSurfaceList,
+ index: u32,
+) -> *const AdSurfaceInfo {
+ if list.is_null() {
+ return ptr::null();
+ }
+ let list_ref: &AdSurfaceList = unsafe { &*list };
+ match list_ref.items.get(index as usize) {
+ Some(item) => item as *const AdSurfaceInfo,
+ None => ptr::null(),
+ }
+}
+
+/// Frees the list and each entry's interior strings.
+///
+/// # Safety
+/// `list` must be null or a pointer returned by `ad_list_surfaces`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_surface_list_free(list: *mut AdSurfaceList) {
+ trap_panic_void(|| unsafe {
+ if list.is_null() {
+ return;
+ }
+ let mut list = Box::from_raw(list);
+ for item in list.items.iter_mut() {
+ free_surface_info_fields(item);
+ }
+ })
+}
diff --git a/crates/ffi/src/surfaces/mod.rs b/crates/ffi/src/surfaces/mod.rs
new file mode 100644
index 000000000..c5ea1738d
--- /dev/null
+++ b/crates/ffi/src/surfaces/mod.rs
@@ -0,0 +1 @@
+pub(crate) mod list;
diff --git a/crates/ffi/src/tree/flatten.rs b/crates/ffi/src/tree/flatten.rs
new file mode 100644
index 000000000..4611d501e
--- /dev/null
+++ b/crates/ffi/src/tree/flatten.rs
@@ -0,0 +1,281 @@
+use crate::convert::string::{opt_string_to_c, string_to_c_lossy};
+use crate::types::{AdNode, AdNodeTree, AdRect};
+use agent_desktop_core::node::AccessibilityNode;
+use std::collections::VecDeque;
+use std::os::raw::c_char;
+use std::ptr;
+
+/// Flattens an `AccessibilityNode` tree into the BFS-ordered layout
+/// C consumers see via `AdNodeTree.nodes`.
+///
+/// Guarantees:
+/// - Direct children of any `AdNode` at index `i` live contiguously at
+/// `nodes[n.child_start .. n.child_start + n.child_count]`. This is
+/// the BFS (level-order) layout.
+/// - `parent_index` is `-1` for the root and otherwise a valid back-index
+/// into `nodes`.
+/// - `child_count` is zero when `child_start` is not indexable.
+///
+/// A recursive DFS layout placed node `a1` immediately after its parent
+/// `a`, overlapping with `a`'s siblings — the range
+/// `a.child_start..a.child_start + a.child_count` therefore stepped into
+/// grandchildren. BFS keeps siblings contiguous by construction.
+pub(crate) fn flatten_tree(root: &AccessibilityNode) -> AdNodeTree {
+ let total = count_nodes(root);
+ let mut flat: Vec<AdNode> = Vec::with_capacity(total);
+
+ flat.push(to_ad_node(root, -1));
+ let mut queue: VecDeque<(&AccessibilityNode, usize)> = VecDeque::new();
+ queue.push_back((root, 0));
+
+ while let Some((node, node_idx)) = queue.pop_front() {
+ if node.children.is_empty() {
+ continue;
+ }
+ let child_start = flat.len() as u32;
+ let child_count = node.children.len() as u32;
+ flat[node_idx].child_start = child_start;
+ flat[node_idx].child_count = child_count;
+ for child in &node.children {
+ let child_idx = flat.len();
+ flat.push(to_ad_node(child, node_idx as i32));
+ queue.push_back((child, child_idx));
+ }
+ }
+
+ let count = flat.len() as u32;
+ let nodes = if flat.is_empty() {
+ ptr::null_mut()
+ } else {
+ let mut boxed = flat.into_boxed_slice();
+ let ptr = boxed.as_mut_ptr();
+ std::mem::forget(boxed);
+ ptr
+ };
+ AdNodeTree { nodes, count }
+}
+
+fn count_nodes(node: &AccessibilityNode) -> usize {
+ let mut total: usize = 0;
+ let mut queue: VecDeque<&AccessibilityNode> = VecDeque::new();
+ queue.push_back(node);
+ while let Some(n) = queue.pop_front() {
+ total += 1;
+ for c in &n.children {
+ queue.push_back(c);
+ }
+ }
+ total
+}
+
+fn to_ad_node(node: &AccessibilityNode, parent_index: i32) -> AdNode {
+ let (states_ptr, state_count) = strings_to_c_array(&node.states);
+ let (bounds, has_bounds) = match &node.bounds {
+ Some(r) => (crate::convert::rect_to_c(r), true),
+ None => (
+ AdRect {
+ x: 0.0,
+ y: 0.0,
+ width: 0.0,
+ height: 0.0,
+ },
+ false,
+ ),
+ };
+ AdNode {
+ ref_id: opt_string_to_c(node.ref_id.as_deref()),
+ role: string_to_c_lossy(&node.role),
+ name: opt_string_to_c(node.name.as_deref()),
+ value: opt_string_to_c(node.value.as_deref()),
+ description: opt_string_to_c(node.description.as_deref()),
+ hint: opt_string_to_c(node.hint.as_deref()),
+ states: states_ptr,
+ state_count,
+ bounds,
+ has_bounds,
+ parent_index,
+ child_start: 0,
+ child_count: 0,
+ }
+}
+
+fn strings_to_c_array(strings: &[String]) -> (*mut *mut c_char, u32) {
+ if strings.is_empty() {
+ return (ptr::null_mut(), 0);
+ }
+ let ptrs: Vec<*mut c_char> = strings.iter().map(|s| string_to_c_lossy(s)).collect();
+ let count = ptrs.len() as u32;
+ let mut boxed = ptrs.into_boxed_slice();
+ let ptr = boxed.as_mut_ptr();
+ std::mem::forget(boxed);
+ (ptr, count)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::convert::string::c_to_string;
+ use crate::tree::free::ad_free_tree;
+
+ fn node(role: &str) -> AccessibilityNode {
+ AccessibilityNode {
+ ref_id: None,
+ role: role.into(),
+ name: None,
+ value: None,
+ description: None,
+ hint: None,
+ states: vec![],
+ bounds: None,
+ children: vec![],
+ children_count: None,
+ }
+ }
+
+ fn direct_children(nodes: &[AdNode], idx: usize) -> Vec<&AdNode> {
+ let n = &nodes[idx];
+ let start = n.child_start as usize;
+ let end = start + n.child_count as usize;
+ nodes[start..end].iter().collect()
+ }
+
+ #[test]
+ fn test_flatten_single_node() {
+ let root = node("window");
+ let tree = flatten_tree(&root);
+ assert_eq!(tree.count, 1);
+ let nodes = unsafe { std::slice::from_raw_parts(tree.nodes, 1) };
+ assert_eq!(nodes[0].parent_index, -1);
+ assert_eq!(nodes[0].child_count, 0);
+ let role = unsafe { c_to_string(nodes[0].role) };
+ assert_eq!(role.as_deref(), Some("window"));
+ unsafe { ad_free_tree(&tree as *const _ as *mut _) };
+ }
+
+ #[test]
+ fn test_flatten_parent_child() {
+ let btn = node("button");
+ let mut root = node("window");
+ root.children = vec![btn];
+
+ let tree = flatten_tree(&root);
+ assert_eq!(tree.count, 2);
+ let nodes = unsafe { std::slice::from_raw_parts(tree.nodes, 2) };
+
+ assert_eq!(nodes[0].parent_index, -1);
+ assert_eq!(nodes[0].child_start, 1);
+ assert_eq!(nodes[0].child_count, 1);
+
+ assert_eq!(nodes[1].parent_index, 0);
+ assert_eq!(nodes[1].child_count, 0);
+ let role = unsafe { c_to_string(nodes[1].role) };
+ assert_eq!(role.as_deref(), Some("button"));
+
+ unsafe { ad_free_tree(&tree as *const _ as *mut _) };
+ }
+
+ #[test]
+ fn test_flatten_breadth_first_layout() {
+ let a1 = node("a1");
+ let a2 = node("a2");
+ let mut a = node("a");
+ a.children = vec![a1, a2];
+ let b = node("b");
+ let mut root = node("root");
+ root.children = vec![a, b];
+
+ let tree = flatten_tree(&root);
+ assert_eq!(tree.count, 5);
+ let nodes = unsafe { std::slice::from_raw_parts(tree.nodes, 5) };
+
+ let roles: Vec<String> = nodes
+ .iter()
+ .map(|n| unsafe { c_to_string(n.role).unwrap() })
+ .collect();
+ assert_eq!(roles, vec!["root", "a", "b", "a1", "a2"]);
+
+ let root_children: Vec<String> = direct_children(nodes, 0)
+ .iter()
+ .map(|n| unsafe { c_to_string(n.role).unwrap() })
+ .collect();
+ assert_eq!(root_children, vec!["a", "b"]);
+
+ let a_idx = nodes
+ .iter()
+ .position(|n| unsafe { c_to_string(n.role).unwrap() } == "a")
+ .unwrap();
+ let a_children: Vec<String> = direct_children(nodes, a_idx)
+ .iter()
+ .map(|n| unsafe { c_to_string(n.role).unwrap() })
+ .collect();
+ assert_eq!(a_children, vec!["a1", "a2"]);
+
+ let b_idx = nodes
+ .iter()
+ .position(|n| unsafe { c_to_string(n.role).unwrap() } == "b")
+ .unwrap();
+ assert!(direct_children(nodes, b_idx).is_empty());
+
+ unsafe { ad_free_tree(&tree as *const _ as *mut _) };
+ }
+
+ #[test]
+ fn test_flatten_deep_chain() {
+ let mut leaf = node("l10");
+ for i in (0..10).rev() {
+ let mut parent = node(&format!("l{}", i));
+ parent.children = vec![leaf];
+ leaf = parent;
+ }
+ let tree = flatten_tree(&leaf);
+ assert_eq!(tree.count, 11);
+ let nodes = unsafe { std::slice::from_raw_parts(tree.nodes, 11) };
+
+ let mut cursor = 0usize;
+ for expected in 0..11 {
+ let role = unsafe { c_to_string(nodes[cursor].role).unwrap() };
+ assert_eq!(role, format!("l{}", expected));
+ let children = direct_children(nodes, cursor);
+ if expected < 10 {
+ assert_eq!(children.len(), 1);
+ cursor = nodes[cursor].child_start as usize;
+ } else {
+ assert!(children.is_empty());
+ }
+ }
+ unsafe { ad_free_tree(&tree as *const _ as *mut _) };
+ }
+
+ #[test]
+ fn test_flatten_wide_root() {
+ let mut root = node("root");
+ for i in 0..100 {
+ root.children.push(node(&format!("child_{}", i)));
+ }
+ let tree = flatten_tree(&root);
+ assert_eq!(tree.count, 101);
+ let nodes = unsafe { std::slice::from_raw_parts(tree.nodes, 101) };
+ let children = direct_children(nodes, 0);
+ assert_eq!(children.len(), 100);
+ for (i, c) in children.iter().enumerate() {
+ let role = unsafe { c_to_string(c.role).unwrap() };
+ assert_eq!(role, format!("child_{}", i));
+ }
+ unsafe { ad_free_tree(&tree as *const _ as *mut _) };
+ }
+
+ #[test]
+ fn test_flatten_with_states() {
+ let mut btn = node("button");
+ btn.states = vec!["focused".into(), "enabled".into()];
+ let tree = flatten_tree(&btn);
+ let nodes = unsafe { std::slice::from_raw_parts(tree.nodes, 1) };
+ assert_eq!(nodes[0].state_count, 2);
+ let states = unsafe { std::slice::from_raw_parts(nodes[0].states, 2) };
+ let s0 = unsafe { c_to_string(states[0]) };
+ let s1 = unsafe { c_to_string(states[1]) };
+ assert_eq!(s0.as_deref(), Some("focused"));
+ assert_eq!(s1.as_deref(), Some("enabled"));
+ unsafe { ad_free_tree(&tree as *const _ as *mut _) };
+ }
+}
diff --git a/crates/ffi/src/tree/free.rs b/crates/ffi/src/tree/free.rs
new file mode 100644
index 000000000..91c84dc9e
--- /dev/null
+++ b/crates/ffi/src/tree/free.rs
@@ -0,0 +1,72 @@
+use crate::convert::string::free_c_string;
+use crate::types::{AdNode, AdNodeTree};
+use std::os::raw::c_char;
+use std::ptr;
+
+unsafe fn free_c_string_array(arr: *mut *mut c_char, count: u32) {
+ if arr.is_null() {
+ return;
+ }
+ let slice = std::slice::from_raw_parts_mut(arr, count as usize);
+ for p in slice.iter_mut() {
+ free_c_string(*p);
+ }
+ drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(
+ arr,
+ count as usize,
+ )));
+}
+
+unsafe fn free_node_fields(node: &mut AdNode) {
+ free_c_string(node.ref_id as *mut c_char);
+ free_c_string(node.role as *mut c_char);
+ free_c_string(node.name as *mut c_char);
+ free_c_string(node.value as *mut c_char);
+ free_c_string(node.description as *mut c_char);
+ free_c_string(node.hint as *mut c_char);
+ free_c_string_array(node.states, node.state_count);
+ node.ref_id = ptr::null();
+ node.role = ptr::null();
+ node.name = ptr::null();
+ node.value = ptr::null();
+ node.description = ptr::null();
+ node.hint = ptr::null();
+ node.states = ptr::null_mut();
+ node.state_count = 0;
+}
+
+/// # Safety
+/// `tree` must be null or point to a valid `AdNodeTree` previously returned
+/// by `flatten_tree` or `ad_get_tree`. After this call the tree is zeroed.
+#[no_mangle]
+pub unsafe extern "C" fn ad_free_tree(tree: *mut AdNodeTree) {
+ crate::ffi_try::trap_panic_void(|| unsafe {
+ if tree.is_null() {
+ return;
+ }
+ let tree = &mut *tree;
+ if tree.nodes.is_null() {
+ return;
+ }
+ let nodes = std::slice::from_raw_parts_mut(tree.nodes, tree.count as usize);
+ for node in nodes.iter_mut() {
+ free_node_fields(node);
+ }
+ drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(
+ tree.nodes,
+ tree.count as usize,
+ )));
+ tree.nodes = ptr::null_mut();
+ tree.count = 0;
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_free_null_tree_is_noop() {
+ unsafe { ad_free_tree(std::ptr::null_mut()) };
+ }
+}
diff --git a/crates/ffi/src/tree/get.rs b/crates/ffi/src/tree/get.rs
new file mode 100644
index 000000000..61270660d
--- /dev/null
+++ b/crates/ffi/src/tree/get.rs
@@ -0,0 +1,133 @@
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::tree::flatten::flatten_tree;
+use crate::types::{AdNodeTree, AdSnapshotSurface, AdTreeOptions, AdWindowInfo};
+use crate::AdAdapter;
+use agent_desktop_core::adapter::SnapshotSurface;
+use std::ptr;
+
+fn core_surface(s: AdSnapshotSurface) -> SnapshotSurface {
+ match s {
+ AdSnapshotSurface::Window => SnapshotSurface::Window,
+ AdSnapshotSurface::Focused => SnapshotSurface::Focused,
+ AdSnapshotSurface::Menu => SnapshotSurface::Menu,
+ AdSnapshotSurface::Menubar => SnapshotSurface::Menubar,
+ AdSnapshotSurface::Sheet => SnapshotSurface::Sheet,
+ AdSnapshotSurface::Popover => SnapshotSurface::Popover,
+ AdSnapshotSurface::Alert => SnapshotSurface::Alert,
+ }
+}
+
+/// Snapshots `win`'s accessibility tree into the flat BFS layout
+/// described in the types module. The result is written into `*out`
+/// and must be freed with `ad_free_tree`. Direct children of any node
+/// live contiguously at `nodes[child_start..child_start + child_count]`.
+///
+/// `opts.max_depth` caps tree depth. `opts.surface` selects which
+/// surface to snapshot (window body, menu, menubar, sheet, popover,
+/// alert, or focused subtree); see `AdSnapshotSurface`.
+/// `opts.interactive_only` prunes non-interactive nodes; `opts.compact`
+/// collapses containers with no semantic payload.
+///
+/// # Raw-tree contract
+///
+/// This is a **raw adapter tree**, not the snapshot the CLI `snapshot`
+/// subcommand returns. Differences the caller must know about:
+///
+/// - `ref_id` is always null on every `AdNode`. The FFI surface does
+/// not run `ref_alloc::allocate_refs`; refs are a CLI/JSON pipeline
+/// concern, so agent-facing code that needs them should drive them
+/// externally (resolve via `ad_find` + `ad_free_handle`, or call the
+/// CLI if refs are required).
+/// - `include_bounds`, `interactive_only`, and `compact` are honored
+/// after the adapter returns the raw tree, using
+/// `ref_alloc::transform_tree`. Because refs are not allocated here,
+/// the `interactive_only` cut is role-based rather than ref-based;
+/// otherwise the semantics match the CLI snapshot path.
+/// - No skeleton/drill-down pipeline is wired through — `skeleton` is
+/// always false on the underlying `TreeOptions`.
+///
+/// If parity with the CLI snapshot is important to your consumer,
+/// either use `ad_find` + `ad_get` / `ad_is` for point lookups (which
+/// bypass tree shape entirely) or invoke the CLI binary for the
+/// snapshot call. A future revision may layer a "normalized snapshot"
+/// FFI function on top of this raw path.
+///
+/// On error `*out` is zeroed so `ad_free_tree` on it is a safe no-op.
+///
+/// # Safety
+/// All pointers must be non-null. `win.id` and `win.title` must be
+/// valid UTF-8 C strings. `out` must be writable.
+#[no_mangle]
+pub unsafe extern "C" fn ad_get_tree(
+ adapter: *const AdAdapter,
+ win: *const AdWindowInfo,
+ opts: *const AdTreeOptions,
+ out: *mut AdNodeTree,
+) -> AdResult {
+ trap_panic(|| {
+ crate::pointer_guard::guard_non_null!(out, c"out is null");
+ unsafe {
+ (*out).nodes = ptr::null_mut();
+ (*out).count = 0;
+ }
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ crate::pointer_guard::guard_non_null!(win, c"win is null");
+ crate::pointer_guard::guard_non_null!(opts, c"opts is null");
+
+ let adapter = unsafe { &*adapter };
+ let opts_ref = unsafe { &*opts };
+ let core_win = match crate::windows::ad_window_to_core(unsafe { &*win }) {
+ Ok(w) => w,
+ Err(e) => {
+ set_last_error(&e);
+ return crate::error::last_error_code();
+ }
+ };
+ let surface = match AdSnapshotSurface::from_c(opts_ref.surface) {
+ Some(s) => core_surface(s),
+ None => {
+ set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "invalid snapshot surface discriminant",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+ let core_opts = agent_desktop_core::adapter::TreeOptions {
+ max_depth: opts_ref.max_depth,
+ include_bounds: opts_ref.include_bounds,
+ interactive_only: opts_ref.interactive_only,
+ compact: opts_ref.compact,
+ surface,
+ skeleton: false,
+ };
+
+ match adapter.inner.get_tree(&core_win, &core_opts) {
+ Ok(tree) => {
+ // Adapters return a full raw tree; flags live on the core
+ // TreeOptions but the macOS adapter only consumes
+ // `max_depth` and `skeleton`. Apply shape transformations
+ // here so the FFI behavior matches what AdTreeOptions
+ // documents. ref_alloc::transform_tree is the ref-free
+ // variant of allocate_refs and matches its semantics for
+ // compact/interactive_only/include_bounds.
+ let shaped = agent_desktop_core::ref_alloc::transform_tree(
+ tree,
+ core_opts.include_bounds,
+ core_opts.interactive_only,
+ core_opts.compact,
+ );
+ unsafe { *out = flatten_tree(&shaped) };
+ AdResult::Ok
+ }
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ }
+ })
+}
diff --git a/crates/ffi/src/tree/mod.rs b/crates/ffi/src/tree/mod.rs
new file mode 100644
index 000000000..05583fda5
--- /dev/null
+++ b/crates/ffi/src/tree/mod.rs
@@ -0,0 +1,3 @@
+pub(crate) mod flatten;
+pub(crate) mod free;
+pub(crate) mod get;
diff --git a/crates/ffi/src/types/action.rs b/crates/ffi/src/types/action.rs
new file mode 100644
index 000000000..5f2cc718f
--- /dev/null
+++ b/crates/ffi/src/types/action.rs
@@ -0,0 +1,20 @@
+use crate::types::drag_params::AdDragParams;
+use crate::types::key_combo::AdKeyCombo;
+use crate::types::scroll_params::AdScrollParams;
+use std::os::raw::c_char;
+
+/// Action dispatched by `ad_execute_action`.
+///
+/// `kind` is stored as `int32_t` so a buggy or malicious C caller
+/// cannot write an out-of-range discriminant into a Rust enum slot —
+/// an out-of-range value is rejected with
+/// `AD_RESULT_ERR_INVALID_ARGS` at the boundary. Valid values are the
+/// discriminants of `AdActionKind`.
+#[repr(C)]
+pub struct AdAction {
+ pub kind: i32,
+ pub text: *const c_char,
+ pub scroll: AdScrollParams,
+ pub key: AdKeyCombo,
+ pub drag: AdDragParams,
+}
diff --git a/crates/ffi/src/types/action_kind.rs b/crates/ffi/src/types/action_kind.rs
new file mode 100644
index 000000000..37ba0beea
--- /dev/null
+++ b/crates/ffi/src/types/action_kind.rs
@@ -0,0 +1,25 @@
+#[repr(i32)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AdActionKind {
+ Click = 0,
+ DoubleClick = 1,
+ RightClick = 2,
+ TripleClick = 3,
+ SetValue = 4,
+ SetFocus = 5,
+ Expand = 6,
+ Collapse = 7,
+ Select = 8,
+ Toggle = 9,
+ Check = 10,
+ Uncheck = 11,
+ Scroll = 12,
+ ScrollTo = 13,
+ PressKey = 14,
+ KeyDown = 15,
+ KeyUp = 16,
+ TypeText = 17,
+ Clear = 18,
+ Hover = 19,
+ Drag = 20,
+}
diff --git a/crates/ffi/src/types/action_result.rs b/crates/ffi/src/types/action_result.rs
new file mode 100644
index 000000000..3b0ccda60
--- /dev/null
+++ b/crates/ffi/src/types/action_result.rs
@@ -0,0 +1,9 @@
+use crate::types::element_state::AdElementState;
+use std::os::raw::c_char;
+
+#[repr(C)]
+pub struct AdActionResult {
+ pub action: *const c_char,
+ pub ref_id: *const c_char,
+ pub post_state: *mut AdElementState,
+}
diff --git a/crates/ffi/src/types/app_info.rs b/crates/ffi/src/types/app_info.rs
new file mode 100644
index 000000000..2f168bb68
--- /dev/null
+++ b/crates/ffi/src/types/app_info.rs
@@ -0,0 +1,8 @@
+use std::os::raw::c_char;
+
+#[repr(C)]
+pub struct AdAppInfo {
+ pub name: *const c_char,
+ pub pid: i32,
+ pub bundle_id: *const c_char,
+}
diff --git a/crates/ffi/src/types/app_list.rs b/crates/ffi/src/types/app_list.rs
new file mode 100644
index 000000000..5118ade52
--- /dev/null
+++ b/crates/ffi/src/types/app_list.rs
@@ -0,0 +1,7 @@
+use crate::types::app_info::AdAppInfo;
+
+/// Opaque list handle emitted by `ad_list_apps`. See
+/// [`crate::types::window_list::AdWindowList`] for the pattern.
+pub struct AdAppList {
+ pub(crate) items: Box<[AdAppInfo]>,
+}
diff --git a/crates/ffi/src/types/direction.rs b/crates/ffi/src/types/direction.rs
new file mode 100644
index 000000000..c63340027
--- /dev/null
+++ b/crates/ffi/src/types/direction.rs
@@ -0,0 +1,8 @@
+#[repr(i32)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AdDirection {
+ Up = 0,
+ Down = 1,
+ Left = 2,
+ Right = 3,
+}
diff --git a/crates/ffi/src/types/drag_params.rs b/crates/ffi/src/types/drag_params.rs
new file mode 100644
index 000000000..487f07466
--- /dev/null
+++ b/crates/ffi/src/types/drag_params.rs
@@ -0,0 +1,8 @@
+use crate::types::point::AdPoint;
+
+#[repr(C)]
+pub struct AdDragParams {
+ pub from: AdPoint,
+ pub to: AdPoint,
+ pub duration_ms: u64,
+}
diff --git a/crates/ffi/src/types/element_state.rs b/crates/ffi/src/types/element_state.rs
new file mode 100644
index 000000000..ca7560743
--- /dev/null
+++ b/crates/ffi/src/types/element_state.rs
@@ -0,0 +1,9 @@
+use std::os::raw::c_char;
+
+#[repr(C)]
+pub struct AdElementState {
+ pub role: *const c_char,
+ pub states: *mut *mut c_char,
+ pub state_count: u32,
+ pub value: *const c_char,
+}
diff --git a/crates/ffi/src/types/find_query.rs b/crates/ffi/src/types/find_query.rs
new file mode 100644
index 000000000..6f80efb96
--- /dev/null
+++ b/crates/ffi/src/types/find_query.rs
@@ -0,0 +1,8 @@
+use std::os::raw::c_char;
+
+#[repr(C)]
+pub struct AdFindQuery {
+ pub role: *const c_char,
+ pub name_substring: *const c_char,
+ pub value_substring: *const c_char,
+}
diff --git a/crates/ffi/src/types/image_buffer.rs b/crates/ffi/src/types/image_buffer.rs
new file mode 100644
index 000000000..f225a890c
--- /dev/null
+++ b/crates/ffi/src/types/image_buffer.rs
@@ -0,0 +1,13 @@
+use crate::types::image_format::AdImageFormat;
+
+/// Opaque image-buffer handle returned by `ad_screenshot`. The backing
+/// byte buffer and its length live inside the Rust-owned struct — a
+/// consumer cannot accidentally desynchronize the pair and trigger a
+/// heap-corruption double-free. Walk it through `ad_image_buffer_*`
+/// accessors and free it with `ad_image_buffer_free`.
+pub struct AdImageBuffer {
+ pub(crate) data: Box<[u8]>,
+ pub(crate) width: u32,
+ pub(crate) height: u32,
+ pub(crate) format: AdImageFormat,
+}
diff --git a/crates/ffi/src/types/image_format.rs b/crates/ffi/src/types/image_format.rs
new file mode 100644
index 000000000..8a4991ad3
--- /dev/null
+++ b/crates/ffi/src/types/image_format.rs
@@ -0,0 +1,6 @@
+#[repr(i32)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AdImageFormat {
+ Png = 0,
+ Jpg = 1,
+}
diff --git a/crates/ffi/src/types/key_combo.rs b/crates/ffi/src/types/key_combo.rs
new file mode 100644
index 000000000..349d37870
--- /dev/null
+++ b/crates/ffi/src/types/key_combo.rs
@@ -0,0 +1,15 @@
+use std::os::raw::c_char;
+
+/// Key combination: a named key plus optional modifier list.
+///
+/// `modifiers` points to an array of `int32_t` values (not a typed Rust
+/// enum array) so the C boundary cannot be tricked into writing an
+/// out-of-range discriminant into a Rust enum slot. Each entry is
+/// validated against `AdModifier` before use; an invalid discriminant
+/// returns `AD_RESULT_ERR_INVALID_ARGS`.
+#[repr(C)]
+pub struct AdKeyCombo {
+ pub key: *const c_char,
+ pub modifiers: *const i32,
+ pub modifier_count: u32,
+}
diff --git a/crates/ffi/src/types/mod.rs b/crates/ffi/src/types/mod.rs
new file mode 100644
index 000000000..a1ffd95eb
--- /dev/null
+++ b/crates/ffi/src/types/mod.rs
@@ -0,0 +1,73 @@
+pub mod action;
+pub mod action_kind;
+pub mod action_result;
+pub mod app_info;
+pub mod app_list;
+pub mod direction;
+pub mod drag_params;
+pub mod element_state;
+pub mod find_query;
+pub mod image_buffer;
+pub mod image_format;
+pub mod key_combo;
+pub mod modifier;
+pub mod mouse_button;
+pub mod mouse_event;
+pub mod mouse_event_kind;
+pub mod native_handle;
+pub mod node;
+pub mod node_tree;
+pub mod notification_filter;
+pub mod notification_info;
+pub mod notification_list;
+pub mod point;
+pub mod rect;
+pub mod ref_entry;
+pub mod screenshot_kind;
+pub mod screenshot_target;
+pub mod scroll_params;
+pub mod snapshot_surface;
+pub mod surface_info;
+pub mod surface_list;
+pub mod tree_options;
+pub mod window_info;
+pub mod window_list;
+pub mod window_op;
+pub mod window_op_kind;
+
+pub use action::AdAction;
+pub use action_kind::AdActionKind;
+pub use action_result::AdActionResult;
+pub use app_info::AdAppInfo;
+pub use app_list::AdAppList;
+pub use direction::AdDirection;
+pub use drag_params::AdDragParams;
+pub use element_state::AdElementState;
+pub use find_query::AdFindQuery;
+pub use image_buffer::AdImageBuffer;
+pub use image_format::AdImageFormat;
+pub use key_combo::AdKeyCombo;
+pub use modifier::AdModifier;
+pub use mouse_button::AdMouseButton;
+pub use mouse_event::AdMouseEvent;
+pub use mouse_event_kind::AdMouseEventKind;
+pub use native_handle::AdNativeHandle;
+pub use node::AdNode;
+pub use node_tree::AdNodeTree;
+pub use notification_filter::AdNotificationFilter;
+pub use notification_info::AdNotificationInfo;
+pub use notification_list::AdNotificationList;
+pub use point::AdPoint;
+pub use rect::AdRect;
+pub use ref_entry::AdRefEntry;
+pub use screenshot_kind::AdScreenshotKind;
+pub use screenshot_target::AdScreenshotTarget;
+pub use scroll_params::AdScrollParams;
+pub use snapshot_surface::AdSnapshotSurface;
+pub use surface_info::AdSurfaceInfo;
+pub use surface_list::AdSurfaceList;
+pub use tree_options::AdTreeOptions;
+pub use window_info::AdWindowInfo;
+pub use window_list::AdWindowList;
+pub use window_op::AdWindowOp;
+pub use window_op_kind::AdWindowOpKind;
diff --git a/crates/ffi/src/types/modifier.rs b/crates/ffi/src/types/modifier.rs
new file mode 100644
index 000000000..c62fdf550
--- /dev/null
+++ b/crates/ffi/src/types/modifier.rs
@@ -0,0 +1,8 @@
+#[repr(i32)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AdModifier {
+ Cmd = 0,
+ Ctrl = 1,
+ Alt = 2,
+ Shift = 3,
+}
diff --git a/crates/ffi/src/types/mouse_button.rs b/crates/ffi/src/types/mouse_button.rs
new file mode 100644
index 000000000..d961482af
--- /dev/null
+++ b/crates/ffi/src/types/mouse_button.rs
@@ -0,0 +1,7 @@
+#[repr(i32)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AdMouseButton {
+ Left = 0,
+ Right = 1,
+ Middle = 2,
+}
diff --git a/crates/ffi/src/types/mouse_event.rs b/crates/ffi/src/types/mouse_event.rs
new file mode 100644
index 000000000..fc4697989
--- /dev/null
+++ b/crates/ffi/src/types/mouse_event.rs
@@ -0,0 +1,15 @@
+use crate::types::point::AdPoint;
+
+/// Mouse event dispatched by `ad_mouse_event`.
+///
+/// `kind` and `button` are stored as `int32_t` for the same reason
+/// `AdAction.kind` is — foreign callers cannot place invalid
+/// discriminants into Rust enum slots. Valid values are the
+/// discriminants of `AdMouseEventKind` and `AdMouseButton`.
+#[repr(C)]
+pub struct AdMouseEvent {
+ pub kind: i32,
+ pub point: AdPoint,
+ pub button: i32,
+ pub click_count: u32,
+}
diff --git a/crates/ffi/src/types/mouse_event_kind.rs b/crates/ffi/src/types/mouse_event_kind.rs
new file mode 100644
index 000000000..760821986
--- /dev/null
+++ b/crates/ffi/src/types/mouse_event_kind.rs
@@ -0,0 +1,8 @@
+#[repr(i32)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AdMouseEventKind {
+ Move = 0,
+ Down = 1,
+ Up = 2,
+ Click = 3,
+}
diff --git a/crates/ffi/src/types/native_handle.rs b/crates/ffi/src/types/native_handle.rs
new file mode 100644
index 000000000..95b7873a3
--- /dev/null
+++ b/crates/ffi/src/types/native_handle.rs
@@ -0,0 +1,4 @@
+#[repr(C)]
+pub struct AdNativeHandle {
+ pub ptr: *const std::ffi::c_void,
+}
diff --git a/crates/ffi/src/types/node.rs b/crates/ffi/src/types/node.rs
new file mode 100644
index 000000000..a2f7d21ea
--- /dev/null
+++ b/crates/ffi/src/types/node.rs
@@ -0,0 +1,19 @@
+use crate::types::rect::AdRect;
+use std::os::raw::c_char;
+
+#[repr(C)]
+pub struct AdNode {
+ pub ref_id: *const c_char,
+ pub role: *const c_char,
+ pub name: *const c_char,
+ pub value: *const c_char,
+ pub description: *const c_char,
+ pub hint: *const c_char,
+ pub states: *mut *mut c_char,
+ pub state_count: u32,
+ pub bounds: AdRect,
+ pub has_bounds: bool,
+ pub parent_index: i32,
+ pub child_start: u32,
+ pub child_count: u32,
+}
diff --git a/crates/ffi/src/types/node_tree.rs b/crates/ffi/src/types/node_tree.rs
new file mode 100644
index 000000000..746b80d78
--- /dev/null
+++ b/crates/ffi/src/types/node_tree.rs
@@ -0,0 +1,7 @@
+use crate::types::node::AdNode;
+
+#[repr(C)]
+pub struct AdNodeTree {
+ pub nodes: *mut AdNode,
+ pub count: u32,
+}
diff --git a/crates/ffi/src/types/notification_filter.rs b/crates/ffi/src/types/notification_filter.rs
new file mode 100644
index 000000000..3a296eef1
--- /dev/null
+++ b/crates/ffi/src/types/notification_filter.rs
@@ -0,0 +1,9 @@
+use std::os::raw::c_char;
+
+#[repr(C)]
+pub struct AdNotificationFilter {
+ pub app: *const c_char,
+ pub text: *const c_char,
+ pub limit: u32,
+ pub has_limit: bool,
+}
diff --git a/crates/ffi/src/types/notification_info.rs b/crates/ffi/src/types/notification_info.rs
new file mode 100644
index 000000000..29650369c
--- /dev/null
+++ b/crates/ffi/src/types/notification_info.rs
@@ -0,0 +1,11 @@
+use std::os::raw::c_char;
+
+#[repr(C)]
+pub struct AdNotificationInfo {
+ pub index: u32,
+ pub app_name: *const c_char,
+ pub title: *const c_char,
+ pub body: *const c_char,
+ pub actions: *mut *mut c_char,
+ pub action_count: u32,
+}
diff --git a/crates/ffi/src/types/notification_list.rs b/crates/ffi/src/types/notification_list.rs
new file mode 100644
index 000000000..14ba200f8
--- /dev/null
+++ b/crates/ffi/src/types/notification_list.rs
@@ -0,0 +1,6 @@
+use crate::types::notification_info::AdNotificationInfo;
+
+pub struct AdNotificationList {
+ #[allow(dead_code)] // populated + read by the Unit 8 notifications module
+ pub(crate) items: Box<[AdNotificationInfo]>,
+}
diff --git a/crates/ffi/src/types/point.rs b/crates/ffi/src/types/point.rs
new file mode 100644
index 000000000..902d42825
--- /dev/null
+++ b/crates/ffi/src/types/point.rs
@@ -0,0 +1,6 @@
+#[repr(C)]
+#[derive(Debug, Clone, Copy)]
+pub struct AdPoint {
+ pub x: f64,
+ pub y: f64,
+}
diff --git a/crates/ffi/src/types/rect.rs b/crates/ffi/src/types/rect.rs
new file mode 100644
index 000000000..57de1db85
--- /dev/null
+++ b/crates/ffi/src/types/rect.rs
@@ -0,0 +1,8 @@
+#[repr(C)]
+#[derive(Debug, Clone, Copy)]
+pub struct AdRect {
+ pub x: f64,
+ pub y: f64,
+ pub width: f64,
+ pub height: f64,
+}
diff --git a/crates/ffi/src/types/ref_entry.rs b/crates/ffi/src/types/ref_entry.rs
new file mode 100644
index 000000000..fdbcbbb0a
--- /dev/null
+++ b/crates/ffi/src/types/ref_entry.rs
@@ -0,0 +1,10 @@
+use std::os::raw::c_char;
+
+#[repr(C)]
+pub struct AdRefEntry {
+ pub pid: i32,
+ pub role: *const c_char,
+ pub name: *const c_char,
+ pub bounds_hash: u64,
+ pub has_bounds_hash: bool,
+}
diff --git a/crates/ffi/src/types/screenshot_kind.rs b/crates/ffi/src/types/screenshot_kind.rs
new file mode 100644
index 000000000..357714271
--- /dev/null
+++ b/crates/ffi/src/types/screenshot_kind.rs
@@ -0,0 +1,7 @@
+#[repr(i32)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AdScreenshotKind {
+ Screen = 0,
+ Window = 1,
+ FullScreen = 2,
+}
diff --git a/crates/ffi/src/types/screenshot_target.rs b/crates/ffi/src/types/screenshot_target.rs
new file mode 100644
index 000000000..580e4552f
--- /dev/null
+++ b/crates/ffi/src/types/screenshot_target.rs
@@ -0,0 +1,12 @@
+/// Screenshot target for `ad_screenshot`.
+///
+/// `kind` is stored as `int32_t` to keep the enum-discriminant check
+/// at the boundary. Valid values are the discriminants of
+/// `AdScreenshotKind`. `screen_index` is only consulted when kind is
+/// `SCREEN`; `pid` only when kind is `WINDOW`.
+#[repr(C)]
+pub struct AdScreenshotTarget {
+ pub kind: i32,
+ pub screen_index: u64,
+ pub pid: i32,
+}
diff --git a/crates/ffi/src/types/scroll_params.rs b/crates/ffi/src/types/scroll_params.rs
new file mode 100644
index 000000000..1e876da95
--- /dev/null
+++ b/crates/ffi/src/types/scroll_params.rs
@@ -0,0 +1,10 @@
+/// Scroll parameters embedded in `AdAction` when `kind == SCROLL`.
+///
+/// `direction` is stored as `int32_t` for the same boundary-safety
+/// reason `AdAction.kind` is. Valid values are the discriminants of
+/// `AdDirection`.
+#[repr(C)]
+pub struct AdScrollParams {
+ pub direction: i32,
+ pub amount: u32,
+}
diff --git a/crates/ffi/src/types/snapshot_surface.rs b/crates/ffi/src/types/snapshot_surface.rs
new file mode 100644
index 000000000..d92504502
--- /dev/null
+++ b/crates/ffi/src/types/snapshot_surface.rs
@@ -0,0 +1,11 @@
+#[repr(i32)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AdSnapshotSurface {
+ Window = 0,
+ Focused = 1,
+ Menu = 2,
+ Menubar = 3,
+ Sheet = 4,
+ Popover = 5,
+ Alert = 6,
+}
diff --git a/crates/ffi/src/types/surface_info.rs b/crates/ffi/src/types/surface_info.rs
new file mode 100644
index 000000000..e9511bdb6
--- /dev/null
+++ b/crates/ffi/src/types/surface_info.rs
@@ -0,0 +1,8 @@
+use std::os::raw::c_char;
+
+#[repr(C)]
+pub struct AdSurfaceInfo {
+ pub kind: *const c_char,
+ pub title: *const c_char,
+ pub item_count: i64,
+}
diff --git a/crates/ffi/src/types/surface_list.rs b/crates/ffi/src/types/surface_list.rs
new file mode 100644
index 000000000..60f765b8e
--- /dev/null
+++ b/crates/ffi/src/types/surface_list.rs
@@ -0,0 +1,7 @@
+use crate::types::surface_info::AdSurfaceInfo;
+
+/// Opaque list handle emitted by `ad_list_surfaces`. See
+/// [`crate::types::window_list::AdWindowList`] for the pattern.
+pub struct AdSurfaceList {
+ pub(crate) items: Box<[AdSurfaceInfo]>,
+}
diff --git a/crates/ffi/src/types/tree_options.rs b/crates/ffi/src/types/tree_options.rs
new file mode 100644
index 000000000..42fbd82d0
--- /dev/null
+++ b/crates/ffi/src/types/tree_options.rs
@@ -0,0 +1,14 @@
+/// Options for `ad_get_tree`.
+///
+/// `surface` is stored as `int32_t` so foreign callers cannot write
+/// an invalid discriminant into a Rust enum slot. Valid values are the
+/// discriminants of `AdSnapshotSurface`; out-of-range values return
+/// `AD_RESULT_ERR_INVALID_ARGS`.
+#[repr(C)]
+pub struct AdTreeOptions {
+ pub max_depth: u8,
+ pub include_bounds: bool,
+ pub interactive_only: bool,
+ pub compact: bool,
+ pub surface: i32,
+}
diff --git a/crates/ffi/src/types/window_info.rs b/crates/ffi/src/types/window_info.rs
new file mode 100644
index 000000000..4b99aaac0
--- /dev/null
+++ b/crates/ffi/src/types/window_info.rs
@@ -0,0 +1,13 @@
+use crate::types::rect::AdRect;
+use std::os::raw::c_char;
+
+#[repr(C)]
+pub struct AdWindowInfo {
+ pub id: *const c_char,
+ pub title: *const c_char,
+ pub app_name: *const c_char,
+ pub pid: i32,
+ pub bounds: AdRect,
+ pub has_bounds: bool,
+ pub is_focused: bool,
+}
diff --git a/crates/ffi/src/types/window_list.rs b/crates/ffi/src/types/window_list.rs
new file mode 100644
index 000000000..0e40fed5f
--- /dev/null
+++ b/crates/ffi/src/types/window_list.rs
@@ -0,0 +1,13 @@
+use crate::types::window_info::AdWindowInfo;
+
+/// Opaque list handle emitted by `ad_list_windows`.
+///
+/// The struct intentionally has no `#[repr(C)]` so cbindgen emits a
+/// forward declaration only (`typedef struct AdWindowList AdWindowList;`).
+/// Consumers cannot read the backing pointer or length and cannot
+/// construct a count mismatch — they walk the list through
+/// `ad_window_list_count`, `ad_window_list_get`, and free it with
+/// `ad_window_list_free`.
+pub struct AdWindowList {
+ pub(crate) items: Box<[AdWindowInfo]>,
+}
diff --git a/crates/ffi/src/types/window_op.rs b/crates/ffi/src/types/window_op.rs
new file mode 100644
index 000000000..0f7387ccc
--- /dev/null
+++ b/crates/ffi/src/types/window_op.rs
@@ -0,0 +1,15 @@
+/// Window-manager operation dispatched by `ad_window_op`.
+///
+/// `kind` is stored as `int32_t` to keep the enum-discriminant check at
+/// the boundary — out-of-range values return
+/// `AD_RESULT_ERR_INVALID_ARGS`. Valid values are the discriminants of
+/// `AdWindowOpKind`. `width`/`height`/`x`/`y` are only consulted for
+/// the variants that use them.
+#[repr(C)]
+pub struct AdWindowOp {
+ pub kind: i32,
+ pub width: f64,
+ pub height: f64,
+ pub x: f64,
+ pub y: f64,
+}
diff --git a/crates/ffi/src/types/window_op_kind.rs b/crates/ffi/src/types/window_op_kind.rs
new file mode 100644
index 000000000..8f8d6692e
--- /dev/null
+++ b/crates/ffi/src/types/window_op_kind.rs
@@ -0,0 +1,9 @@
+#[repr(i32)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum AdWindowOpKind {
+ Resize = 0,
+ Move = 1,
+ Minimize = 2,
+ Maximize = 3,
+ Restore = 4,
+}
diff --git a/crates/ffi/src/windows/focus.rs b/crates/ffi/src/windows/focus.rs
new file mode 100644
index 000000000..482955edf
--- /dev/null
+++ b/crates/ffi/src/windows/focus.rs
@@ -0,0 +1,42 @@
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::types::AdWindowInfo;
+use crate::windows::to_core::ad_window_to_core;
+use crate::AdAdapter;
+
+/// Brings `win` to the foreground on the current space. Returns
+/// `AD_RESULT_ERR_WINDOW_NOT_FOUND` when the referenced window no longer
+/// exists (the caller should re-list and retry).
+///
+/// # Safety
+/// `adapter` must be a non-null pointer from `ad_adapter_create`. `win`
+/// must be a non-null pointer to an `AdWindowInfo` whose `id` and
+/// `title` fields are non-null, valid UTF-8 C strings.
+#[no_mangle]
+pub unsafe extern "C" fn ad_focus_window(
+ adapter: *const AdAdapter,
+ win: *const AdWindowInfo,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ crate::pointer_guard::guard_non_null!(win, c"win is null");
+ let adapter = &*adapter;
+ let core_win = match ad_window_to_core(&*win) {
+ Ok(w) => w,
+ Err(e) => {
+ set_last_error(&e);
+ return crate::error::last_error_code();
+ }
+ };
+ match adapter.inner.focus_window(&core_win) {
+ Ok(()) => AdResult::Ok,
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ }
+ })
+}
diff --git a/crates/ffi/src/windows/free_one.rs b/crates/ffi/src/windows/free_one.rs
new file mode 100644
index 000000000..7683d8624
--- /dev/null
+++ b/crates/ffi/src/windows/free_one.rs
@@ -0,0 +1,27 @@
+use crate::convert::window::free_window_info_fields;
+use crate::ffi_try::trap_panic_void;
+use crate::types::AdWindowInfo;
+
+/// Releases the heap-allocated string fields (`id`, `title`, `app_name`)
+/// inside a single `AdWindowInfo` previously written by `ad_launch_app`
+/// or returned through a list accessor. Does not free the `AdWindowInfo`
+/// struct itself — that memory is owned by the caller's stack or by the
+/// enclosing list.
+///
+/// Named `ad_release_window_fields` (not `ad_free_window`) to disambiguate
+/// from the now-removed list-free function and make the semantics clear
+/// in the header.
+///
+/// # Safety
+/// `win` must be null or point to a valid `AdWindowInfo` whose string
+/// fields were allocated by this crate. Do not call on pointers inside
+/// an `AdWindowList` — free the list instead.
+#[no_mangle]
+pub unsafe extern "C" fn ad_release_window_fields(win: *mut AdWindowInfo) {
+ trap_panic_void(|| unsafe {
+ if win.is_null() {
+ return;
+ }
+ free_window_info_fields(&mut *win);
+ })
+}
diff --git a/crates/ffi/src/windows/list.rs b/crates/ffi/src/windows/list.rs
new file mode 100644
index 000000000..93e70597f
--- /dev/null
+++ b/crates/ffi/src/windows/list.rs
@@ -0,0 +1,96 @@
+use crate::convert::string::decode_optional_filter;
+use crate::convert::window::{free_window_info_fields, window_info_to_c};
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::{trap_panic, trap_panic_void};
+use crate::types::{AdWindowInfo, AdWindowList};
+use crate::AdAdapter;
+use agent_desktop_core::adapter::WindowFilter;
+use std::os::raw::c_char;
+use std::ptr;
+
+/// # Safety
+/// `adapter` must be valid. `out` must be a valid writable
+/// `*mut *mut AdWindowList`. `app_filter` may be null or a C string.
+/// Success produces a list handle freed via `ad_window_list_free`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_list_windows(
+ adapter: *const AdAdapter,
+ app_filter: *const c_char,
+ focused_only: bool,
+ out: *mut *mut AdWindowList,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ crate::pointer_guard::guard_non_null!(out, c"out is null");
+ *out = ptr::null_mut();
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ let adapter = &*adapter;
+ let filter = WindowFilter {
+ focused_only,
+ app: decode_optional_filter!(app_filter, "app_filter"),
+ };
+ match adapter.inner.list_windows(&filter) {
+ Ok(windows) => {
+ let items: Vec<AdWindowInfo> = windows.iter().map(window_info_to_c).collect();
+ let list = Box::new(AdWindowList {
+ items: items.into_boxed_slice(),
+ });
+ *out = Box::into_raw(list);
+ AdResult::Ok
+ }
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ }
+ })
+}
+
+/// # Safety
+/// `list` must be null or a pointer returned by `ad_list_windows`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_window_list_count(list: *const AdWindowList) -> u32 {
+ if list.is_null() {
+ return 0;
+ }
+ let list_ref: &AdWindowList = unsafe { &*list };
+ list_ref.items.len() as u32
+}
+
+/// Borrow a window info entry. Null if `index` is out of range.
+///
+/// # Safety
+/// `list` must be null or a pointer returned by `ad_list_windows`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_window_list_get(
+ list: *const AdWindowList,
+ index: u32,
+) -> *const AdWindowInfo {
+ if list.is_null() {
+ return ptr::null();
+ }
+ let list_ref: &AdWindowList = unsafe { &*list };
+ match list_ref.items.get(index as usize) {
+ Some(item) => item as *const AdWindowInfo,
+ None => ptr::null(),
+ }
+}
+
+/// Frees the list and each entry's interior strings.
+///
+/// # Safety
+/// `list` must be null or a pointer returned by `ad_list_windows`.
+#[no_mangle]
+pub unsafe extern "C" fn ad_window_list_free(list: *mut AdWindowList) {
+ trap_panic_void(|| unsafe {
+ if list.is_null() {
+ return;
+ }
+ let mut list = Box::from_raw(list);
+ for item in list.items.iter_mut() {
+ free_window_info_fields(item);
+ }
+ })
+}
diff --git a/crates/ffi/src/windows/mod.rs b/crates/ffi/src/windows/mod.rs
new file mode 100644
index 000000000..f9829e738
--- /dev/null
+++ b/crates/ffi/src/windows/mod.rs
@@ -0,0 +1,7 @@
+pub(crate) mod focus;
+pub(crate) mod free_one;
+pub(crate) mod list;
+pub(crate) mod op;
+pub(crate) mod to_core;
+
+pub(crate) use to_core::ad_window_to_core;
diff --git a/crates/ffi/src/windows/op.rs b/crates/ffi/src/windows/op.rs
new file mode 100644
index 000000000..10d08cde5
--- /dev/null
+++ b/crates/ffi/src/windows/op.rs
@@ -0,0 +1,66 @@
+use crate::error::{set_last_error, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::types::{AdWindowInfo, AdWindowOp, AdWindowOpKind};
+use crate::windows::to_core::ad_window_to_core;
+use crate::AdAdapter;
+use agent_desktop_core::action::WindowOp;
+
+/// Performs a window-manager operation (`Resize`, `Move`, `Minimize`,
+/// `Maximize`, `Restore`) on `win`. Width / height / x / y are consulted
+/// only for the variants that use them; other kinds ignore them.
+///
+/// An invalid `op.kind` discriminant is rejected with
+/// `AD_RESULT_ERR_INVALID_ARGS` before any adapter call.
+///
+/// # Safety
+/// `adapter` and `win` must be non-null pointers. `win.id` and
+/// `win.title` must be non-null valid UTF-8 C strings.
+#[no_mangle]
+pub unsafe extern "C" fn ad_window_op(
+ adapter: *const AdAdapter,
+ win: *const AdWindowInfo,
+ op: AdWindowOp,
+) -> AdResult {
+ trap_panic(|| unsafe {
+ if let Err(rc) = crate::main_thread::require_main_thread() {
+ return rc;
+ }
+ crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
+ crate::pointer_guard::guard_non_null!(win, c"win is null");
+ let adapter = &*adapter;
+ let core_win = match ad_window_to_core(&*win) {
+ Ok(w) => w,
+ Err(e) => {
+ set_last_error(&e);
+ return crate::error::last_error_code();
+ }
+ };
+ let kind = match AdWindowOpKind::from_c(op.kind) {
+ Some(k) => k,
+ None => {
+ set_last_error(&agent_desktop_core::error::AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ "invalid window op kind discriminant",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+ let core_op = match kind {
+ AdWindowOpKind::Resize => WindowOp::Resize {
+ width: op.width,
+ height: op.height,
+ },
+ AdWindowOpKind::Move => WindowOp::Move { x: op.x, y: op.y },
+ AdWindowOpKind::Minimize => WindowOp::Minimize,
+ AdWindowOpKind::Maximize => WindowOp::Maximize,
+ AdWindowOpKind::Restore => WindowOp::Restore,
+ };
+ match adapter.inner.window_op(&core_win, core_op) {
+ Ok(()) => AdResult::Ok,
+ Err(e) => {
+ set_last_error(&e);
+ crate::error::last_error_code()
+ }
+ }
+ })
+}
diff --git a/crates/ffi/src/windows/to_core.rs b/crates/ffi/src/windows/to_core.rs
new file mode 100644
index 000000000..d06670c76
--- /dev/null
+++ b/crates/ffi/src/windows/to_core.rs
@@ -0,0 +1,44 @@
+use crate::convert::string::c_to_string;
+use crate::types::AdWindowInfo;
+use agent_desktop_core::error::{AdapterError, ErrorCode};
+
+/// Converts an `AdWindowInfo` from C into the core `WindowInfo`.
+///
+/// The `id` and `title` fields are mandatory in the ABI contract — null
+/// or non-UTF-8 inputs would silently coerce to an empty string and
+/// match the wrong window. The function returns `InvalidArgs` so the
+/// caller can propagate the error to the consumer instead.
+///
+/// `app_name` is allowed to be empty (some Electron apps report blank
+/// window owners) and is filled in from the platform adapter as needed.
+pub(crate) fn ad_window_to_core(
+ w: &AdWindowInfo,
+) -> Result<agent_desktop_core::node::WindowInfo, AdapterError> {
+ let id = unsafe { c_to_string(w.id) }.ok_or_else(|| {
+ AdapterError::new(ErrorCode::InvalidArgs, "window id is null or invalid UTF-8")
+ })?;
+ let title = unsafe { c_to_string(w.title) }.ok_or_else(|| {
+ AdapterError::new(
+ ErrorCode::InvalidArgs,
+ "window title is null or invalid UTF-8",
+ )
+ })?;
+ let app = unsafe { c_to_string(w.app_name) }.unwrap_or_default();
+ Ok(agent_desktop_core::node::WindowInfo {
+ id,
+ title,
+ app,
+ pid: w.pid,
+ bounds: if w.has_bounds {
+ Some(agent_desktop_core::node::Rect {
+ x: w.bounds.x,
+ y: w.bounds.y,
+ width: w.bounds.width,
+ height: w.bounds.height,
+ })
+ } else {
+ None
+ },
+ is_focused: w.is_focused,
+ })
+}
diff --git a/crates/ffi/tests/c_abi_harness.rs b/crates/ffi/tests/c_abi_harness.rs
new file mode 100644
index 000000000..26e6a8ce9
--- /dev/null
+++ b/crates/ffi/tests/c_abi_harness.rs
@@ -0,0 +1,468 @@
+//! C-ABI contract harness.
+//!
+//! Drives the FFI exactly as a C program would — raw `extern "C"`
+//! declarations with `#[allow(improper_ctypes)]` over the opaque
+//! handle types, no high-level Rust access. Exercises bug classes the
+//! inline `#[cfg(test)]` modules can't reach on their own:
+//!
+//! 1. Struct layouts that a consumer memcpy-copies (AdRect, AdAction).
+//! 2. Enum fuzzing — `int32_t` bit patterns written into enum-typed
+//! fields must not UB, must return `AD_RESULT_ERR_INVALID_ARGS`.
+//! 3. Null tolerance in the free-* family and accessor family.
+//! 4. Interior-NUL inputs funnel through `string_to_c_lossy` without
+//! returning null.
+//! 5. List handle lifecycle (count on null, _free on null, _get OOB).
+
+#![allow(improper_ctypes)]
+
+use agent_desktop_ffi::error::AdResult;
+use agent_desktop_ffi::{
+ AdAction, AdActionResult, AdAdapter, AdAppList, AdDirection, AdDragParams, AdFindQuery,
+ AdKeyCombo, AdNativeHandle, AdPoint, AdRect, AdRefEntry, AdScrollParams, AdWindowInfo,
+ AdWindowList,
+};
+use std::ffi::CStr;
+use std::os::raw::c_char;
+
+extern "C" {
+ fn ad_adapter_create() -> *mut AdAdapter;
+ fn ad_adapter_destroy(adapter: *mut AdAdapter);
+ fn ad_check_permissions(adapter: *const AdAdapter) -> AdResult;
+
+ fn ad_last_error_code() -> AdResult;
+ fn ad_last_error_message() -> *const c_char;
+
+ fn ad_list_apps(adapter: *const AdAdapter, out: *mut *mut AdAppList) -> AdResult;
+ fn ad_app_list_count(list: *const AdAppList) -> u32;
+ fn ad_app_list_get(list: *const AdAppList, index: u32) -> *const u8;
+ fn ad_app_list_free(list: *mut AdAppList);
+
+ fn ad_list_windows(
+ adapter: *const AdAdapter,
+ app_filter: *const c_char,
+ focused_only: bool,
+ out: *mut *mut AdWindowList,
+ ) -> AdResult;
+ fn ad_window_list_count(list: *const AdWindowList) -> u32;
+ fn ad_window_list_free(list: *mut AdWindowList);
+
+ fn ad_launch_app(
+ adapter: *const AdAdapter,
+ id: *const c_char,
+ timeout_ms: u64,
+ out: *mut AdWindowInfo,
+ ) -> AdResult;
+
+ fn ad_execute_action(
+ adapter: *const AdAdapter,
+ handle: *const AdNativeHandle,
+ action: *const AdAction,
+ out: *mut AdActionResult,
+ ) -> AdResult;
+
+ fn ad_find(
+ adapter: *const AdAdapter,
+ win: *const AdWindowInfo,
+ query: *const AdFindQuery,
+ out: *mut AdNativeHandle,
+ ) -> AdResult;
+
+ fn ad_free_handle(adapter: *const AdAdapter, handle: *mut AdNativeHandle) -> AdResult;
+
+ fn ad_resolve_element(
+ adapter: *const AdAdapter,
+ entry: *const AdRefEntry,
+ out: *mut AdNativeHandle,
+ ) -> AdResult;
+}
+
+fn with_adapter<F: FnOnce(*mut AdAdapter)>(body: F) {
+ unsafe {
+ let adapter = ad_adapter_create();
+ assert!(!adapter.is_null(), "ad_adapter_create must not return null");
+ body(adapter);
+ ad_adapter_destroy(adapter);
+ }
+}
+
+fn default_scroll() -> AdScrollParams {
+ AdScrollParams {
+ direction: AdDirection::Down as i32,
+ amount: 0,
+ }
+}
+
+fn default_key() -> AdKeyCombo {
+ AdKeyCombo {
+ key: std::ptr::null(),
+ modifiers: std::ptr::null(),
+ modifier_count: 0,
+ }
+}
+
+fn default_drag() -> AdDragParams {
+ AdDragParams {
+ from: AdPoint { x: 0.0, y: 0.0 },
+ to: AdPoint { x: 0.0, y: 0.0 },
+ duration_ms: 0,
+ }
+}
+
+#[test]
+fn rect_and_point_layouts_are_memcpyable() {
+ // A C consumer that does { AdRect r; memcpy(&r, src, sizeof(r)); } must
+ // see the same field values Rust wrote. Plain #[repr(C)] without
+ // padding games makes this a byte copy.
+ let rect = AdRect {
+ x: 1.25,
+ y: -2.5,
+ width: 640.0,
+ height: 480.0,
+ };
+ let copied = unsafe { std::ptr::read(&rect as *const AdRect) };
+ assert_eq!(copied.x, 1.25);
+ assert_eq!(copied.y, -2.5);
+ assert_eq!(copied.width, 640.0);
+ assert_eq!(copied.height, 480.0);
+
+ let point = AdPoint { x: 3.0, y: 4.0 };
+ let copied = unsafe { std::ptr::read(&point as *const AdPoint) };
+ assert_eq!(copied.x, 3.0);
+ assert_eq!(copied.y, 4.0);
+}
+
+#[test]
+fn enum_fuzz_invalid_discriminant_rejected() {
+ // AdAction.kind is `i32` — a buggy C caller can legally stuff any
+ // value in here. Must not UB the Rust side; the validator should
+ // surface AD_RESULT_ERR_INVALID_ARGS before any adapter code runs.
+ with_adapter(|adapter| unsafe {
+ let mut action: AdAction = std::mem::zeroed();
+ action.kind = i32::MAX;
+ action.scroll = default_scroll();
+ action.key = default_key();
+ action.drag = default_drag();
+ action.text = std::ptr::null();
+
+ let handle = AdNativeHandle {
+ ptr: std::ptr::null(),
+ };
+ let mut out: AdActionResult = std::mem::zeroed();
+ let rc = ad_execute_action(adapter, &handle, &action, &mut out);
+ // Either the enum validator rejects (expected) or the cargo-test
+ // worker thread trips the macOS main-thread assert and returns
+ // ErrInternal. Both prove the absence of UB; what matters is that
+ // the arbitrary bit pattern never results in AD_RESULT_OK.
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "arbitrary enum bit pattern must be rejected, got {:?}",
+ rc
+ );
+ });
+}
+
+#[test]
+fn null_adapter_rejected_without_ub() {
+ unsafe {
+ let mut list: *mut AdAppList = std::ptr::null_mut();
+ let rc = ad_list_apps(std::ptr::null(), &mut list);
+ // On cargo-test worker threads the macOS main-thread guard
+ // fires first (ErrInternal); on the main thread the null-adapter
+ // guard wins (ErrInvalidArgs). Either way: no dereference, no UB.
+ assert!(matches!(
+ rc,
+ AdResult::ErrInvalidArgs | AdResult::ErrInternal
+ ));
+ assert!(list.is_null(), "out-param must stay null on failure");
+
+ let rc2 = ad_check_permissions(std::ptr::null());
+ // ad_check_permissions has no main-thread guard — null adapter
+ // must hit the null-check and return InvalidArgs deterministically.
+ assert_eq!(rc2, AdResult::ErrInvalidArgs);
+ }
+}
+
+#[test]
+fn dirty_out_param_is_cleared_before_early_return_on_worker_thread() {
+ // Regression for todo 006: prior shape ran require_main_thread()
+ // *before* zeroing *out, so a worker-thread early-return left
+ // whatever the caller had in the struct. A follow-up free on that
+ // stale pointer would double-free. This test seeds the out slot
+ // with fake pointers that *must* be cleared before the fn returns.
+ with_adapter(|adapter| unsafe {
+ let fake_ptr = 0xDEAD_BEEF as *mut AdAppList;
+ let mut list: *mut AdAppList = fake_ptr;
+ let rc = ad_list_apps(adapter, &mut list);
+ // Either the main-thread guard (ErrInternal on worker) or a
+ // successful call zeroed the slot before anything else.
+ if rc != AdResult::Ok {
+ assert!(
+ list.is_null(),
+ "dirty out-param must be zeroed before early return, got {:?}",
+ list
+ );
+ }
+ });
+}
+
+#[test]
+fn invalid_utf8_filter_rejected_not_silently_widened() {
+ // Regression for todo 010: prior c_to_string conflated null with
+ // invalid UTF-8, so a non-null buffer with bogus bytes in the
+ // app_filter slot would be treated as "no filter" and widen
+ // ad_list_windows to every app on the system. Must now fail closed.
+ with_adapter(|adapter| unsafe {
+ let bad: [u8; 2] = [0xC3, 0x00];
+ let mut list: *mut AdWindowList = std::ptr::null_mut();
+ let rc = ad_list_windows(adapter, bad.as_ptr() as *const c_char, false, &mut list);
+ // Main-thread guard (ErrInternal on worker) or UTF-8 rejection
+ // (ErrInvalidArgs) — either way we do NOT produce a list by
+ // silently treating bad bytes as "no filter".
+ assert!(matches!(
+ rc,
+ AdResult::ErrInvalidArgs | AdResult::ErrInternal
+ ));
+ assert!(list.is_null());
+ });
+}
+
+#[test]
+fn null_out_param_rejected_before_write() {
+ with_adapter(|adapter| unsafe {
+ let rc = ad_list_apps(adapter, std::ptr::null_mut());
+ assert!(matches!(
+ rc,
+ AdResult::ErrInvalidArgs | AdResult::ErrInternal
+ ));
+ });
+}
+
+#[test]
+fn null_tolerance_on_list_accessors_and_free() {
+ unsafe {
+ assert_eq!(ad_app_list_count(std::ptr::null()), 0);
+ assert!(ad_app_list_get(std::ptr::null(), 0).is_null());
+ ad_app_list_free(std::ptr::null_mut());
+
+ assert_eq!(ad_window_list_count(std::ptr::null()), 0);
+ ad_window_list_free(std::ptr::null_mut());
+ }
+}
+
+#[test]
+fn list_handle_lifecycle_roundtrip() {
+ with_adapter(|adapter| unsafe {
+ let mut list: *mut AdAppList = std::ptr::null_mut();
+ let rc = ad_list_apps(adapter, &mut list);
+ // On CI without accessibility permission this may return PermDenied;
+ // both outcomes preserve the contract we're testing (no UB, valid
+ // pointer-or-null).
+ if rc == AdResult::Ok {
+ assert!(!list.is_null());
+ let count = ad_app_list_count(list);
+ // Request an index past the end — must return null, not segfault.
+ assert!(ad_app_list_get(list, count).is_null());
+ ad_app_list_free(list);
+ } else {
+ assert!(list.is_null(), "failed list call must leave out null");
+ let msg_ptr = ad_last_error_message();
+ assert!(!msg_ptr.is_null());
+ let _ = CStr::from_ptr(msg_ptr).to_string_lossy();
+ assert_eq!(ad_last_error_code(), rc);
+ }
+ });
+}
+
+#[test]
+fn list_windows_focused_only_runs() {
+ with_adapter(|adapter| unsafe {
+ let mut list: *mut AdWindowList = std::ptr::null_mut();
+ let rc = ad_list_windows(adapter, std::ptr::null(), true, &mut list);
+ if rc == AdResult::Ok {
+ assert!(!list.is_null());
+ let _ = ad_window_list_count(list);
+ ad_window_list_free(list);
+ } else {
+ assert!(list.is_null());
+ }
+ });
+}
+
+#[test]
+fn invalid_utf8_app_id_rejected() {
+ with_adapter(|adapter| unsafe {
+ // A mid-byte of a multi-byte UTF-8 sequence, not valid on its own.
+ let bad: [u8; 2] = [0xC3, 0];
+ let mut out: AdWindowInfo = std::mem::zeroed();
+ let rc = ad_launch_app(adapter, bad.as_ptr() as *const c_char, 0, &mut out);
+ // Either the UTF-8 check (ErrInvalidArgs) or the macOS main-thread
+ // guard (ErrInternal — cargo tests run on worker threads) rejects
+ // the call. Either way no UB occurred.
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "must reject without UB, got {:?}",
+ rc
+ );
+ });
+}
+
+#[test]
+fn find_returns_not_found_on_empty_query_against_no_window() {
+ with_adapter(|adapter| unsafe {
+ let bad_win: AdWindowInfo = std::mem::zeroed();
+ let query = AdFindQuery {
+ role: std::ptr::null(),
+ name_substring: std::ptr::null(),
+ value_substring: std::ptr::null(),
+ };
+ let mut handle = AdNativeHandle {
+ ptr: std::ptr::null(),
+ };
+ let rc = ad_find(adapter, &bad_win, &query, &mut handle);
+ // A zeroed window has null id/title → InvalidArgs. On cargo-test
+ // worker threads the main-thread assert trips first and returns
+ // ErrInternal. Either outcome means the FFI refused a malformed
+ // input without UB.
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "zeroed window must not succeed, got {:?}",
+ rc
+ );
+ });
+}
+
+#[test]
+fn free_handle_null_is_noop() {
+ with_adapter(|adapter| unsafe {
+ let mut handle = AdNativeHandle {
+ ptr: std::ptr::null(),
+ };
+ let rc = ad_free_handle(adapter, &mut handle);
+ assert_eq!(rc, AdResult::Ok);
+ assert!(handle.ptr.is_null());
+
+ let rc2 = ad_free_handle(adapter, std::ptr::null_mut());
+ assert_eq!(rc2, AdResult::Ok);
+ });
+}
+
+#[cfg(not(target_os = "macos"))]
+#[test]
+fn free_handle_zeroes_ptr_so_double_free_is_noop() {
+ // macOS is excluded: ad_free_handle invokes CFRelease on the
+ // underlying pointer, and a fabricated "fake live" pointer will
+ // SIGBUS before we can observe the zeroing. On Windows/Linux
+ // release_handle is NotSupported (no platform call), so the zeroing
+ // contract is safely observable with a fake pointer.
+ with_adapter(|adapter| unsafe {
+ let fake_live_ptr = 0x1234 as *const std::ffi::c_void;
+ let mut handle = AdNativeHandle { ptr: fake_live_ptr };
+
+ let _ = ad_free_handle(adapter, &mut handle);
+ assert!(handle.ptr.is_null());
+
+ let rc = ad_free_handle(adapter, &mut handle);
+ assert_eq!(rc, AdResult::Ok);
+ });
+}
+
+#[test]
+fn resolve_element_rejects_invalid_utf8_name() {
+ // Regression for todo 004: prior c_to_string(entry.name) conflated
+ // null with invalid UTF-8, so a non-null buffer with bogus bytes in
+ // the `name` slot was treated as "no name filter" and widened the
+ // re-resolution match. Must now fail closed with InvalidArgs.
+ with_adapter(|adapter| unsafe {
+ let role = std::ffi::CString::new("button").unwrap();
+ let bad_name: [u8; 2] = [0xC3, 0x00]; // partial multi-byte + NUL
+ let entry = AdRefEntry {
+ pid: 0,
+ role: role.as_ptr(),
+ name: bad_name.as_ptr() as *const c_char,
+ bounds_hash: 0,
+ has_bounds_hash: false,
+ };
+ let mut out = AdNativeHandle {
+ ptr: std::ptr::null(),
+ };
+ let rc = ad_resolve_element(adapter, &entry, &mut out);
+ // Either the UTF-8 check wins (ErrInvalidArgs) or the main-thread
+ // guard wins on worker threads (ErrInternal). Either way, no
+ // silent widening, no UB, and the out-handle stays null.
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "must reject without UB, got {:?}",
+ rc
+ );
+ assert!(out.ptr.is_null());
+ });
+}
+
+#[test]
+fn execute_action_rejects_null_handle_ptr() {
+ with_adapter(|adapter| unsafe {
+ let action = AdAction {
+ kind: 0,
+ text: std::ptr::null(),
+ scroll: AdScrollParams {
+ direction: 0,
+ amount: 0,
+ },
+ key: AdKeyCombo {
+ key: std::ptr::null(),
+ modifiers: std::ptr::null(),
+ modifier_count: 0,
+ },
+ drag: AdDragParams {
+ from: AdPoint { x: 0.0, y: 0.0 },
+ to: AdPoint { x: 0.0, y: 0.0 },
+ duration_ms: 0,
+ },
+ };
+ let handle = AdNativeHandle {
+ ptr: std::ptr::null(),
+ };
+ let mut out: AdActionResult = std::mem::zeroed();
+ let rc = ad_execute_action(adapter, &handle, &action, &mut out);
+ // Main-thread guard or null-ptr guard wins; both avoid UB and
+ // keep the struct-level handle accepted while rejecting the
+ // inner null pointer.
+ assert!(matches!(
+ rc,
+ AdResult::ErrInvalidArgs | AdResult::ErrInternal
+ ));
+ });
+}
+
+#[test]
+fn last_error_survives_successful_calls() {
+ with_adapter(|adapter| unsafe {
+ let mut out: AdWindowInfo = std::mem::zeroed();
+ let rc = ad_launch_app(adapter, std::ptr::null(), 0, &mut out);
+ // Worker-thread cargo tests hit the main-thread guard first,
+ // producing ErrInternal. Main-thread runs would see
+ // ErrInvalidArgs. What we need is that *some* failure populates
+ // last-error and its pointer stays stable across the success
+ // calls that follow.
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "must fail, got {:?}",
+ rc
+ );
+ let msg_ptr = ad_last_error_message();
+ assert!(!msg_ptr.is_null());
+
+ // Use accessors that are guaranteed to succeed and never set
+ // last-error. ad_check_permissions is NOT safe here — it can
+ // return ErrPermDenied on macOS without Accessibility permission,
+ // which overwrites the TLS error slot we're testing.
+ for _ in 0..5 {
+ let _ = ad_app_list_count(std::ptr::null());
+ let _ = ad_window_list_count(std::ptr::null());
+ }
+
+ let after = ad_last_error_message();
+ assert_eq!(msg_ptr, after);
+ assert_eq!(ad_last_error_code(), rc);
+ });
+}
diff --git a/crates/ffi/tests/c_header_compile.rs b/crates/ffi/tests/c_header_compile.rs
new file mode 100644
index 000000000..028bdc091
--- /dev/null
+++ b/crates/ffi/tests/c_header_compile.rs
@@ -0,0 +1,93 @@
+//! Verifies the committed FFI header compiles as C and that every named
+//! enum discriminant documented in the header is usable from C code. This
+//! guards against cbindgen configuration drift that would silently drop
+//! the `AdActionKind` / `AdDirection` / etc. enum blocks, forcing C
+//! consumers to hard-code numeric literals instead of AD_* constants.
+//!
+//! The test shells out to the system `cc`; it skips on platforms where
+//! that binary is not on PATH so cargo test still passes on bare CI
+//! images.
+
+use std::path::PathBuf;
+use std::process::Command;
+
+fn system_cc() -> Option<&'static str> {
+ let cc = if cfg!(target_os = "windows") {
+ "cl"
+ } else {
+ "cc"
+ };
+ Command::new(cc)
+ .arg("--version")
+ .output()
+ .ok()
+ .filter(|o| o.status.success())
+ .map(|_| cc)
+}
+
+fn header_include_dir() -> PathBuf {
+ let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
+ p.push("include");
+ p
+}
+
+#[test]
+fn committed_header_compiles_with_every_public_enum_constant() {
+ let cc = match system_cc() {
+ Some(cc) => cc,
+ None => {
+ eprintln!("skipping: system C compiler not found");
+ return;
+ }
+ };
+
+ let tmp = std::env::temp_dir().join("agent_desktop_header_abi_test.c");
+ let obj = std::env::temp_dir().join("agent_desktop_header_abi_test.o");
+ // Touch every named-constant family so a missing enum block in the
+ // header fails compilation with "undeclared identifier". Keeping the
+ // list close to cbindgen.toml's [export].include ensures they stay
+ // in sync: add an entry there, add its representative here.
+ let src = r#"
+#include <stdint.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include "agent_desktop.h"
+
+int main(void) {
+ (void)AD_ACTION_KIND_CLICK;
+ (void)AD_DIRECTION_UP;
+ (void)AD_MODIFIER_CMD;
+ (void)AD_MOUSE_BUTTON_LEFT;
+ (void)AD_MOUSE_EVENT_KIND_MOVE;
+ (void)AD_SCREENSHOT_KIND_FULL_SCREEN;
+ (void)AD_SNAPSHOT_SURFACE_WINDOW;
+ (void)AD_WINDOW_OP_KIND_RESIZE;
+ (void)AD_IMAGE_FORMAT_PNG;
+ (void)AD_RESULT_OK;
+ return 0;
+}
+"#;
+ std::fs::write(&tmp, src).expect("write test translation unit");
+
+ let include = header_include_dir();
+ let status = Command::new(cc)
+ .arg("-Wall")
+ .arg("-Werror")
+ .arg("-I")
+ .arg(&include)
+ .arg("-c")
+ .arg(&tmp)
+ .arg("-o")
+ .arg(&obj)
+ .status()
+ .expect("cc invocation failed");
+
+ let _ = std::fs::remove_file(&tmp);
+ let _ = std::fs::remove_file(&obj);
+
+ assert!(
+ status.success(),
+ "C compile of agent_desktop.h failed — a named enum constant is missing. \
+ Check crates/ffi/cbindgen.toml [export].include."
+ );
+}
diff --git a/crates/ffi/tests/error_lifetime.rs b/crates/ffi/tests/error_lifetime.rs
new file mode 100644
index 000000000..52b806b8b
--- /dev/null
+++ b/crates/ffi/tests/error_lifetime.rs
@@ -0,0 +1,53 @@
+use agent_desktop_ffi::error::AdResult;
+use std::ffi::CStr;
+
+#[allow(improper_ctypes)]
+extern "C" {
+ fn ad_adapter_create() -> *mut agent_desktop_ffi::AdAdapter;
+ fn ad_adapter_destroy(adapter: *mut agent_desktop_ffi::AdAdapter);
+ fn ad_launch_app(
+ adapter: *const agent_desktop_ffi::AdAdapter,
+ id: *const std::os::raw::c_char,
+ timeout_ms: u64,
+ out: *mut agent_desktop_ffi::AdWindowInfo,
+ ) -> AdResult;
+ fn ad_last_error_message() -> *const std::os::raw::c_char;
+ fn ad_last_error_code() -> AdResult;
+ fn ad_check_permissions(adapter: *const agent_desktop_ffi::AdAdapter) -> AdResult;
+}
+
+#[test]
+fn last_error_pointer_survives_across_successful_calls() {
+ unsafe {
+ let adapter = ad_adapter_create();
+ assert!(!adapter.is_null());
+
+ let bad_id = std::ptr::null();
+ let mut out_win: agent_desktop_ffi::AdWindowInfo = std::mem::zeroed();
+ let rc = ad_launch_app(adapter, bad_id, 0, &mut out_win);
+ // Worker-thread cargo tests hit the main-thread guard first
+ // (ErrInternal); main-thread callers would see ErrInvalidArgs.
+ // The contract we're testing here is that *some* failure
+ // populates last-error and the pointer stays stable.
+ assert!(matches!(
+ rc,
+ AdResult::ErrInvalidArgs | AdResult::ErrInternal
+ ));
+
+ let first_msg_ptr = ad_last_error_message();
+ assert!(!first_msg_ptr.is_null());
+ let first_msg = CStr::from_ptr(first_msg_ptr).to_string_lossy().into_owned();
+
+ for _ in 0..10 {
+ let _rc = ad_check_permissions(adapter);
+ }
+
+ let later_msg_ptr = ad_last_error_message();
+ assert_eq!(first_msg_ptr, later_msg_ptr);
+ let later_msg = CStr::from_ptr(later_msg_ptr).to_string_lossy().into_owned();
+ assert_eq!(first_msg, later_msg);
+ assert_eq!(ad_last_error_code(), rc);
+
+ ad_adapter_destroy(adapter);
+ }
+}
diff --git a/crates/macos/src/adapter.rs b/crates/macos/src/adapter.rs
index 1ee114e37..93b5d9ac1 100644
--- a/crates/macos/src/adapter.rs
+++ b/crates/macos/src/adapter.rs
@@ -6,7 +6,7 @@ use agent_desktop_core::{
},
error::AdapterError,
node::{AccessibilityNode, AppInfo, Rect, SurfaceInfo, WindowInfo},
- notification::{NotificationFilter, NotificationInfo},
+ notification::{NotificationFilter, NotificationIdentity, NotificationInfo},
refs::RefEntry,
};
use rustc_hash::FxHashSet;
@@ -67,6 +67,17 @@ impl PlatformAdapter for MacOSAdapter {
crate::tree::resolve::resolve_element_impl(entry)
}
+ fn release_handle(&self, handle: &NativeHandle) -> Result<(), AdapterError> {
+ let raw = handle.as_raw();
+ if raw.is_null() {
+ return Ok(());
+ }
+ unsafe {
+ core_foundation::base::CFRelease(raw as core_foundation::base::CFTypeRef);
+ }
+ Ok(())
+ }
+
fn list_windows(&self, filter: &WindowFilter) -> Result<Vec<WindowInfo>, AdapterError> {
list_windows_impl(filter)
}
@@ -201,9 +212,10 @@ impl PlatformAdapter for MacOSAdapter {
fn notification_action(
&self,
index: usize,
+ identity: Option<&NotificationIdentity>,
action_name: &str,
) -> Result<ActionResult, AdapterError> {
- crate::notifications::actions::notification_action(index, action_name)
+ crate::notifications::actions::notification_action(index, identity, action_name)
}
fn get_subtree(
diff --git a/crates/macos/src/notifications/actions.rs b/crates/macos/src/notifications/actions.rs
index 8f0c2ad92..058999772 100644
--- a/crates/macos/src/notifications/actions.rs
+++ b/crates/macos/src/notifications/actions.rs
@@ -1,7 +1,7 @@
use agent_desktop_core::{
action::ActionResult,
error::{AdapterError, ErrorCode},
- notification::{NotificationFilter, NotificationInfo},
+ notification::{NotificationFilter, NotificationIdentity, NotificationInfo},
};
use super::nc_session::NcSession;
@@ -25,9 +25,13 @@ pub fn dismiss_all(
result
}
-pub fn notification_action(index: usize, action_name: &str) -> Result<ActionResult, AdapterError> {
+pub fn notification_action(
+ index: usize,
+ identity: Option<&NotificationIdentity>,
+ action_name: &str,
+) -> Result<ActionResult, AdapterError> {
let session = NcSession::open()?;
- let result = action_impl(index, action_name);
+ let result = action_impl(index, identity, action_name);
session.close()?;
result
}
@@ -117,7 +121,11 @@ fn try_dismiss_button(children: &[crate::tree::AXElement]) -> bool {
}
#[cfg(target_os = "macos")]
-fn action_impl(index: usize, action_name: &str) -> Result<ActionResult, AdapterError> {
+fn action_impl(
+ index: usize,
+ identity: Option<&NotificationIdentity>,
+ action_name: &str,
+) -> Result<ActionResult, AdapterError> {
use crate::actions::ax_helpers::try_ax_action;
use crate::tree::{copy_ax_array, copy_string_attr};
use accessibility_sys::{kAXChildrenAttribute, kAXRoleAttribute};
@@ -130,6 +138,27 @@ fn action_impl(index: usize, action_name: &str) -> Result<ActionResult, AdapterE
.find(|e| e.info.index == index)
.ok_or_else(|| AdapterError::notification_not_found(index))?;
+ // Fingerprint check: NC may have reordered between the host's
+ // list_notifications call and now. When identity fields are
+ // provided, refuse to press an action on a row whose fingerprint
+ // doesn't match. Fail closed with NotificationNotFound so the host
+ // treats this exactly like "the notification disappeared" — which
+ // is precisely what happened from the host's perspective.
+ if let Some(id) = identity {
+ if !id.is_empty() && !id.matches(&entry.info) {
+ return Err(AdapterError::new(
+ ErrorCode::NotificationNotFound,
+ format!(
+ "Notification at index {index} does not match the expected identity (app={:?}, title={:?}); NC likely reordered",
+ id.expected_app, id.expected_title
+ ),
+ )
+ .with_suggestion(
+ "Run list-notifications again and retry with the freshly-observed index",
+ ));
+ }
+ }
+
let children = copy_ax_array(&entry.element, kAXChildrenAttribute).unwrap_or_default();
let action_lower = action_name.to_lowercase();
let action_btn = children.iter().find(|c| {
@@ -206,6 +235,10 @@ fn dismiss_all_impl(
}
#[cfg(not(target_os = "macos"))]
-fn action_impl(_index: usize, _action_name: &str) -> Result<ActionResult, AdapterError> {
+fn action_impl(
+ _index: usize,
+ _identity: Option<&NotificationIdentity>,
+ _action_name: &str,
+) -> Result<ActionResult, AdapterError> {
Err(AdapterError::not_supported("notification_action"))
}
diff --git a/docs/solutions/best-practices/deterministic-build-artifact-marker-2026-04-16.md b/docs/solutions/best-practices/deterministic-build-artifact-marker-2026-04-16.md
new file mode 100644
index 000000000..5be8316db
--- /dev/null
+++ b/docs/solutions/best-practices/deterministic-build-artifact-marker-2026-04-16.md
@@ -0,0 +1,129 @@
+---
+title: Stamp build artifacts at a deterministic path for CI and scripts
+date: 2026-04-16
+category: best-practices
+module: crates/ffi
+problem_type: best_practice
+component: tooling
+severity: medium
+applies_when:
+ - A build script (cbindgen, bindgen, codegen) writes an artifact to $OUT_DIR whose path includes a cargo-generated hash
+ - CI or a developer script needs to locate that artifact after the build finishes
+ - The obvious shell-out (`find target -path '*/out/<artifact>' | head -1`) silently picks the wrong file when multiple cached build dirs coexist
+ - You want a drift check (`diff committed_copy generated_copy`) that reliably fails when the committed copy is stale
+tags:
+ - build-rs
+ - cbindgen
+ - ci
+ - reproducibility
+ - determinism
+ - cargo
+ - rust-patterns
+---
+
+## Problem
+
+Cargo puts build-script artifacts under a hash-randomized directory:
+
+```
+target/<profile>/build/<crate-name>-<hash>/out/<artifact>
+```
+
+The `<hash>` is not documented, not stable across rebuilds of the same
+code on different toolchain minor versions, and you can end up with
+several `<crate-name>-<hash>/` dirs in the same warm `target/` cache
+(e.g. after a `cargo clean -p` and rebuild, or rustup flip). Any CI
+step or developer script that resolves the artifact with
+`find target -path '.../<artifact>' | head -1` is picking arbitrarily
+among those dirs. Under drift check:
+
+- If `head -1` picks the current build's artifact → drift correctly
+ surfaces when the committed copy is stale.
+- If `head -1` picks a stale leftover → you either self-heal (false
+ green) or report stale-vs-stale (useless).
+
+The failure mode is silent: a CI step says "OK: header in sync" while
+the committed header is actually out of date, and the bad ABI ships.
+
+## Solution
+
+Have `build.rs` write a stable marker file containing the absolute path
+of the just-generated artifact. Downstream consumers read the marker
+instead of guessing:
+
+```rust
+// crates/<your-crate>/build.rs
+fn main() {
+ // ... generate $OUT_DIR/artifact ...
+
+ if let Some(target_root) = target_root_from_out_dir(Path::new(&out_dir)) {
+ let stamp = target_root.join("ffi-header-path.txt");
+ let _ = std::fs::write(&stamp, out_path.to_string_lossy().as_bytes());
+ }
+}
+
+/// OUT_DIR = {target}/{profile}/build/{pkg-hash}/out
+fn target_root_from_out_dir(out_dir: &Path) -> Option<PathBuf> {
+ let mut current = out_dir;
+ for _ in 0..4 {
+ current = current.parent()?;
+ }
+ Some(current.to_path_buf())
+}
+```
+
+CI and scripts read the marker:
+
+```yaml
+- name: Drift check
+ run: |
+ STAMP=target/ffi-header-path.txt
+ test -f "$STAMP" || { echo "FAIL: stamp missing"; exit 1; }
+ GENERATED=$(cat "$STAMP")
+ test -f "$GENERATED" || { echo "FAIL: stamped path missing"; exit 1; }
+ diff -u crates/ffi/include/artifact.h "$GENERATED"
+```
+
+## Why this works
+
+- **One writer**: the build script's own invocation knows exactly which
+ `OUT_DIR` it ran in. Stamping the path at that moment captures it
+ authoritatively; no later tool has to reconstruct it.
+- **Stable path**: `target/<marker>.txt` lives one directory above the
+ hashed build dirs and is overwritten each build. CI's cache system
+ sees it as content of `target/` — no special allowlisting needed.
+- **Fail-fast wrapper**: the marker file's absence is itself a signal
+ that the build script didn't run (e.g. `cargo check` instead of
+ `cargo build`). CI should fail rather than fall back to a wrong
+ default.
+
+## When NOT to use this
+
+- If your build script generates artifacts deterministically **at a
+ fixed location outside `OUT_DIR`** (e.g. directly into a committed
+ dir), you don't need a marker — the path itself is stable.
+- If the artifact lifecycle is driven by `cargo metadata` queries
+ (e.g. `cargo metadata --format-version=1 | jq .target_directory`),
+ that's already deterministic. Stamping is only needed when the
+ specific pkg-hash subdirectory matters.
+
+## Sibling anti-pattern to avoid
+
+Do **not** have `build.rs` copy the generated artifact into the source
+tree (e.g. `fs::copy(&out_path, &committed_path)`). That mutates the
+working tree during every build, which means:
+
+- `git diff` is polluted by invisible copies.
+- The drift check (`git diff --exit-code committed_path`) can
+ self-heal a stale committed copy instead of catching it.
+
+The committed copy is the ABI contract; updating it should be an
+explicit developer action (dedicated script) or CI-only step.
+
+## References
+
+- `crates/ffi/build.rs` — the stamping logic
+- `.github/workflows/ci.yml` — "FFI header drift check" step
+- `scripts/update-ffi-header.sh` — developer-facing refresh script
+- Todo `006-ready-p2-deterministic-ffi-header-drift-path` — the bug this
+ pattern resolves
diff --git a/docs/solutions/best-practices/identity-fingerprint-against-os-reorder-2026-04-16.md b/docs/solutions/best-practices/identity-fingerprint-against-os-reorder-2026-04-16.md
new file mode 100644
index 000000000..31d93f140
--- /dev/null
+++ b/docs/solutions/best-practices/identity-fingerprint-against-os-reorder-2026-04-16.md
@@ -0,0 +1,135 @@
+---
+title: Guard OS-reordered resources with an identity fingerprint, not a raw index
+date: 2026-04-16
+category: best-practices
+module: crates/core, crates/macos, crates/ffi
+problem_type: best_practice
+component: notifications
+severity: high
+applies_when:
+ - The API exposes a numeric index (or handle) obtained from a list-then-act flow
+ - The underlying OS can reorder, add, or remove entries between the list and act calls
+ - Acting on the wrong entry has user-visible consequences (Reply to the wrong sender, Dismiss the wrong notification, Press the wrong button)
+ - Existing design assumed lists are stable across calls and did not re-verify
+tags:
+ - notification-center
+ - confused-deputy
+ - fingerprint
+ - identity
+ - ffi
+ - reordering
+ - fail-closed
+---
+
+## Problem
+
+macOS Notification Center reassigns the `index` of every visible
+notification on each listing. Between `list_notifications()` and
+`notification_action(index, ...)`:
+
+- a new notification arrives → everything shifts down by 1
+- an unrelated notification is dismissed → everything shifts up by 1
+- the user opens the Notification Center sidebar → grouping changes
+ can renumber entries entirely
+
+Any tool that round-trips `(app, title) → index → "press Reply"` is a
+**confused deputy** at the OS boundary: the tool thinks it's acting on
+the notification it showed to the user, but by the time the action
+call reaches NC the slot points elsewhere.
+
+This class of bug exists for any OS API that:
+
+- returns an ordered list whose ordering is defined by "current state",
+ not by a stable identity
+- accepts an index (or some other positional handle) as a subsequent
+ parameter
+
+Examples beyond NC: running-process lists by PID reuse, window lists
+after `raise()`, clipboard history, filesystem listings used for bulk
+operations.
+
+## Solution
+
+Pass an optional identity fingerprint alongside the index. Verify the
+row at that index against the fingerprint **before** acting. Fail
+closed if it doesn't match.
+
+```rust
+pub struct NotificationIdentity {
+ pub expected_app: Option<String>,
+ pub expected_title: Option<String>,
+}
+
+impl NotificationIdentity {
+ pub fn matches(&self, info: &NotificationInfo) -> bool {
+ if let Some(ref app) = self.expected_app {
+ if app != &info.app_name { return false; }
+ }
+ if let Some(ref title) = self.expected_title {
+ if title != &info.title { return false; }
+ }
+ true
+ }
+}
+```
+
+Adapter layer:
+
+```rust
+let entry = list_entries(&filter)?.into_iter()
+ .find(|e| e.info.index == index)
+ .ok_or_else(|| AdapterError::notification_not_found(index))?;
+
+if let Some(id) = identity {
+ if !id.is_empty() && !id.matches(&entry.info) {
+ return Err(AdapterError::new(
+ ErrorCode::NotificationNotFound,
+ "row at this index does not match the expected fingerprint — NC likely reordered",
+ ));
+ }
+}
+
+// safe to press
+```
+
+## Design choices
+
+**Optional fields, not mandatory.** The fingerprint is a safety feature,
+not a required parameter. Hosts that already reconcile (e.g. by
+re-listing just before acting) can leave both fields null and get
+the legacy behavior. This keeps the API ergonomic for simple scripts
+while making the safe path available.
+
+**Re-use an existing error code** (`NotificationNotFound`) rather than
+adding a new one. From the host's perspective, "the notification I
+intended to act on is gone or moved" is semantically the same as "the
+notification at that index disappeared": in both cases the right
+recovery is re-list and retry. Introducing a distinct
+`IDENTITY_MISMATCH` code would fork callers' error handling without a
+real behavioral difference.
+
+**Tri-state UTF-8 decoding at the FFI boundary.** The identity strings
+come in as `*const c_char`. Null means "no fingerprint"; invalid UTF-8
+must NOT be silently coerced to "no fingerprint" (that would defeat
+the guard). Use `try_c_to_string` which returns
+`Ok(None)` / `Ok(Some(_))` / `Err(())` and map `Err` to
+`InvalidArgs`.
+
+## When NOT to use this
+
+- If the OS API returns a stable opaque handle that the caller can
+ hold across calls (e.g. `HWND` on Windows), plumb the handle
+ through instead of an index. Fingerprinting is a fallback for
+ APIs whose handles we can't or shouldn't persist.
+- If the operation is idempotent and harmless (e.g. "list children
+ of this group"), mismatch handling adds cost without value.
+
+## References
+
+- `crates/core/src/notification.rs` — `NotificationIdentity` type and
+ tests
+- `crates/macos/src/notifications/actions.rs` — adapter-layer check
+- `crates/ffi/src/notifications/action.rs` — C-ABI surface with
+ optional app/title pointers
+- Todo `003-ready-p1-stable-notification-action-identity` — the bug
+ this pattern resolves
diff --git a/scripts/update-ffi-header.sh b/scripts/update-ffi-header.sh
new file mode 100755
index 000000000..299e48172
--- /dev/null
+++ b/scripts/update-ffi-header.sh
@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# Regenerate the committed FFI header from source.
+#
+# Run this after changing any `#[no_mangle] pub extern "C"` signatures in
+# crates/ffi/src/ and commit the result. build.rs stamps the absolute path
+# to the generated header at target/ffi-header-path.txt so we never have to
+# guess which of several cached `agent-desktop-ffi-<hash>/` build dirs is
+# current — `find target | head -1` would pick arbitrarily.
+
+ROOT=$(git rev-parse --show-toplevel)
+cd "$ROOT"
+
+cargo build -p agent-desktop-ffi >/dev/null 2>&1
+
+STAMP=target/ffi-header-path.txt
+if [ ! -f "$STAMP" ]; then
+ echo "ERROR: $STAMP was not produced by build.rs. Check the build output." >&2
+ exit 1
+fi
+
+GENERATED=$(cat "$STAMP")
+if [ ! -f "$GENERATED" ]; then
+ echo "ERROR: stamped header path does not exist: $GENERATED" >&2
+ exit 1
+fi
+
+cp "$GENERATED" crates/ffi/include/agent_desktop.h
+echo "Updated crates/ffi/include/agent_desktop.h"
diff --git a/skills/agent-desktop-ffi/SKILL.md b/skills/agent-desktop-ffi/SKILL.md
new file mode 100644
index 000000000..da0c92542
--- /dev/null
+++ b/skills/agent-desktop-ffi/SKILL.md
@@ -0,0 +1,78 @@
+---
+name: agent-desktop-ffi
+version: 0.1.11
+tags: ffi, c-bindings, cdylib, python, swift, node, go, rust-ffi
+requirements:
+ - agent-desktop-ffi
+description: >
+ C-ABI bindings over agent-desktop's PlatformAdapter. Consumers
+ (Python ctypes, Swift, Node ffi-napi, Go cgo, C++, Ruby fiddle)
+ link libagent_desktop_ffi.{dylib,so,dll} and call `ad_*` functions
+ directly instead of spawning the CLI binary per call.
+---
+
+# agent-desktop-ffi
+
+Direct C-ABI access to every PlatformAdapter operation. Build the
+cdylib with the workspace's `release-ffi` profile:
+
+```sh
+cargo build --profile release-ffi -p agent-desktop-ffi
+```
+
+The output is `target/release-ffi/libagent_desktop_ffi.dylib`
+(`.so` on Linux, `.dll` on Windows) plus a committed C header at
+`crates/ffi/include/agent_desktop.h`.
+
+Four reference topics, loaded as needed:
+
+- [ownership.md](references/ownership.md) — who allocates / who frees,
+ for every `*mut T` the FFI hands back to the caller.
+- [error-handling.md](references/error-handling.md) — errno-style
+ last-error contract, enum validation, panic boundary.
+- [threading.md](references/threading.md) — macOS main-thread rule,
+ AXIsProcessTrusted inheritance when Python/Node dlopens the cdylib,
+ and the single-owner handle invariant.
+- [build-and-link.md](references/build-and-link.md) — minimum working
+ example for Python ctypes and a C program that links the dylib.
+
+## ⚠ Core constraints before you integrate
+
+- **Main thread only (macOS).** Call every adapter-touching entrypoint
+ (`ad_get_tree`, `ad_resolve_element`, `ad_execute_action`,
+ `ad_screenshot`, clipboard, launch/close, window ops, observation,
+ notifications, etc.) from the process's main thread. The FFI enforces
+ this at runtime in **every build profile** — a worker-thread call
+ returns `AD_RESULT_ERR_INTERNAL` with a diagnostic last-error. On
+ non-macOS platforms the check is a compile-time true; there is no
+ runtime cost.
+
+- **Release profile.** `cargo build --release` produces
+ `panic = "abort"` — any Rust panic inside an `extern "C"` fn will
+ `SIGABRT` the host. Use `--profile release-ffi` to get the correct
+ `panic = "unwind"` profile. CI enforces this.
+
+- **Last-error lifetime.** Pointers returned by `ad_last_error_*`
+ remain valid across any number of subsequent *successful* FFI calls
+ on the same thread. Only the next failing call rotates them. Cache
+ the pointer once, read it as many times as you need.
+
+- **Handle release.** Every `ad_resolve_element` result must be
+ released with `ad_free_handle(adapter, handle)` on the same adapter
+ that produced it. On macOS this balances the internal `CFRetain`;
+ on Windows/Linux the call is a no-op but safe to issue.
+
+- **Enum discriminants.** Every `#[repr(i32)]` enum field is validated
+ at the C boundary — invalid discriminants return
+ `AD_RESULT_ERR_INVALID_ARGS` instead of undefined behavior.
+
+- **ABI is unstable before 1.0.** The header lists the exact current
+ shapes. Anything added or reordered in a later patch is a breaking
+ change; pin the version of libagent_desktop_ffi you link against.
+
+- **`ad_get_tree` returns a raw adapter tree, not the CLI snapshot.**
+ Ref IDs are always null, no skeleton/drill-down pipeline is wired
+ through, and `interactive_only` / `compact` follow adapter
+ semantics which may diverge slightly from the CLI's post-processed
+ shape. Use `ad_find` + `ad_get` / `ad_is` for point lookups, or
+ invoke the CLI if you need CLI-parity JSON snapshots.
diff --git a/skills/agent-desktop-ffi/references/build-and-link.md b/skills/agent-desktop-ffi/references/build-and-link.md
new file mode 100644
index 000000000..fae1594af
--- /dev/null
+++ b/skills/agent-desktop-ffi/references/build-and-link.md
@@ -0,0 +1,100 @@
+# Build and link
+
+## Building the cdylib
+
+```sh
+cargo build --profile release-ffi -p agent-desktop-ffi
+```
+
+Output:
+
+- macOS: `target/release-ffi/libagent_desktop_ffi.dylib` (~470 KB)
+- Linux: `target/release-ffi/libagent_desktop_ffi.so`
+- Windows: `target/release-ffi/agent_desktop_ffi.dll`
+
+The generated header is at `crates/ffi/include/agent_desktop.h`.
+CI validates that the committed header matches what `cargo build`
+regenerates — if you change a type in `crates/ffi/src/`, rebuild
+locally and commit the header.
+
+## Minimal C example
+
+```c
+#include <stdio.h>
+#include "agent_desktop.h"
+
+int main(void) {
+ AdAdapter *adapter = ad_adapter_create();
+ if (!adapter) return 1;
+
+ AdResult rc = ad_check_permissions(adapter);
+ if (rc != AD_RESULT_OK) {
+ fprintf(stderr, "permission denied: %s\n", ad_last_error_message());
+ ad_adapter_destroy(adapter);
+ return 1;
+ }
+
+ /* Opaque list handle — walk via _count / _get, free with _free. */
+ AdAppList *list = NULL;
+ rc = ad_list_apps(adapter, &list);
+ if (rc == AD_RESULT_OK) {
+ uint32_t count = ad_app_list_count(list);
+ for (uint32_t i = 0; i < count; i++) {
+ const AdAppInfo *app = ad_app_list_get(list, i);
+ if (app) {
+ printf("%s (pid %d)\n", app->name, app->pid);
+ }
+ }
+ ad_app_list_free(list);
+ } else {
+ fprintf(stderr, "list_apps failed: %s\n", ad_last_error_message());
+ }
+
+ ad_adapter_destroy(adapter);
+ return 0;
+}
+```
+
+Compile:
+
+```sh
+clang -I./crates/ffi/include main.c \
+ -L./target/release-ffi -lagent_desktop_ffi \
+ -o list_apps
+install_name_tool -change \
+ libagent_desktop_ffi.dylib \
+ @executable_path/target/release-ffi/libagent_desktop_ffi.dylib \
+ list_apps
+```
+
+## Minimal Python ctypes example
+
+```python
+import ctypes
+from ctypes import c_int32, c_char_p, POINTER, Structure, c_uint32
+
+lib = ctypes.CDLL("./target/release-ffi/libagent_desktop_ffi.dylib")
+
+# Opaque adapter handle
+class AdAdapter(ctypes.Structure):
+ pass
+
+lib.ad_adapter_create.restype = POINTER(AdAdapter)
+lib.ad_adapter_destroy.argtypes = [POINTER(AdAdapter)]
+lib.ad_check_permissions.restype = c_int32
+lib.ad_check_permissions.argtypes = [POINTER(AdAdapter)]
+lib.ad_last_error_message.restype = c_char_p
+
+adapter = lib.ad_adapter_create()
+rc = lib.ad_check_permissions(adapter)
+if rc != 0:
+ msg = lib.ad_last_error_message()
+ print("permission denied:", msg.decode() if msg else "(no message)")
+lib.ad_adapter_destroy(adapter)
+```
+
+## Call graph reminder
+
+All FFI calls above must run on the **main thread** on macOS. For
+Python that typically means the script's entry point, not a worker
+spawned via `threading`. See [threading.md](threading.md).
diff --git a/skills/agent-desktop-ffi/references/error-handling.md b/skills/agent-desktop-ffi/references/error-handling.md
new file mode 100644
index 000000000..777db03d7
--- /dev/null
+++ b/skills/agent-desktop-ffi/references/error-handling.md
@@ -0,0 +1,81 @@
+# Error handling
+
+The FFI uses an errno-style last-error pattern. Every `AdResult`-returning
+function returns `AD_RESULT_OK` (= 0) on success or a negative error
+code on failure. When a failure occurs, thread-local last-error state is
+populated; read it with the `ad_last_error_*` accessors.
+
+## Minimal pattern
+
+```c
+AdResult rc = ad_launch_app(adapter, "com.apple.finder", 5000, &win);
+if (rc != AD_RESULT_OK) {
+ const char *msg = ad_last_error_message();
+ const char *sug = ad_last_error_suggestion(); // may be NULL
+ fprintf(stderr, "launch_app failed (%d): %s\n", (int)rc, msg ? msg : "(no message)");
+ if (sug) fprintf(stderr, " suggestion: %s\n", sug);
+ // no need to release the struct — out-param was zero-initialized
+ return -1;
+}
+// ...use win...
+ad_release_window_fields(&win);
+```
+
+## Lifetime contract
+
+The pointer returned by `ad_last_error_message()`,
+`ad_last_error_suggestion()`, and `ad_last_error_platform_detail()`
+remains valid across any number of subsequent **successful** FFI calls.
+Only the next **failing** call rotates the slot.
+
+Consequence: you can cache the pointer right after a failure and keep
+reading it until the next failure — equivalent to POSIX `errno` /
+`strerror`.
+
+```c
+AdResult rc = ad_some_call(...);
+const char *msg = ad_last_error_message(); // snapshot
+
+ad_check_permissions(adapter); // success
+ad_check_permissions(adapter); // success
+printf("%s\n", msg); // still valid
+```
+
+Failure-path calls rotate: if a subsequent call fails, the prior
+pointer may dangle. Read it before the next potentially-failing call.
+
+## Error codes
+
+| Name | i32 | Meaning |
+|--------------------------------------|-------|---------------------------------------|
+| `AD_RESULT_OK` | 0 | Success |
+| `AD_RESULT_ERR_PERM_DENIED` | -1 | Accessibility / input permission missing |
+| `AD_RESULT_ERR_ELEMENT_NOT_FOUND` | -2 | Ref resolve / find miss |
+| `AD_RESULT_ERR_APP_NOT_FOUND` | -3 | Bundle/PID lookup miss |
+| `AD_RESULT_ERR_ACTION_FAILED` | -4 | Action dispatched but rejected |
+| `AD_RESULT_ERR_ACTION_NOT_SUPPORTED` | -5 | Platform cannot perform this action |
+| `AD_RESULT_ERR_STALE_REF` | -6 | Handle pre-dates a DOM change |
+| `AD_RESULT_ERR_WINDOW_NOT_FOUND` | -7 | Window filter matched nothing |
+| `AD_RESULT_ERR_PLATFORM_NOT_SUPPORTED`| -8 | API unavailable on this OS |
+| `AD_RESULT_ERR_TIMEOUT` | -9 | Wait exceeded deadline |
+| `AD_RESULT_ERR_INVALID_ARGS` | -10 | Null pointer, bad enum, invalid UTF-8 |
+| `AD_RESULT_ERR_NOTIFICATION_NOT_FOUND`| -11 | Notification index out of range |
+| `AD_RESULT_ERR_INTERNAL` | -12 | Rust panic caught at FFI boundary |
+
+## Enum validation
+
+Every `#[repr(i32)]` enum field is validated at the C boundary. An
+out-of-range discriminant returns `AD_RESULT_ERR_INVALID_ARGS` with
+diagnostic last-error text. This prevents the consumer from
+accidentally triggering undefined behavior by stuffing an arbitrary
+`int32_t` into an enum slot.
+
+## Panic safety
+
+Every `extern "C"` entrypoint wraps its body in `catch_unwind`. A
+Rust panic inside the FFI surfaces as `AD_RESULT_ERR_INTERNAL` with
+message `"rust panic in FFI boundary"`. No `SIGABRT`, no host crash.
+
+The cdylib must be built under the `release-ffi` profile for this
+guarantee to hold in optimized builds — the workspace `release` profile
+uses `panic = "abort"` (for CLI binary-size reasons).
diff --git a/skills/agent-desktop-ffi/references/ownership.md b/skills/agent-desktop-ffi/references/ownership.md
new file mode 100644
index 000000000..09ca71a5d
--- /dev/null
+++ b/skills/agent-desktop-ffi/references/ownership.md
@@ -0,0 +1,66 @@
+# Pointer ownership
+
+Every `*mut T` / `*const T` returned by the FFI comes with a matching
+free function. Always call it; the allocator the FFI uses is Rust's
+`Box::from_raw` / `CString::from_raw`, which cannot be freed with C's
+`free()`.
+
+## Allocation / release table
+
+| Allocates | Frees with |
+|---------------------------------------------------------|-----------------------------------------|
+| `ad_adapter_create()` | `ad_adapter_destroy(adapter)` |
+| `ad_list_apps(adapter, &list)` | `ad_app_list_free(list)` |
+| `ad_list_windows(adapter, app, focused, &list)` | `ad_window_list_free(list)` |
+| `ad_list_surfaces(adapter, pid, &list)` | `ad_surface_list_free(list)` |
+| `ad_list_notifications(adapter, filter, &list)` | `ad_notification_list_free(list)` |
+| `ad_dismiss_all_notifications(adapter, f, &ok, &fail)` | `ad_notification_list_free` on each (or `ad_dismiss_all_notifications_free(ok, fail)`) |
+| `ad_launch_app(adapter, id, timeout, &out)` | `ad_release_window_fields(&out)` (free interior strings; struct itself lives on caller's stack) |
+| `ad_get_tree(adapter, win, opts, &out)` | `ad_free_tree(&out)` |
+| `ad_resolve_element(adapter, entry, &handle)` | `ad_free_handle(adapter, &handle)` — `*mut AdNativeHandle`; the call zeroes `handle.ptr` on success so a follow-up call is a no-op |
+| `ad_find(adapter, win, query, &handle)` | same as `ad_resolve_element` |
+| `ad_execute_action(adapter, handle, action, &out)` | `ad_free_action_result(&out)` |
+| `ad_notification_action(adapter, idx, expected_app, expected_title, name, &out)` | `ad_free_action_result(&out)` — pass the `app_name`/`title` you observed in `ad_list_notifications` (either may be null) so NC reorder between list and press is caught with `ERR_NOTIFICATION_NOT_FOUND` instead of pressing a different notification |
+| `ad_screenshot(adapter, target, &buf)` | `ad_image_buffer_free(buf)` (buf is opaque; read via `ad_image_buffer_{data,size,width,height,format}`) |
+| `ad_get_clipboard(adapter, &text)` | `ad_free_string(text)` |
+| `ad_get(adapter, handle, property, &text)` | `ad_free_string(text)` (text may be null on "property absent"; `ad_free_string(NULL)` is a no-op) |
+
+## Rules
+
+- Every free function is **null-tolerant**. `ad_free_tree(NULL)`,
+ `ad_free_handle(adapter, NULL)`, `ad_free_string(NULL)`, etc. are
+ no-ops. List accessors (`ad_*_list_count`, `_get`) also accept null
+ and return `0` / `NULL` respectively.
+- **Double-free of list handles and `AdImageBuffer` is undefined.** The
+ opaque wrappers are allocated by `Box::into_raw`; the second call
+ would invoke `Box::from_raw` on a freed allocation. Always set the
+ pointer to `NULL` after freeing.
+- **`ad_free_handle` is safe to double-call** — it zeroes
+ `handle.ptr` after the platform release, so a follow-up call sees
+ `NULL` and returns `AD_RESULT_OK` without re-entering `CFRelease`.
+- Pointers inside a struct (`.id`, `.title`, `.app_name`, each
+ `AdNotificationInfo.body`, etc.) are freed by the struct's owning
+ free function (list_free / release_fields) — do not
+ `ad_free_string()` them individually.
+- Ownership does **not** transfer back to Rust after you free. Keep a
+ local `NULL` to prevent accidental reuse.
+
+## Out-param zeroing
+
+Every fallible FFI function zeroes its out-param **before** any guard
+(pointer validation, main-thread check, UTF-8 validation). On error,
+calling the paired free function is safe: all pointers inside are
+guaranteed null, all counts zero, so the free is a no-op rather than
+a double-free on a previous caller's allocation.
+
+In particular:
+
+- `ad_get_clipboard` writes `*out = NULL` before the adapter call —
+ no stale buffer visible on error.
+- `ad_launch_app` writes `*out = zeroed AdWindowInfo` before the
+ platform call — `ad_release_window_fields(&out)` on the zero-init
+ struct is a no-op.
+- `ad_screenshot` writes `*out = NULL` before allocating the image
+ buffer — no stale pointer when the screenshot fails.
+- `ad_*_list` and `ad_resolve_element` / `ad_find` all apply the same
+ pattern to their handle / list out-params.
diff --git a/skills/agent-desktop-ffi/references/threading.md b/skills/agent-desktop-ffi/references/threading.md
new file mode 100644
index 000000000..1cb778f96
--- /dev/null
+++ b/skills/agent-desktop-ffi/references/threading.md
@@ -0,0 +1,76 @@
+# Threading
+
+## macOS: main-thread rule
+
+Every adapter-touching entrypoint (`ad_get_tree`, `ad_find`, `ad_get`,
+`ad_is`, `ad_resolve_element`, `ad_execute_action`, `ad_screenshot`,
+clipboard get/set/clear, mouse, drag, launch, close, focus, window-op,
+list-apps/windows/surfaces, notification list/dismiss/action)
+**must be invoked on the process's main thread**. macOS accessibility
+and Cocoa APIs require this.
+
+The check runs at **runtime, in every build profile** — worker-thread
+calls return `AD_RESULT_ERR_INTERNAL` with a `'static` diagnostic
+`"agent_desktop FFI entry called off the main thread (macOS requires
+main-thread AX/Cocoa calls)"`. No build-config difference; no silent
+UB window in release builds.
+
+On non-macOS targets the check is a compile-time `true` and has zero
+runtime cost.
+
+Operations that are **safe off-main-thread** (no runtime guard):
+
+- `ad_adapter_create` / `ad_adapter_destroy`
+- `ad_last_error_{code,message,suggestion,platform_detail}`
+- `ad_check_permissions` (pure process-wide query)
+- `ad_app_list_count` / `_get` / `_free`
+- `ad_window_list_count` / `_get` / `_free`
+- `ad_surface_list_count` / `_get` / `_free`
+- `ad_notification_list_count` / `_get` / `_free`
+- `ad_image_buffer_data` / `_size` / `_width` / `_height` / `_format` / `_free`
+- `ad_release_window_fields`
+- `ad_free_handle` (invokes `CFRelease` which is thread-safe) — but
+ still prefer calling from the thread that produced the handle.
+- `ad_free_tree`, `ad_free_action_result`, `ad_free_string`
+
+## Python consumers
+
+CPython's GIL serializes calls but does not pin them to the main
+thread. If you're calling from anything other than the main interpreter
+thread you will silently corrupt state on macOS.
+
+Two patterns work:
+
+1. **Restrict FFI calls to the main thread.** Use `asyncio` with the
+ default event loop pinned to main, or a synchronous entrypoint only.
+2. **Marshal across threads yourself.** Use a queue; have a dedicated
+ main-thread worker that dequeues and invokes the FFI.
+
+## AXIsProcessTrusted inheritance
+
+⚠ **Privilege-escalation vector.** `ad_check_permissions` calls macOS's
+`AXIsProcessTrusted()`, which returns the trust status of the **hosting
+executable** — i.e., the `python3` / `node` / `swift` process, not
+`agent-desktop` itself.
+
+Consequence: granting accessibility permission to one Python script's
+Python interpreter grants it to every Python script that dlopens
+`libagent_desktop_ffi.dylib`. Document this prominently for your
+consumers; consider requiring opt-in permission prompts in host code
+rather than relying on macOS's binary-level grant.
+
+## Thread-ownership of handles
+
+`ad_resolve_element` returns an opaque `AdNativeHandle` that wraps a
+platform pointer. The handle is **single-owner, single-thread** by FFI
+contract:
+
+- Create it on thread A → free it on thread A with `ad_free_handle`.
+ Transferring the handle to thread B is undefined behavior.
+- Use it in FFI calls only from the same thread that produced it.
+
+## Last-error is thread-local
+
+Every thread has its own last-error slot. Thread A's failure does not
+set thread B's last-error; `ad_last_error_*` accessors always see the
+calling thread's state.
diff --git a/skills/agent-desktop/SKILL.md b/skills/agent-desktop/SKILL.md
index 604b1baad..eee960b23 100644
--- a/skills/agent-desktop/SKILL.md
+++ b/skills/agent-desktop/SKILL.md
@@ -183,7 +183,7 @@ agent-desktop list-notifications --text "deploy" --limit 5 # Filter by text
agent-desktop dismiss-notification 1 # Dismiss by index
agent-desktop dismiss-all-notifications # Dismiss all
agent-desktop dismiss-all-notifications --app "Slack" # Dismiss all from app
-agent-desktop notification-action 1 --action "Reply" # Click action button
+agent-desktop notification-action 1 "Reply" --expected-app Slack # Click action (with NC reorder guard)
```
### Clipboard
diff --git a/skills/agent-desktop/references/commands-system.md b/skills/agent-desktop/references/commands-system.md
index b29b7ac5f..efb55cfa8 100644
--- a/skills/agent-desktop/references/commands-system.md
+++ b/skills/agent-desktop/references/commands-system.md
@@ -111,15 +111,26 @@ Returns `{ "dismissed_count": N, "failures": [...], "failed_count": N }`.
### notification-action
```bash
-agent-desktop notification-action 1 --action "Reply"
-agent-desktop notification-action 2 --action "Mark as Read"
+agent-desktop notification-action 1 "Reply"
+agent-desktop notification-action 2 "Mark as Read" --expected-app Slack --expected-title "#general"
```
Clicks a named action button on a notification by its 1-based index.
+`--expected-app` and `--expected-title` pin the call to the notification
+you observed in `list-notifications`. Notification Center reorders
+entries between listings, so without a fingerprint an arriving or
+dismissed notification can shift the target at `INDEX` and cause the
+action to press the wrong row. When either flag is set and the row at
+`INDEX` no longer matches, the call fails with `NOTIFICATION_NOT_FOUND`
+instead of pressing. Both flags omitted preserves the legacy
+index-only behavior for callers that reconcile themselves.
+
| Flag | Default | Description |
|------|---------|-------------|
-| (positional) | | 1-based notification index (required) |
-| `--action` | | Action button name to click (required) |
+| `INDEX` (positional) | | 1-based notification index (required) |
+| `ACTION` (positional) | | Action button name to click (required) |
+| `--expected-app` | | Fingerprint app name (from `list-notifications`) |
+| `--expected-title` | | Fingerprint title (from `list-notifications`) |
### wait --notification
```bash
diff --git a/src/batch_dispatch_ext.rs b/src/batch_dispatch_ext.rs
index 32af51c00..a609c7588 100644
--- a/src/batch_dispatch_ext.rs
+++ b/src/batch_dispatch_ext.rs
@@ -143,6 +143,8 @@ pub fn dispatch(
notification_action::NotificationActionArgs {
index,
action: req_str(&args, "action")?,
+ expected_app: str_field(&args, "expected_app"),
+ expected_title: str_field(&args, "expected_title"),
},
adapter,
)
diff --git a/src/cli_args_notifications.rs b/src/cli_args_notifications.rs
index 8e9c19d29..c1a3e356e 100644
--- a/src/cli_args_notifications.rs
+++ b/src/cli_args_notifications.rs
@@ -35,4 +35,16 @@ pub struct NotificationActionCliArgs {
help = "Name of the action button to click (e.g., Reply, Open)"
)]
pub action: String,
+ #[arg(
+ long,
+ help = "Expected app name of the notification at INDEX. If set and NC reordered, the action is refused with NOTIFICATION_NOT_FOUND instead of pressing the wrong notification.",
+ value_name = "APP"
+ )]
+ pub expected_app: Option<String>,
+ #[arg(
+ long,
+ help = "Expected title of the notification at INDEX. Same reorder-safety behavior as --expected-app.",
+ value_name = "TITLE"
+ )]
+ pub expected_title: Option<String>,
}
diff --git a/src/dispatch_notifications.rs b/src/dispatch_notifications.rs
index 704df7ec0..c02dea816 100644
--- a/src/dispatch_notifications.rs
+++ b/src/dispatch_notifications.rs
@@ -37,6 +37,8 @@ pub fn dispatch_notification(
notification_action::NotificationActionArgs {
index: a.index as usize,
action: a.action,
+ expected_app: a.expected_app,
+ expected_title: a.expected_title,
},
adapter,
),