Skip to content

Computer use CLI for AI agents

feat: complete FFI C-ABI surface (Phase A) — handshake, pipeline entrypoints, log callback (#67)

Lahfir8de8f904dbe5
diff --git a/.gitignore b/.gitignore
index 01dd3aebc..94246175b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -81,3 +81,4 @@ docs/*
todos/
.cursor/
.context/
+rust_out
diff --git a/Cargo.lock b/Cargo.lock
index 759143b49..d326c26b7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -52,6 +52,8 @@ dependencies = [
"libc",
"serde_json",
"smallvec",
+ "tracing",
+ "tracing-subscriber",
]
[[package]]
diff --git a/crates/core/src/action.rs b/crates/core/src/action.rs
index 91a3c7b2b..0e05d6ec3 100644
--- a/crates/core/src/action.rs
+++ b/crates/core/src/action.rs
@@ -59,6 +59,19 @@ impl Action {
pub fn may_use_focus_fallback(&self) -> bool {
matches!(self, Self::TypeText(_) | Self::PressKey(_))
}
+
+ /// Returns the minimum `InteractionPolicy` the CLI uses for this action.
+ /// `TypeText` and `PressKey` require focus to land in the right field, so
+ /// their base is `focus_fallback`. Everything else is pure-AX and uses
+ /// `headless`. FFI callers join this base with their caller-supplied policy
+ /// so they can only elevate, never downgrade below CLI parity.
+ pub fn base_interaction_policy(&self) -> crate::interaction_policy::InteractionPolicy {
+ if self.may_use_focus_fallback() {
+ crate::interaction_policy::InteractionPolicy::focus_fallback()
+ } else {
+ crate::interaction_policy::InteractionPolicy::headless()
+ }
+ }
}
#[derive(Debug, Clone, Serialize, Deserialize)]
diff --git a/crates/core/src/actionability/mod.rs b/crates/core/src/actionability/mod.rs
index f557a50c2..414e952f6 100644
--- a/crates/core/src/actionability/mod.rs
+++ b/crates/core/src/actionability/mod.rs
@@ -49,7 +49,9 @@ pub fn check_live(
ErrorCode::StaleRef,
"Resolved element no longer exposes live accessibility state",
)
- .with_suggestion("Run 'snapshot' again and retry with the refreshed ref"));
+ .with_suggestion(
+ "Re-run a snapshot to obtain fresh refs, then retry with the new ref (CLI: snapshot; FFI: ad_snapshot then ad_execute_by_ref with the returned snapshot_id)",
+ ));
}
if let Some(state) = live.state {
observed.role = state.role;
diff --git a/crates/core/src/commands/check.rs b/crates/core/src/commands/check.rs
index f05435df0..0ba6cf0fc 100644
--- a/crates/core/src/commands/check.rs
+++ b/crates/core/src/commands/check.rs
@@ -4,7 +4,6 @@ use crate::{
commands::helpers::{RefArgs, execute_ref_action_with_context},
context::CommandContext,
error::AppError,
- interaction_policy::InteractionPolicy,
};
use serde_json::Value;
@@ -13,10 +12,5 @@ pub fn execute(
adapter: &dyn PlatformAdapter,
context: &CommandContext,
) -> Result<Value, AppError> {
- execute_ref_action_with_context(
- args,
- adapter,
- context.request(Action::Check, InteractionPolicy::headless()),
- context,
- )
+ execute_ref_action_with_context(args, adapter, context.request_base(Action::Check), context)
}
diff --git a/crates/core/src/commands/clear.rs b/crates/core/src/commands/clear.rs
index 60de3a77d..4f4a676f8 100644
--- a/crates/core/src/commands/clear.rs
+++ b/crates/core/src/commands/clear.rs
@@ -4,7 +4,6 @@ use crate::{
commands::helpers::{RefArgs, execute_ref_action_with_context},
context::CommandContext,
error::AppError,
- interaction_policy::InteractionPolicy,
};
use serde_json::Value;
@@ -13,10 +12,5 @@ pub fn execute(
adapter: &dyn PlatformAdapter,
context: &CommandContext,
) -> Result<Value, AppError> {
- execute_ref_action_with_context(
- args,
- adapter,
- context.request(Action::Clear, InteractionPolicy::headless()),
- context,
- )
+ execute_ref_action_with_context(args, adapter, context.request_base(Action::Clear), context)
}
diff --git a/crates/core/src/commands/click.rs b/crates/core/src/commands/click.rs
index 61f3c7846..6dd977858 100644
--- a/crates/core/src/commands/click.rs
+++ b/crates/core/src/commands/click.rs
@@ -4,7 +4,6 @@ use crate::{
commands::helpers::{RefArgs, execute_ref_action_with_context},
context::CommandContext,
error::AppError,
- interaction_policy::InteractionPolicy,
};
use serde_json::Value;
@@ -13,10 +12,5 @@ pub fn execute(
adapter: &dyn PlatformAdapter,
context: &CommandContext,
) -> Result<Value, AppError> {
- execute_ref_action_with_context(
- args,
- adapter,
- context.request(Action::Click, InteractionPolicy::headless()),
- context,
- )
+ execute_ref_action_with_context(args, adapter, context.request_base(Action::Click), context)
}
diff --git a/crates/core/src/commands/collapse.rs b/crates/core/src/commands/collapse.rs
index b904cbbf3..b100bffbf 100644
--- a/crates/core/src/commands/collapse.rs
+++ b/crates/core/src/commands/collapse.rs
@@ -4,7 +4,6 @@ use crate::{
commands::helpers::{RefArgs, execute_ref_action_with_context},
context::CommandContext,
error::AppError,
- interaction_policy::InteractionPolicy,
};
use serde_json::Value;
@@ -16,7 +15,7 @@ pub fn execute(
execute_ref_action_with_context(
args,
adapter,
- context.request(Action::Collapse, InteractionPolicy::headless()),
+ context.request_base(Action::Collapse),
context,
)
}
diff --git a/crates/core/src/commands/double_click.rs b/crates/core/src/commands/double_click.rs
index 2344aacfa..46fd3c7f9 100644
--- a/crates/core/src/commands/double_click.rs
+++ b/crates/core/src/commands/double_click.rs
@@ -4,7 +4,6 @@ use crate::{
commands::helpers::{RefArgs, execute_ref_action_with_context},
context::CommandContext,
error::AppError,
- interaction_policy::InteractionPolicy,
};
use serde_json::Value;
@@ -19,7 +18,7 @@ pub fn execute(
execute_ref_action_with_context(
args,
adapter,
- context.request(Action::DoubleClick, InteractionPolicy::headless()),
+ context.request_base(Action::DoubleClick),
context,
)
}
diff --git a/crates/core/src/commands/execute_by_ref.rs b/crates/core/src/commands/execute_by_ref.rs
new file mode 100644
index 000000000..1c7990f5c
--- /dev/null
+++ b/crates/core/src/commands/execute_by_ref.rs
@@ -0,0 +1,50 @@
+use crate::{
+ action::Action,
+ action_request::ActionRequest,
+ adapter::PlatformAdapter,
+ commands::helpers::{RefArgs, execute_ref_action_with_context},
+ context::CommandContext,
+ error::AppError,
+ interaction_policy::InteractionPolicy,
+};
+use serde_json::Value;
+
+/// Executes an action addressed by a snapshot ref through the canonical
+/// ref-action pipeline: `RefStore` load → `RefMap` lookup → strict element
+/// resolution → live actionability preflight → dispatch.
+///
+/// `snapshot_id` follows CLI `--snapshot` semantics: `None` pins to the
+/// latest snapshot for the session; `Some(id)` pins to that specific snapshot.
+///
+/// The effective `InteractionPolicy` is the join of `caller_policy` and the
+/// action's CLI base policy, ensuring the result is always at least as
+/// permissive as what the CLI would use for the same action, while allowing
+/// FFI callers to opt in to higher-permission policies such as `headed`.
+///
+/// Note on PressKey: its base policy is `focus_fallback` (derived from
+/// `Action::base_interaction_policy`, shared with `TypeText`) because a
+/// ref-targeted key press may need the target focused for keystrokes to land.
+pub fn execute(
+ ref_id: &str,
+ snapshot_id: Option<&str>,
+ action: Action,
+ caller_policy: InteractionPolicy,
+ adapter: &dyn PlatformAdapter,
+ context: &CommandContext,
+) -> Result<Value, AppError> {
+ let base = action.base_interaction_policy();
+ let effective = base.join(caller_policy);
+ let request = ActionRequest {
+ action,
+ policy: effective,
+ };
+ execute_ref_action_with_context(
+ RefArgs {
+ ref_id: ref_id.to_owned(),
+ snapshot_id: snapshot_id.map(ToOwned::to_owned),
+ },
+ adapter,
+ request,
+ context,
+ )
+}
diff --git a/crates/core/src/commands/expand.rs b/crates/core/src/commands/expand.rs
index f3d2fbc98..a0f5eef55 100644
--- a/crates/core/src/commands/expand.rs
+++ b/crates/core/src/commands/expand.rs
@@ -4,7 +4,6 @@ use crate::{
commands::helpers::{RefArgs, execute_ref_action_with_context},
context::CommandContext,
error::AppError,
- interaction_policy::InteractionPolicy,
};
use serde_json::Value;
@@ -13,10 +12,5 @@ pub fn execute(
adapter: &dyn PlatformAdapter,
context: &CommandContext,
) -> Result<Value, AppError> {
- execute_ref_action_with_context(
- args,
- adapter,
- context.request(Action::Expand, InteractionPolicy::headless()),
- context,
- )
+ execute_ref_action_with_context(args, adapter, context.request_base(Action::Expand), context)
}
diff --git a/crates/core/src/commands/focus.rs b/crates/core/src/commands/focus.rs
index cdda016c6..4ac69ac68 100644
--- a/crates/core/src/commands/focus.rs
+++ b/crates/core/src/commands/focus.rs
@@ -4,7 +4,6 @@ use crate::{
commands::helpers::{RefArgs, execute_ref_action_with_context},
context::CommandContext,
error::AppError,
- interaction_policy::InteractionPolicy,
};
use serde_json::Value;
@@ -16,7 +15,7 @@ pub fn execute(
execute_ref_action_with_context(
args,
adapter,
- context.request(Action::SetFocus, InteractionPolicy::headless()),
+ context.request_base(Action::SetFocus),
context,
)
}
diff --git a/crates/core/src/commands/mod.rs b/crates/core/src/commands/mod.rs
index 45c151257..94cceb8cd 100644
--- a/crates/core/src/commands/mod.rs
+++ b/crates/core/src/commands/mod.rs
@@ -11,6 +11,7 @@ pub mod dismiss_all_notifications;
pub mod dismiss_notification;
pub mod double_click;
pub mod drag;
+pub mod execute_by_ref;
pub mod expand;
pub mod find;
pub mod focus;
diff --git a/crates/core/src/commands/ref_policy_tests.rs b/crates/core/src/commands/ref_policy_tests.rs
index 09cdab600..9cd66c062 100644
--- a/crates/core/src/commands/ref_policy_tests.rs
+++ b/crates/core/src/commands/ref_policy_tests.rs
@@ -16,7 +16,7 @@ use crate::{
};
use std::sync::Mutex;
-/// Every command module stem whose execute function calls `context.request(`.
+/// Every command module stem whose execute function calls `context.request_base(`.
/// Adding a new ref-action command requires adding its stem here; the
/// `all_context_request_callers_are_policy_tested` guard enforces this.
const POLICY_TESTED_COMMANDS: &[&str] = &[
@@ -305,7 +305,7 @@ fn all_context_request_callers_are_policy_tested() {
}
let path = commands_dir.join(format!("{stem}.rs"));
let source = std::fs::read_to_string(&path).unwrap_or_default();
- source.contains("context.request(")
+ source.contains("context.request_base(")
})
.collect();
diff --git a/crates/core/src/commands/right_click.rs b/crates/core/src/commands/right_click.rs
index 802cebf34..d58f6108f 100644
--- a/crates/core/src/commands/right_click.rs
+++ b/crates/core/src/commands/right_click.rs
@@ -4,7 +4,6 @@ use crate::{
commands::helpers::{RefArgs, execute_ref_action_result_with_context},
context::CommandContext,
error::AppError,
- interaction_policy::InteractionPolicy,
refs::RefEntry,
snapshot,
};
@@ -15,7 +14,7 @@ pub fn execute(
adapter: &dyn PlatformAdapter,
context: &CommandContext,
) -> Result<Value, AppError> {
- let request = context.request(Action::RightClick, InteractionPolicy::headless());
+ let request = context.request_base(Action::RightClick);
let (entry, result) = execute_ref_action_result_with_context(
&args.ref_id,
args.snapshot_id.as_deref(),
diff --git a/crates/core/src/commands/scroll.rs b/crates/core/src/commands/scroll.rs
index ace5f00d3..a30d45fe4 100644
--- a/crates/core/src/commands/scroll.rs
+++ b/crates/core/src/commands/scroll.rs
@@ -4,7 +4,6 @@ use crate::{
commands::helpers::execute_ref_action_result_with_context,
context::CommandContext,
error::AppError,
- interaction_policy::InteractionPolicy,
};
use serde_json::Value;
@@ -20,10 +19,7 @@ pub fn execute(
adapter: &dyn PlatformAdapter,
context: &CommandContext,
) -> Result<Value, AppError> {
- let request = context.request(
- Action::Scroll(args.direction, args.amount),
- InteractionPolicy::headless(),
- );
+ let request = context.request_base(Action::Scroll(args.direction, args.amount));
let (_entry, result) = execute_ref_action_result_with_context(
&args.ref_id,
args.snapshot_id.as_deref(),
diff --git a/crates/core/src/commands/scroll_to.rs b/crates/core/src/commands/scroll_to.rs
index 3d32c07e9..efe717b9c 100644
--- a/crates/core/src/commands/scroll_to.rs
+++ b/crates/core/src/commands/scroll_to.rs
@@ -4,7 +4,6 @@ use crate::{
commands::helpers::{RefArgs, execute_ref_action_with_context},
context::CommandContext,
error::AppError,
- interaction_policy::InteractionPolicy,
};
use serde_json::Value;
@@ -16,7 +15,7 @@ pub fn execute(
execute_ref_action_with_context(
args,
adapter,
- context.request(Action::ScrollTo, InteractionPolicy::headless()),
+ context.request_base(Action::ScrollTo),
context,
)
}
diff --git a/crates/core/src/commands/select.rs b/crates/core/src/commands/select.rs
index f396d1516..eeeb53b3a 100644
--- a/crates/core/src/commands/select.rs
+++ b/crates/core/src/commands/select.rs
@@ -1,7 +1,7 @@
use crate::{
action::Action, adapter::PlatformAdapter,
commands::helpers::execute_ref_action_result_with_context, context::CommandContext,
- error::AppError, interaction_policy::InteractionPolicy,
+ error::AppError,
};
use serde_json::Value;
@@ -16,7 +16,7 @@ pub fn execute(
adapter: &dyn PlatformAdapter,
context: &CommandContext,
) -> Result<Value, AppError> {
- let request = context.request(Action::Select(args.value), InteractionPolicy::headless());
+ let request = context.request_base(Action::Select(args.value));
let (_entry, result) = execute_ref_action_result_with_context(
&args.ref_id,
args.snapshot_id.as_deref(),
diff --git a/crates/core/src/commands/set_value.rs b/crates/core/src/commands/set_value.rs
index dc67d2ad6..6fef056c8 100644
--- a/crates/core/src/commands/set_value.rs
+++ b/crates/core/src/commands/set_value.rs
@@ -1,7 +1,7 @@
use crate::{
action::Action, adapter::PlatformAdapter,
commands::helpers::execute_ref_action_result_with_context, context::CommandContext,
- error::AppError, interaction_policy::InteractionPolicy,
+ error::AppError,
};
use serde_json::Value;
@@ -16,7 +16,7 @@ pub fn execute(
adapter: &dyn PlatformAdapter,
context: &CommandContext,
) -> Result<Value, AppError> {
- let request = context.request(Action::SetValue(args.value), InteractionPolicy::headless());
+ let request = context.request_base(Action::SetValue(args.value));
let (_entry, result) = execute_ref_action_result_with_context(
&args.ref_id,
args.snapshot_id.as_deref(),
diff --git a/crates/core/src/commands/toggle.rs b/crates/core/src/commands/toggle.rs
index c55c8c0b8..86e39ce63 100644
--- a/crates/core/src/commands/toggle.rs
+++ b/crates/core/src/commands/toggle.rs
@@ -4,7 +4,6 @@ use crate::{
commands::helpers::{RefArgs, execute_ref_action_with_context},
context::CommandContext,
error::AppError,
- interaction_policy::InteractionPolicy,
};
use serde_json::Value;
@@ -13,10 +12,5 @@ pub fn execute(
adapter: &dyn PlatformAdapter,
context: &CommandContext,
) -> Result<Value, AppError> {
- execute_ref_action_with_context(
- args,
- adapter,
- context.request(Action::Toggle, InteractionPolicy::headless()),
- context,
- )
+ execute_ref_action_with_context(args, adapter, context.request_base(Action::Toggle), context)
}
diff --git a/crates/core/src/commands/triple_click.rs b/crates/core/src/commands/triple_click.rs
index 35ff65578..d082880e1 100644
--- a/crates/core/src/commands/triple_click.rs
+++ b/crates/core/src/commands/triple_click.rs
@@ -4,7 +4,6 @@ use crate::{
commands::helpers::{RefArgs, execute_ref_action_with_context},
context::CommandContext,
error::AppError,
- interaction_policy::InteractionPolicy,
};
use serde_json::Value;
@@ -16,7 +15,7 @@ pub fn execute(
execute_ref_action_with_context(
args,
adapter,
- context.request(Action::TripleClick, InteractionPolicy::headless()),
+ context.request_base(Action::TripleClick),
context,
)
}
diff --git a/crates/core/src/commands/type_text.rs b/crates/core/src/commands/type_text.rs
index 7855d8432..192f58d70 100644
--- a/crates/core/src/commands/type_text.rs
+++ b/crates/core/src/commands/type_text.rs
@@ -1,7 +1,7 @@
use crate::{
action::Action, adapter::PlatformAdapter,
commands::helpers::execute_ref_action_result_with_context, context::CommandContext,
- error::AppError, interaction_policy::InteractionPolicy,
+ error::AppError,
};
use serde_json::Value;
@@ -24,10 +24,7 @@ pub fn execute(
)));
}
- let request = context.request(
- Action::TypeText(args.text),
- InteractionPolicy::focus_fallback(),
- );
+ let request = context.request_base(Action::TypeText(args.text));
let (_entry, result) = execute_ref_action_result_with_context(
&args.ref_id,
args.snapshot_id.as_deref(),
diff --git a/crates/core/src/commands/uncheck.rs b/crates/core/src/commands/uncheck.rs
index 58e6ed860..ab1d24f8b 100644
--- a/crates/core/src/commands/uncheck.rs
+++ b/crates/core/src/commands/uncheck.rs
@@ -4,7 +4,6 @@ use crate::{
commands::helpers::{RefArgs, execute_ref_action_with_context},
context::CommandContext,
error::AppError,
- interaction_policy::InteractionPolicy,
};
use serde_json::Value;
@@ -16,7 +15,7 @@ pub fn execute(
execute_ref_action_with_context(
args,
adapter,
- context.request(Action::Uncheck, InteractionPolicy::headless()),
+ context.request_base(Action::Uncheck),
context,
)
}
diff --git a/crates/core/src/commands/wait_resolution_tests.rs b/crates/core/src/commands/wait_resolution_tests.rs
index b187dc599..cec45d369 100644
--- a/crates/core/src/commands/wait_resolution_tests.rs
+++ b/crates/core/src/commands/wait_resolution_tests.rs
@@ -112,7 +112,7 @@ fn element_wait_retries_transient_ambiguous_resolution() {
"@e1".into(),
Some(snapshot_id),
wait_predicate::ElementPredicate::Exists,
- 250,
+ 2000,
&adapter,
&crate::context::CommandContext::default(),
)
@@ -134,7 +134,7 @@ fn element_wait_retries_transient_resolution_timeout() {
"@e1".into(),
Some(snapshot_id),
wait_predicate::ElementPredicate::Exists,
- 250,
+ 2000,
&adapter,
&crate::context::CommandContext::default(),
)
diff --git a/crates/core/src/context.rs b/crates/core/src/context.rs
index 646d18701..21af67ab3 100644
--- a/crates/core/src/context.rs
+++ b/crates/core/src/context.rs
@@ -49,6 +49,15 @@ impl CommandContext {
}
}
+ /// Builds the action request using the action's canonical CLI base policy
+ /// from `Action::base_interaction_policy()`, ensuring a single source of
+ /// truth for the per-action minimum. `--headed` upgrades the base to
+ /// `headed` exactly as `request()` does.
+ pub fn request_base(&self, action: Action) -> ActionRequest {
+ let base = action.base_interaction_policy();
+ self.request(action, base)
+ }
+
/// Policy for raw physical-input commands (hover, drag, mouse-*). They
/// have no semantic action chain, so headless denies both focus stealing
/// and cursor movement unless `--headed` opts in.
@@ -77,11 +86,12 @@ impl CommandContext {
}
pub fn trace(&self, event: &str, fields: Value) -> Result<(), AppError> {
- self.trace.emit(event, fields)
+ self.trace.emit(event, self.session_id.as_deref(), fields)
}
pub fn trace_lazy(&self, event: &str, fields: impl FnOnce() -> Value) -> Result<(), AppError> {
- self.trace.emit_lazy(event, fields)
+ self.trace
+ .emit_lazy(event, self.session_id.as_deref(), fields)
}
pub fn session_id(&self) -> Option<&str> {
@@ -139,6 +149,41 @@ mod tests {
assert_eq!(event["event"], "ref.resolve.ok");
assert_eq!(event["ref"], "@e1");
assert!(event["ts_ms"].as_u64().is_some());
+ assert!(
+ event.get("session_id").is_none(),
+ "session_id must be absent when not set"
+ );
+ let _ = std::fs::remove_file(path);
+ }
+
+ #[test]
+ fn trace_injects_session_id_as_top_level_unredacted_field() {
+ let path = std::env::temp_dir().join(format!(
+ "agent-desktop-session-trace-{}.jsonl",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let context =
+ CommandContext::new(Some("my-session".into()), Some(path.clone()), false).unwrap();
+
+ context
+ .trace("ref.resolve.ok", serde_json::json!({ "ref": "@e1" }))
+ .unwrap();
+
+ let body = std::fs::read_to_string(&path).unwrap();
+ let event: serde_json::Value = serde_json::from_str(body.trim()).unwrap();
+ assert_eq!(
+ event["session_id"], "my-session",
+ "session_id must be a top-level string"
+ );
+ assert_eq!(event["event"], "ref.resolve.ok");
+ assert!(event["ts_ms"].as_u64().is_some());
+ assert!(
+ !body.contains("redacted"),
+ "session_id must not be redacted"
+ );
let _ = std::fs::remove_file(path);
}
diff --git a/crates/core/src/error.rs b/crates/core/src/error.rs
index e730ae706..645cd4be2 100644
--- a/crates/core/src/error.rs
+++ b/crates/core/src/error.rs
@@ -95,13 +95,15 @@ impl AdapterError {
format!("{ref_id} not found in current RefMap"),
)
.with_suggestion(
- "Use the snapshot_id returned with this ref, or run 'snapshot' / 'snapshot --skeleton' again for fresh refs",
+ "Re-run a snapshot to obtain fresh refs, then retry with the new ref \
+ (CLI: snapshot [--skeleton]; FFI: ad_snapshot then ad_execute_by_ref with the returned snapshot_id)",
)
}
pub fn ambiguous_target(message: impl Into<String>) -> Self {
- Self::new(ErrorCode::AmbiguousTarget, message)
- .with_suggestion("Run 'snapshot' to refresh, then retry with a more specific ref")
+ Self::new(ErrorCode::AmbiguousTarget, message).with_suggestion(
+ "Re-run a snapshot to refresh refs, then retry with a more specific ref",
+ )
}
pub fn not_supported(method: &str) -> Self {
@@ -117,7 +119,7 @@ impl AdapterError {
ErrorCode::ElementNotFound,
format!("Element {ref_id} could not be resolved"),
)
- .with_suggestion("Run 'snapshot' to get fresh refs")
+ .with_suggestion("Re-run a snapshot to obtain fresh refs, then retry with the new ref")
}
pub fn timeout(msg: impl Into<String>) -> Self {
@@ -130,7 +132,11 @@ impl AdapterError {
ErrorCode::NotificationNotFound,
format!("Notification at index {index} not found"),
)
- .with_suggestion("Notification may have been dismissed or expired. Run 'list-notifications' to see current notifications")
+ .with_suggestion(
+ "Notification may have been dismissed or expired. \
+ Re-run a notification list to see current notifications \
+ (CLI: list-notifications; FFI: ad_list_notifications)",
+ )
}
pub fn internal(msg: impl Into<String>) -> Self {
@@ -152,7 +158,10 @@ impl AdapterError {
ErrorCode::SnapshotNotFound,
format!("Snapshot '{snapshot_id}' not found"),
)
- .with_suggestion("Run 'snapshot' again and retry with the returned snapshot_id; if you omitted --snapshot, use the same --session as the snapshot")
+ .with_suggestion(
+ "Re-run a snapshot and retry with the returned snapshot_id \
+ (CLI: snapshot, then pass --snapshot <id>; FFI: ad_snapshot then supply snapshot_id to ad_execute_by_ref)",
+ )
}
pub fn policy_denied(message: impl Into<String>) -> Self {
@@ -169,9 +178,13 @@ impl AdapterError {
fn policy_denied_suggestion(policy: InteractionPolicy) -> &'static str {
if policy.allow_focus_steal && !policy.allow_cursor_move {
- "Retry with --headed to permit cursor movement, or use an explicit mouse command if physical input is intended"
+ "Enable cursor movement in the interaction policy to permit cursor-driven actions \
+ (CLI: --headed; FFI: set allow_cursor_move in the policy), \
+ or use an explicit mouse command if physical input is intended"
} else if !policy.allow_focus_steal && !policy.allow_cursor_move {
- "Headless mode allows only accessibility-backed actions; retry with --headed only if physical cursor/focus interaction is intended, otherwise refresh the snapshot or target an element with the needed semantic action"
+ "Headless mode allows only accessibility-backed actions; \
+ enable physical interaction in the policy (CLI: --headed) only if cursor/focus movement is intended, \
+ otherwise refresh the snapshot or target an element with the needed semantic action"
} else {
"Use an explicit mouse/focus command if physical interaction is intended"
}
@@ -245,7 +258,7 @@ mod tests {
}
#[test]
- fn stale_ref_suggestion_mentions_skeleton() {
+ fn stale_ref_suggestion_is_transport_neutral() {
let err = AdapterError::stale_ref("@e7");
assert_eq!(err.code, ErrorCode::StaleRef);
assert!(err.message.contains("@e7"));
@@ -254,8 +267,12 @@ mod tests {
.as_deref()
.expect("stale_ref should carry a suggestion");
assert!(
- suggestion.contains("skeleton"),
- "stale-ref suggestion should mention skeleton refresh, got: {suggestion}"
+ suggestion.contains("snapshot"),
+ "stale-ref suggestion should mention running a snapshot, got: {suggestion}"
+ );
+ assert!(
+ suggestion.contains("FFI"),
+ "stale-ref suggestion should include FFI transport guidance, got: {suggestion}"
);
}
diff --git a/crates/core/src/interaction_policy.rs b/crates/core/src/interaction_policy.rs
index d612de995..637bd4ee6 100644
--- a/crates/core/src/interaction_policy.rs
+++ b/crates/core/src/interaction_policy.rs
@@ -27,6 +27,17 @@ impl InteractionPolicy {
allow_cursor_move: true,
}
}
+
+ /// Returns the least-restrictive policy that satisfies both `self` and
+ /// `other`. Used by FFI callers that supply an explicit caller policy: the
+ /// result is always at least as permissive as the action's CLI base, and
+ /// at least as permissive as what the caller requested.
+ pub fn join(self, other: InteractionPolicy) -> InteractionPolicy {
+ InteractionPolicy {
+ allow_focus_steal: self.allow_focus_steal || other.allow_focus_steal,
+ allow_cursor_move: self.allow_cursor_move || other.allow_cursor_move,
+ }
+ }
}
impl Default for InteractionPolicy {
@@ -34,3 +45,56 @@ impl Default for InteractionPolicy {
Self::headless()
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn join_headless_with_headless_stays_headless() {
+ assert_eq!(
+ InteractionPolicy::headless().join(InteractionPolicy::headless()),
+ InteractionPolicy::headless()
+ );
+ }
+
+ #[test]
+ fn join_headless_with_focus_fallback_gives_focus_fallback() {
+ assert_eq!(
+ InteractionPolicy::headless().join(InteractionPolicy::focus_fallback()),
+ InteractionPolicy::focus_fallback()
+ );
+ }
+
+ #[test]
+ fn join_focus_fallback_with_headless_gives_focus_fallback() {
+ assert_eq!(
+ InteractionPolicy::focus_fallback().join(InteractionPolicy::headless()),
+ InteractionPolicy::focus_fallback()
+ );
+ }
+
+ #[test]
+ fn join_headless_with_headed_gives_headed() {
+ assert_eq!(
+ InteractionPolicy::headless().join(InteractionPolicy::headed()),
+ InteractionPolicy::headed()
+ );
+ }
+
+ #[test]
+ fn join_focus_fallback_with_headed_gives_headed() {
+ assert_eq!(
+ InteractionPolicy::focus_fallback().join(InteractionPolicy::headed()),
+ InteractionPolicy::headed()
+ );
+ }
+
+ #[test]
+ fn join_headed_with_headless_gives_headed() {
+ assert_eq!(
+ InteractionPolicy::headed().join(InteractionPolicy::headless()),
+ InteractionPolicy::headed()
+ );
+ }
+}
diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs
index bc0999fe6..3036fe58e 100644
--- a/crates/core/src/lib.rs
+++ b/crates/core/src/lib.rs
@@ -56,3 +56,4 @@ pub use permission_report::PermissionReport;
pub use permission_state::PermissionState;
pub use refs::{RefEntry, RefMap};
pub use refs_store::RefStore;
+pub use trace::sanitize_trace_value;
diff --git a/crates/core/src/output.rs b/crates/core/src/output.rs
index 859e0e83c..b8990400d 100644
--- a/crates/core/src/output.rs
+++ b/crates/core/src/output.rs
@@ -1,7 +1,7 @@
use serde::Serialize;
use serde_json::Value;
-use crate::error::AppError;
+use crate::error::{AppError, ErrorCode};
pub const ENVELOPE_VERSION: &str = "2.0";
@@ -53,6 +53,16 @@ impl Response {
}
}
+fn retry_token_for_code(code: &ErrorCode) -> Option<String> {
+ match code {
+ ErrorCode::StaleRef | ErrorCode::SnapshotNotFound => {
+ Some("snapshot;execute_by_ref".to_owned())
+ }
+ ErrorCode::PolicyDenied => Some("escalate_policy".to_owned()),
+ _ => None,
+ }
+}
+
impl ErrorPayload {
pub fn from_app_error(err: &AppError) -> Self {
let mut payload = Self::new(err.code(), err.to_string());
@@ -62,6 +72,7 @@ impl ErrorPayload {
if let AppError::Adapter(adapter_error) = err {
payload.platform_detail = adapter_error.platform_detail.clone();
payload.details = adapter_error.details.clone();
+ payload.retry_command = retry_token_for_code(&adapter_error.code);
}
payload
}
@@ -113,5 +124,61 @@ mod tests {
Some("native press action failed")
);
assert_eq!(payload.details, Some(json!({ "check": "visible" })));
+ assert_eq!(
+ payload.retry_command, None,
+ "ACTION_FAILED must not carry a retry token"
+ );
+ }
+
+ #[test]
+ fn stale_ref_payload_carries_snapshot_retry_token() {
+ let err = AppError::stale_ref("@e5");
+ let payload = ErrorPayload::from_app_error(&err);
+ assert_eq!(payload.code, "STALE_REF");
+ assert_eq!(
+ payload.retry_command.as_deref(),
+ Some("snapshot;execute_by_ref"),
+ "STALE_REF must carry the canonical retry token"
+ );
+ }
+
+ #[test]
+ fn snapshot_not_found_payload_carries_snapshot_retry_token() {
+ let err = AppError::Adapter(AdapterError::snapshot_not_found("snap-abc"));
+ let payload = ErrorPayload::from_app_error(&err);
+ assert_eq!(payload.code, "SNAPSHOT_NOT_FOUND");
+ assert_eq!(
+ payload.retry_command.as_deref(),
+ Some("snapshot;execute_by_ref"),
+ "SNAPSHOT_NOT_FOUND must carry the canonical retry token"
+ );
+ }
+
+ #[test]
+ fn policy_denied_payload_carries_escalate_policy_token() {
+ let err = AppError::Adapter(AdapterError::policy_denied("blocked by policy"));
+ let payload = ErrorPayload::from_app_error(&err);
+ assert_eq!(payload.code, "POLICY_DENIED");
+ assert_eq!(
+ payload.retry_command.as_deref(),
+ Some("escalate_policy"),
+ "POLICY_DENIED must carry the escalate_policy token, not a snapshot token"
+ );
+ }
+
+ #[test]
+ fn retry_command_absent_for_non_retryable_errors() {
+ for err in [
+ AppError::Adapter(AdapterError::new(ErrorCode::InvalidArgs, "bad input")),
+ AppError::Adapter(AdapterError::not_supported("method_x")),
+ AppError::Adapter(AdapterError::new(ErrorCode::ActionFailed, "failed")),
+ ] {
+ let payload = ErrorPayload::from_app_error(&err);
+ assert!(
+ payload.retry_command.is_none(),
+ "non-retryable error {} must not carry a retry token",
+ payload.code
+ );
+ }
}
}
diff --git a/crates/core/src/ref_action.rs b/crates/core/src/ref_action.rs
index c7b823d64..aebfd024a 100644
--- a/crates/core/src/ref_action.rs
+++ b/crates/core/src/ref_action.rs
@@ -68,27 +68,60 @@ fn check_actionability_with_trace(
Ok(())
}
-pub fn execute_entry(
+/// Builds a stable, non-sensitive trace label from a `RefEntry`. The label
+/// is derived from role and path indices only — no content fields — so it is
+/// safe to emit in the `"ref"` trace key without redaction risk. Path indices
+/// are deterministic within a snapshot but carry no secret information.
+fn ref_label_from_entry(entry: &RefEntry) -> String {
+ if entry.path.is_empty() {
+ return format!("<{}>", entry.role);
+ }
+ let indices: Vec<String> = entry.path.iter().map(|i| i.to_string()).collect();
+ format!("<{}/{}>", entry.role, indices.join("/"))
+}
+
+/// Executes a pre-resolved ref-action entry using the provided `context` for
+/// session identity and trace emission. Prefer this over `execute_entry` when
+/// a real `CommandContext` is available (e.g. from `AdAdapter::command_context`
+/// in the FFI layer), so that trace events carry the correct session id.
+///
+/// Trace records use a role/path-derived label for the `"ref"` field so that
+/// FFI call-site events are distinguishable in multi-element trace logs. The
+/// label never includes content fields (name, value, text) that are subject to
+/// redaction.
+pub fn execute_entry_with_context(
adapter: &dyn PlatformAdapter,
entry: &RefEntry,
request: ActionRequest,
+ context: &CommandContext,
) -> Result<ActionResult, AdapterError> {
+ let label = ref_label_from_entry(entry);
let handle = adapter.resolve_element_strict(entry)?;
let handle = ResolvedElement::new(adapter, handle);
- let context = CommandContext::default();
let result = execute_resolved(
ResolvedRefAction {
adapter,
entry,
handle: handle.handle(),
- ref_id: "<ffi>",
- context: &context,
+ ref_id: &label,
+ context,
},
request,
);
result.map_err(into_adapter_error)
}
+/// Executes a pre-resolved ref-action entry with a default (no-session,
+/// no-trace) `CommandContext`. Existing callers outside the FFI layer that do
+/// not have a live session context continue to use this entry point unchanged.
+pub fn execute_entry(
+ adapter: &dyn PlatformAdapter,
+ entry: &RefEntry,
+ request: ActionRequest,
+) -> Result<ActionResult, AdapterError> {
+ execute_entry_with_context(adapter, entry, request, &CommandContext::default())
+}
+
fn into_adapter_error(err: AppError) -> AdapterError {
match err {
AppError::Adapter(err) => err,
diff --git a/crates/core/src/ref_action_tests.rs b/crates/core/src/ref_action_tests.rs
index 7013cd924..9dcacf1e4 100644
--- a/crates/core/src/ref_action_tests.rs
+++ b/crates/core/src/ref_action_tests.rs
@@ -95,3 +95,94 @@ fn failed_action_still_releases_resolved_handle() {
assert_eq!(err.code, crate::error::ErrorCode::Internal);
assert_eq!(adapter.releases.load(Ordering::SeqCst), 1);
}
+
+#[test]
+fn execute_entry_with_context_succeeds_and_matches_execute_entry() {
+ let context = CommandContext::default();
+ let result = execute_entry_with_context(
+ &ReleaseFailingAdapter,
+ &entry(),
+ ActionRequest::headless(Action::Click),
+ &context,
+ )
+ .unwrap();
+
+ assert_eq!(result.action, "click");
+}
+
+#[test]
+fn execute_entry_with_context_emits_trace_events() {
+ let trace_path = std::env::temp_dir().join(format!(
+ "agent-desktop-ref-action-trace-{}.jsonl",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let context =
+ CommandContext::new(Some("test-session".into()), Some(trace_path.clone()), false).unwrap();
+
+ let _ = execute_entry_with_context(
+ &ReleaseFailingAdapter,
+ &entry(),
+ ActionRequest::headless(Action::Click),
+ &context,
+ );
+
+ let body = std::fs::read_to_string(&trace_path).unwrap();
+ assert!(
+ body.contains("actionability.check.start"),
+ "expected actionability trace event"
+ );
+ assert!(
+ body.contains("action.dispatch.start"),
+ "expected dispatch trace event"
+ );
+ for line in body.lines() {
+ let record: serde_json::Value = serde_json::from_str(line).unwrap();
+ assert_eq!(
+ record["session_id"], "test-session",
+ "session_id must appear in every trace record when set"
+ );
+ }
+ let _ = std::fs::remove_file(trace_path);
+}
+
+#[test]
+fn trace_records_omit_session_id_when_context_has_none() {
+ let trace_path = std::env::temp_dir().join(format!(
+ "agent-desktop-ref-action-no-session-trace-{}.jsonl",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ let context = CommandContext::new(None, Some(trace_path.clone()), false).unwrap();
+
+ let _ = execute_entry_with_context(
+ &ReleaseFailingAdapter,
+ &entry(),
+ ActionRequest::headless(Action::Click),
+ &context,
+ );
+
+ let body = std::fs::read_to_string(&trace_path).unwrap();
+ for line in body.lines() {
+ let record: serde_json::Value = serde_json::from_str(line).unwrap();
+ assert!(
+ record.get("session_id").is_none(),
+ "session_id must be absent when context has no session"
+ );
+ }
+ let _ = std::fs::remove_file(trace_path);
+}
+
+#[test]
+fn ref_label_from_entry_uses_role_and_path_indices() {
+ let no_path = entry();
+ assert_eq!(ref_label_from_entry(&no_path), "<button>");
+
+ let mut with_path = entry();
+ with_path.path = smallvec::smallvec![2, 0, 3];
+ assert_eq!(ref_label_from_entry(&with_path), "<button/2/0/3>");
+}
diff --git a/crates/core/src/snapshot_ref_tests.rs b/crates/core/src/snapshot_ref_tests.rs
index b0b267e6b..f00b2f1c5 100644
--- a/crates/core/src/snapshot_ref_tests.rs
+++ b/crates/core/src/snapshot_ref_tests.rs
@@ -240,8 +240,8 @@ fn test_run_from_ref_stale_root_returns_stale_ref() {
assert_eq!(adapter_err.code, crate::error::ErrorCode::StaleRef);
let suggestion = adapter_err.suggestion.as_deref().unwrap_or("");
assert!(
- suggestion.contains("skeleton"),
- "stale-ref suggestion should mention skeleton, got: {suggestion}"
+ suggestion.contains("snapshot"),
+ "stale-ref suggestion should mention running a snapshot, got: {suggestion}"
);
}
other => panic!("expected Adapter(StaleRef), got {other:?}"),
diff --git a/crates/core/src/trace.rs b/crates/core/src/trace.rs
index 8c586de65..171d9b85c 100644
--- a/crates/core/src/trace.rs
+++ b/crates/core/src/trace.rs
@@ -34,18 +34,28 @@ impl TraceConfig {
Ok(Self { strict, writer })
}
- pub fn emit(&self, event: &str, fields: Value) -> Result<(), AppError> {
- self.emit_lazy(event, || fields)
+ pub fn emit(
+ &self,
+ event: &str,
+ session_id: Option<&str>,
+ fields: Value,
+ ) -> Result<(), AppError> {
+ self.emit_lazy(event, session_id, || fields)
}
- pub fn emit_lazy(&self, event: &str, fields: impl FnOnce() -> Value) -> Result<(), AppError> {
+ pub fn emit_lazy(
+ &self,
+ event: &str,
+ session_id: Option<&str>,
+ fields: impl FnOnce() -> Value,
+ ) -> Result<(), AppError> {
let Some(writer) = self.writer.as_ref() else {
return Ok(());
};
match writer
.lock()
.map_err(|_| AppError::Internal("trace writer lock poisoned".into()))
- .and_then(|mut file| write_event(&mut file, event, fields()))
+ .and_then(|mut file| write_event(&mut file, event, session_id, fields()))
{
Ok(()) => Ok(()),
Err(err) if self.strict => Err(err),
@@ -71,7 +81,12 @@ fn open_trace_file(path: &Path) -> Result<std::fs::File, AppError> {
Ok(file)
}
-fn write_event(file: &mut std::fs::File, event: &str, fields: Value) -> Result<(), AppError> {
+fn write_event(
+ file: &mut std::fs::File,
+ event: &str,
+ session_id: Option<&str>,
+ fields: Value,
+) -> Result<(), AppError> {
reject_oversized_trace(file)?;
let mut body = Map::new();
body.insert("event".to_string(), json!(event));
@@ -89,6 +104,9 @@ fn write_event(file: &mut std::fs::File, event: &str, fields: Value) -> Result<(
body.insert(key, value);
}
}
+ if let Some(sid) = session_id {
+ body.insert("session_id".to_string(), json!(sid));
+ }
serde_json::to_writer(&mut *file, &Value::Object(body))?;
use std::io::Write;
file.write_all(b"\n").map_err(AppError::from)
@@ -124,7 +142,11 @@ fn reject_loose_trace_permissions(_file: &std::fs::File) -> Result<(), AppError>
Ok(())
}
-fn sanitize_trace_value(value: Value) -> Value {
+/// Recursively redacts fields whose keys match `SENSITIVE_KEYS`. Non-sensitive
+/// fields and non-object values are left unchanged. Array elements are
+/// recursively scanned. Used by both the file-trace writer and the FFI log
+/// callback layer so that sensitive values never reach a consumer.
+pub fn sanitize_trace_value(value: Value) -> Value {
match value {
Value::Object(map) => Value::Object(
map.into_iter()
@@ -292,7 +314,7 @@ mod tests {
}
let mut file = open_trace_file(&path).unwrap();
- let err = write_event(&mut file, "event", json!({})).unwrap_err();
+ let err = write_event(&mut file, "event", None, json!({})).unwrap_err();
assert_eq!(err.code(), "INVALID_ARGS");
let _ = std::fs::remove_file(path);
diff --git a/crates/ffi/Cargo.toml b/crates/ffi/Cargo.toml
index df24d463b..a77df22a2 100644
--- a/crates/ffi/Cargo.toml
+++ b/crates/ffi/Cargo.toml
@@ -11,6 +11,8 @@ crate-type = ["cdylib", "rlib"]
[dependencies]
smallvec.workspace = true
serde_json.workspace = true
+tracing.workspace = true
+tracing-subscriber.workspace = true
agent-desktop-core.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
diff --git a/crates/ffi/build.rs b/crates/ffi/build.rs
index f154d8413..bbe94ef03 100644
--- a/crates/ffi/build.rs
+++ b/crates/ffi/build.rs
@@ -1,6 +1,19 @@
//! 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.
+//!
+//! # panic=abort guard (Finding #14)
+//!
+//! `trap_panic` (the `catch_unwind` fence in `src/ffi.rs`) requires
+//! `panic = "unwind"` to function; building with `panic = "abort"` silently
+//! degrades hostile-input panics to process abort. The `release-ffi` profile
+//! enforces `panic = "unwind"` and is the only profile used to ship the cdylib.
+//!
+//! A build-time check via `CARGO_CFG_PANIC` is not viable here: because this
+//! crate declares both `cdylib` and `rlib` crate-types, Cargo always reports
+//! `CARGO_CFG_PANIC = "unwind"` in the build script regardless of the active
+//! profile's `panic` setting. The invariant is therefore documented rather
+//! than machine-enforced; CI gates the cdylib via `--profile release-ffi` only.
fn main() {
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
diff --git a/crates/ffi/cbindgen.toml b/crates/ffi/cbindgen.toml
index 294400532..a8a3f94e7 100644
--- a/crates/ffi/cbindgen.toml
+++ b/crates/ffi/cbindgen.toml
@@ -5,6 +5,87 @@ sys_includes = ["stdint.h", "stdbool.h", "stddef.h"]
style = "both"
usize_is_size_t = true
+# Agent workflow orientation for C/C++ binding authors.
+# Placed after sys-includes and before declarations (inside the include guard).
+after_includes = """
+/*
+ * Agent workflow — quick orientation for C/C++ binding authors:
+ *
+ * 1. (Optional) Call ad_init(AD_ABI_VERSION_MAJOR) to verify at runtime that
+ * the header you compiled against matches the loaded dylib. A version
+ * mismatch returns ErrInvalidArgs; abort rather than proceed.
+ *
+ * 2. Create an adapter:
+ * AdAdapter *a = ad_adapter_create(); // no session
+ * AdAdapter *a = ad_adapter_create_with_session(session_id); // with session
+ *
+ * 3. Observe via ad_snapshot(). The returned JSON envelope contains the
+ * accessibility tree with @e-prefixed ref IDs (e.g. "@e5") that address
+ * individual interactive elements. A refmap is written under
+ * ~/.agent-desktop/ and is keyed to the session. The envelope carries
+ * data.snapshot_id — pass it back as the snapshot_id argument to
+ * ad_execute_by_ref to pin the action to that exact snapshot; pass NULL
+ * to target the latest snapshot for the session.
+ *
+ * 4. Act via ad_execute_by_ref(a, "@e5", snapshot_id, &action, policy, &out).
+ * Build an AdAction by zero-initialising it and setting its kind field to
+ * an AD_ACTION_KIND_* constant plus any kind-specific fields (e.g. .text
+ * for AD_ACTION_KIND_TYPE_TEXT). policy=0 (Headless) keeps each action's
+ * built-in base behaviour; pass 2 (Headed) to additionally allow
+ * cursor/focus fallbacks. ref_id must be non-null (null returns
+ * ErrInvalidArgs immediately).
+ *
+ * 5. Ownership: every non-null *out string must be freed with ad_free_string().
+ * Destroy the adapter when done with ad_adapter_destroy(a).
+ *
+ * macOS: all ad_* calls that interact with the AX API must be made from the
+ * main thread. ad_snapshot and ad_execute_by_ref enforce this with a guard.
+ */
+"""
+
+# ABI layout guards — regenerated automatically by scripts/update-ffi-header.sh.
+# Each sizeof guard references an AD_*_SIZE macro (emitted from the corresponding
+# Rust pub const via [const] allow_static_const = false), so the size literal
+# lives in exactly one place: the Rust source. Alignment and offset guards use
+# literal values because no Rust const tracks those — they are structurally fixed
+# on all 64-bit targets (8-byte pointer alignment; fields in declaration order).
+trailer = """
+/* C11 ABI layout guards — auto-generated; do not hand-edit.
+ * Each sizeof check references the AD_*_SIZE macro defined above so the
+ * size literal lives in exactly one place (the Rust source). Alignment
+ * and offset values are structurally fixed on all 64-bit targets.
+ * The one-shot guard makes double-include safe regardless of C standard. */
+#ifndef AGENT_DESKTOP_ABI_ASSERTS
+#define AGENT_DESKTOP_ABI_ASSERTS
+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
+_Static_assert(sizeof(AdDragParams) == AD_DRAG_PARAMS_SIZE, "AdDragParams ABI size changed");
+_Static_assert(_Alignof(AdDragParams) == 8, "AdDragParams ABI alignment changed");
+_Static_assert(sizeof(AdAction) == AD_ACTION_SIZE, "AdAction ABI size changed");
+_Static_assert(_Alignof(AdAction) == 8, "AdAction ABI alignment changed");
+_Static_assert(sizeof(AdElementState) == AD_ELEMENT_STATE_SIZE, "AdElementState ABI size changed");
+_Static_assert(_Alignof(AdElementState) == 8, "AdElementState ABI alignment changed");
+_Static_assert(sizeof(AdActionStep) == AD_ACTION_STEP_SIZE, "AdActionStep ABI size changed");
+_Static_assert(_Alignof(AdActionStep) == 8, "AdActionStep ABI alignment changed");
+_Static_assert(offsetof(AdActionStep, label) == 0, "AdActionStep.label offset changed");
+_Static_assert(offsetof(AdActionStep, outcome) == 8, "AdActionStep.outcome offset changed");
+_Static_assert(sizeof(AdActionResult) == AD_ACTION_RESULT_SIZE, "AdActionResult ABI size changed");
+_Static_assert(_Alignof(AdActionResult) == 8, "AdActionResult ABI alignment changed");
+_Static_assert(offsetof(AdActionResult, action) == 0, "AdActionResult.action offset changed");
+_Static_assert(offsetof(AdActionResult, ref_id) == 8, "AdActionResult.ref_id offset changed");
+_Static_assert(offsetof(AdActionResult, post_state) == 16, "AdActionResult.post_state offset changed");
+_Static_assert(offsetof(AdActionResult, steps) == 24, "AdActionResult.steps offset changed");
+_Static_assert(offsetof(AdActionResult, step_count) == 32, "AdActionResult.step_count offset changed");
+_Static_assert(sizeof(AdRefEntry) == AD_REF_ENTRY_SIZE, "AdRefEntry ABI size changed");
+_Static_assert(_Alignof(AdRefEntry) == 8, "AdRefEntry ABI alignment changed");
+_Static_assert(sizeof(struct AdWaitArgs) == AD_WAIT_ARGS_SIZE, "AdWaitArgs ABI size drift");
+_Static_assert(_Alignof(struct AdWaitArgs) == 8, "AdWaitArgs ABI alignment changed");
+#endif /* __STDC_VERSION__ >= 201112L */
+#endif /* AGENT_DESKTOP_ABI_ASSERTS */
+"""
+
+[const]
+allow_static_const = false
+
[export]
# Force-emit the enums whose discriminants are the valid values for
# public `int32_t` fields (AdAction.kind, AdScrollParams.direction, etc.).
diff --git a/crates/ffi/include/agent_desktop.h b/crates/ffi/include/agent_desktop.h
index bd1034cd8..ef5d9e972 100644
--- a/crates/ffi/include/agent_desktop.h
+++ b/crates/ffi/include/agent_desktop.h
@@ -4,10 +4,107 @@
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
+/*
+ * Agent workflow — quick orientation for C/C++ binding authors:
+ *
+ * 1. (Optional) Call ad_init(AD_ABI_VERSION_MAJOR) to verify at runtime that
+ * the header you compiled against matches the loaded dylib. A version
+ * mismatch returns ErrInvalidArgs; abort rather than proceed.
+ *
+ * 2. Create an adapter:
+ * AdAdapter *a = ad_adapter_create(); // no session
+ * AdAdapter *a = ad_adapter_create_with_session(session_id); // with session
+ *
+ * 3. Observe via ad_snapshot(). The returned JSON envelope contains the
+ * accessibility tree with @e-prefixed ref IDs (e.g. "@e5") that address
+ * individual interactive elements. A refmap is written under
+ * ~/.agent-desktop/ and is keyed to the session. The envelope carries
+ * data.snapshot_id — pass it back as the snapshot_id argument to
+ * ad_execute_by_ref to pin the action to that exact snapshot; pass NULL
+ * to target the latest snapshot for the session.
+ *
+ * 4. Act via ad_execute_by_ref(a, "@e5", snapshot_id, &action, policy, &out).
+ * Build an AdAction by zero-initialising it and setting its kind field to
+ * an AD_ACTION_KIND_* constant plus any kind-specific fields (e.g. .text
+ * for AD_ACTION_KIND_TYPE_TEXT). policy=0 (Headless) keeps each action's
+ * built-in base behaviour; pass 2 (Headed) to additionally allow
+ * cursor/focus fallbacks. ref_id must be non-null (null returns
+ * ErrInvalidArgs immediately).
+ *
+ * 5. Ownership: every non-null *out string must be freed with ad_free_string().
+ * Destroy the adapter when done with ad_adapter_destroy(a).
+ *
+ * macOS: all ad_* calls that interact with the AX API must be made from the
+ * main thread. ad_snapshot and ad_execute_by_ref enforce this with a guard.
+ */
+
+
+/**
+ * The major ABI version of this build of `libagent_desktop_ffi`.
+ *
+ * Version-bump rule: increment this constant (and update the header via
+ * `scripts/update-ffi-header.sh`) whenever a breaking change is made to the
+ * C ABI — a removed or incompatibly-changed `ad_*` symbol, or a layout
+ * change to any `repr(C)` struct. Additive changes (new `ad_*` symbols, new
+ * error codes) do **not** require a bump. It is recommended to call `ad_init`
+ * with the major compiled against the header to verify ABI compatibility; a
+ * mismatch means the header and dylib are incompatible and the consumer should
+ * refuse to proceed rather than risk undefined behaviour.
+ */
+#define AD_ABI_VERSION_MAJOR 1
+
+/**
+ * Maximum byte length (excluding the NUL terminator) accepted for any
+ * foreign C string. Bounds both the terminator scan and the resulting
+ * allocation, so a missing NUL or a hostile caller cannot walk arbitrary
+ * memory into a `String`. Sized to roughly match the CLI's argv ceiling so
+ * payload-bearing calls (clipboard-set, type) keep CLI parity rather than
+ * being cut off at a ref-field-sized cap. Mirrored in the header as
+ * `AD_MAX_STRING_BYTES`.
+ */
+#define AD_MAX_STRING_BYTES (1024 * 1024)
+
+#define AD_ACTION_SIZE 96
+
+#define AD_ACTION_RESULT_SIZE 40
+
+#define AD_ACTION_STEP_SIZE 16
+
+#define AD_DRAG_PARAMS_SIZE 48
+
+#define AD_ELEMENT_STATE_SIZE 32
+
+#define AD_REF_ENTRY_SIZE 192
+
+/**
+ * Per-field input caps enforced when converting an `AdRefEntry` at the C
+ * boundary, sized from what real accessibility trees produce (a handful of
+ * states/actions, double-digit path depth) with generous headroom. Mirrored
+ * in the header so callers can validate before calling.
+ */
+#define AD_MAX_REF_STATES 64
+
+#define AD_MAX_REF_ACTIONS 32
+
+#define AD_MAX_REF_PATH_DEPTH 128
-/* New result codes may be appended in future releases.
- * Always handle values outside this list. */
-enum AdResult {
+/**
+ * Pinned size of `AdWaitArgs` on 64-bit targets. The compile-time
+ * assert below and the `ad_wait_args_size()` runtime getter form the
+ * 3-layer pin: Rust const assert, C `_Static_assert` in the header,
+ * and the test in `c_abi_layout.rs`.
+ */
+#define AD_WAIT_ARGS_SIZE 112
+
+/**
+ * New result codes may be appended in future releases. Always handle values
+ * outside this list.
+ */
+enum AdResult
+#if __STDC_VERSION__ >= 202311L
+ : int32_t
+#endif // __STDC_VERSION__ >= 202311L
+ {
AD_RESULT_OK = 0,
AD_RESULT_ERR_PERM_DENIED = -1,
AD_RESULT_ERR_ELEMENT_NOT_FOUND = -2,
@@ -25,15 +122,31 @@ enum AdResult {
AD_RESULT_ERR_POLICY_DENIED = -14,
AD_RESULT_ERR_AMBIGUOUS_TARGET = -15,
};
+#if __STDC_VERSION__ >= 202311L
+typedef enum AdResult AdResult;
+#else
typedef int32_t AdResult;
+#endif // __STDC_VERSION__ >= 202311L
-enum AdImageFormat {
+enum AdImageFormat
+#if __STDC_VERSION__ >= 202311L
+ : int32_t
+#endif // __STDC_VERSION__ >= 202311L
+ {
AD_IMAGE_FORMAT_PNG = 0,
AD_IMAGE_FORMAT_JPG = 1,
};
+#if __STDC_VERSION__ >= 202311L
+typedef enum AdImageFormat AdImageFormat;
+#else
typedef int32_t AdImageFormat;
+#endif // __STDC_VERSION__ >= 202311L
-enum AdActionKind {
+enum AdActionKind
+#if __STDC_VERSION__ >= 202311L
+ : int32_t
+#endif // __STDC_VERSION__ >= 202311L
+ {
AD_ACTION_KIND_CLICK = 0,
AD_ACTION_KIND_DOUBLE_CLICK = 1,
AD_ACTION_KIND_RIGHT_CLICK = 2,
@@ -56,54 +169,110 @@ enum AdActionKind {
AD_ACTION_KIND_HOVER = 19,
AD_ACTION_KIND_DRAG = 20,
};
+#if __STDC_VERSION__ >= 202311L
+typedef enum AdActionKind AdActionKind;
+#else
typedef int32_t AdActionKind;
+#endif // __STDC_VERSION__ >= 202311L
-enum AdDirection {
+enum AdDirection
+#if __STDC_VERSION__ >= 202311L
+ : int32_t
+#endif // __STDC_VERSION__ >= 202311L
+ {
AD_DIRECTION_UP = 0,
AD_DIRECTION_DOWN = 1,
AD_DIRECTION_LEFT = 2,
AD_DIRECTION_RIGHT = 3,
};
+#if __STDC_VERSION__ >= 202311L
+typedef enum AdDirection AdDirection;
+#else
typedef int32_t AdDirection;
+#endif // __STDC_VERSION__ >= 202311L
-enum AdModifier {
+enum AdModifier
+#if __STDC_VERSION__ >= 202311L
+ : int32_t
+#endif // __STDC_VERSION__ >= 202311L
+ {
AD_MODIFIER_CMD = 0,
AD_MODIFIER_CTRL = 1,
AD_MODIFIER_ALT = 2,
AD_MODIFIER_SHIFT = 3,
};
+#if __STDC_VERSION__ >= 202311L
+typedef enum AdModifier AdModifier;
+#else
typedef int32_t AdModifier;
+#endif // __STDC_VERSION__ >= 202311L
-enum AdMouseButton {
+enum AdMouseButton
+#if __STDC_VERSION__ >= 202311L
+ : int32_t
+#endif // __STDC_VERSION__ >= 202311L
+ {
AD_MOUSE_BUTTON_LEFT = 0,
AD_MOUSE_BUTTON_RIGHT = 1,
AD_MOUSE_BUTTON_MIDDLE = 2,
};
+#if __STDC_VERSION__ >= 202311L
+typedef enum AdMouseButton AdMouseButton;
+#else
typedef int32_t AdMouseButton;
+#endif // __STDC_VERSION__ >= 202311L
-enum AdMouseEventKind {
+enum AdMouseEventKind
+#if __STDC_VERSION__ >= 202311L
+ : int32_t
+#endif // __STDC_VERSION__ >= 202311L
+ {
AD_MOUSE_EVENT_KIND_MOVE = 0,
AD_MOUSE_EVENT_KIND_DOWN = 1,
AD_MOUSE_EVENT_KIND_UP = 2,
AD_MOUSE_EVENT_KIND_CLICK = 3,
};
+#if __STDC_VERSION__ >= 202311L
+typedef enum AdMouseEventKind AdMouseEventKind;
+#else
typedef int32_t AdMouseEventKind;
+#endif // __STDC_VERSION__ >= 202311L
-enum AdPolicyKind {
+enum AdPolicyKind
+#if __STDC_VERSION__ >= 202311L
+ : int32_t
+#endif // __STDC_VERSION__ >= 202311L
+ {
AD_POLICY_KIND_HEADLESS = 0,
AD_POLICY_KIND_FOCUS_FALLBACK = 1,
AD_POLICY_KIND_HEADED = 2,
};
+#if __STDC_VERSION__ >= 202311L
+typedef enum AdPolicyKind AdPolicyKind;
+#else
typedef int32_t AdPolicyKind;
+#endif // __STDC_VERSION__ >= 202311L
-enum AdScreenshotKind {
+enum AdScreenshotKind
+#if __STDC_VERSION__ >= 202311L
+ : int32_t
+#endif // __STDC_VERSION__ >= 202311L
+ {
AD_SCREENSHOT_KIND_SCREEN = 0,
AD_SCREENSHOT_KIND_WINDOW = 1,
AD_SCREENSHOT_KIND_FULL_SCREEN = 2,
};
+#if __STDC_VERSION__ >= 202311L
+typedef enum AdScreenshotKind AdScreenshotKind;
+#else
typedef int32_t AdScreenshotKind;
+#endif // __STDC_VERSION__ >= 202311L
-enum AdSnapshotSurface {
+enum AdSnapshotSurface
+#if __STDC_VERSION__ >= 202311L
+ : int32_t
+#endif // __STDC_VERSION__ >= 202311L
+ {
AD_SNAPSHOT_SURFACE_WINDOW = 0,
AD_SNAPSHOT_SURFACE_FOCUSED = 1,
AD_SNAPSHOT_SURFACE_MENU = 2,
@@ -112,16 +281,28 @@ enum AdSnapshotSurface {
AD_SNAPSHOT_SURFACE_POPOVER = 5,
AD_SNAPSHOT_SURFACE_ALERT = 6,
};
+#if __STDC_VERSION__ >= 202311L
+typedef enum AdSnapshotSurface AdSnapshotSurface;
+#else
typedef int32_t AdSnapshotSurface;
+#endif // __STDC_VERSION__ >= 202311L
-enum AdWindowOpKind {
+enum AdWindowOpKind
+#if __STDC_VERSION__ >= 202311L
+ : int32_t
+#endif // __STDC_VERSION__ >= 202311L
+ {
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,
};
+#if __STDC_VERSION__ >= 202311L
+typedef enum AdWindowOpKind AdWindowOpKind;
+#else
typedef int32_t AdWindowOpKind;
+#endif // __STDC_VERSION__ >= 202311L
typedef struct AdAdapter AdAdapter;
@@ -140,6 +321,9 @@ typedef struct AdAppList AdAppList;
*/
typedef struct AdImageBuffer AdImageBuffer;
+/**
+ * Opaque notification list returned by `ad_list_notifications`.
+ */
typedef struct AdNotificationList AdNotificationList;
/**
@@ -196,38 +380,20 @@ typedef struct AdPoint {
double y;
} AdPoint;
-/*
- * Caller-allocated drag parameters. Zero-initialize the whole struct before
- * setting fields: `duration_ms`/`drop_delay_ms` treat 0 as the adapter-default
- * sentinel, so stack garbage in an unset field would become a real delay.
- * Validate layout with `AD_DRAG_PARAMS_SIZE` / `ad_drag_params_size()`.
- *
- * Layout history (adjudicated pre-1.0 breaks; revalidate sizes on upgrade,
- * do not re-report): 0.x grew this struct 40 -> 48 bytes by adding
- * `drop_delay_ms` (which also grew the embedding `AdAction` — see
- * `AD_ACTION_SIZE`), `AdRefEntry` grew to 192 bytes (`AD_REF_ENTRY_SIZE`),
- * `AdActionStep` was added as a public 16-byte struct (`AD_ACTION_STEP_SIZE`),
- * `AdActionResult` grew to 40 bytes (`AD_ACTION_RESULT_SIZE`) to expose action
- * steps, and `AD_POLICY_KIND_PHYSICAL` was renamed to `AD_POLICY_KIND_HEADED`
- * with a stable discriminant and intentionally no compatibility alias.
+/**
+ * Caller-allocated drag parameters. Callers must zero-initialize the whole
+ * struct before setting fields so unset numeric fields read as the `0`
+ * adapter-default sentinel rather than stack garbage. Verify layout against
+ * `AD_DRAG_PARAMS_SIZE` / `ad_drag_params_size()` when binding from a language
+ * whose struct layout may diverge.
*/
typedef struct AdDragParams {
struct AdPoint from;
struct AdPoint to;
uint64_t duration_ms;
- /* Milliseconds to hold over the destination before releasing, so the drop
- * target activates (macOS). Zero uses the adapter default (500ms). */
uint64_t drop_delay_ms;
} AdDragParams;
-#define AD_DRAG_PARAMS_SIZE (sizeof(AdDragParams))
-#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
-_Static_assert(sizeof(AdDragParams) == 48, "AdDragParams ABI size changed");
-_Static_assert(_Alignof(AdDragParams) == 8, "AdDragParams ABI alignment changed");
-#endif
-
-uintptr_t ad_drag_params_size(void);
-
/**
* Action dispatched by `ad_execute_action`.
*
@@ -238,10 +404,10 @@ uintptr_t ad_drag_params_size(void);
* discriminants of `AdActionKind`.
*
* `AdDragParams` is embedded by value, so any growth there grows this
- * struct too. Zero-initialize the whole struct before setting fields and
- * validate layout with `AD_ACTION_SIZE` / `ad_action_size()` — an
- * under-allocated action makes the library read past your buffer, and
- * stack garbage in the embedded `drag` fields becomes a live delay.
+ * struct too. Callers must zero-initialize the whole struct and verify
+ * layout against `AD_ACTION_SIZE` / `ad_action_size()` when binding from
+ * a language whose struct layout may diverge — an under-allocated action
+ * makes the library read past the caller's buffer.
*/
typedef struct AdAction {
int32_t kind;
@@ -251,14 +417,6 @@ typedef struct AdAction {
struct AdDragParams drag;
} AdAction;
-#define AD_ACTION_SIZE (sizeof(AdAction))
-#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
-_Static_assert(sizeof(AdAction) == 96, "AdAction ABI size changed");
-_Static_assert(_Alignof(AdAction) == 8, "AdAction ABI alignment changed");
-#endif
-
-uintptr_t ad_action_size(void);
-
typedef struct AdElementState {
const char *role;
char **states;
@@ -266,37 +424,11 @@ typedef struct AdElementState {
const char *value;
} AdElementState;
-#define AD_ELEMENT_STATE_SIZE (sizeof(AdElementState))
-#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
-_Static_assert(sizeof(AdElementState) == 32, "AdElementState ABI size changed");
-_Static_assert(_Alignof(AdElementState) == 8, "AdElementState ABI alignment changed");
-#endif
-
-uintptr_t ad_element_state_size(void);
-
typedef struct AdActionStep {
const char *label;
const char *outcome;
} AdActionStep;
-#define AD_ACTION_STEP_SIZE (sizeof(AdActionStep))
-#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
-_Static_assert(sizeof(AdActionStep) == 16, "AdActionStep ABI size changed");
-_Static_assert(_Alignof(AdActionStep) == 8, "AdActionStep ABI alignment changed");
-_Static_assert(offsetof(AdActionStep, label) == 0, "AdActionStep.label offset changed");
-_Static_assert(offsetof(AdActionStep, outcome) == 8, "AdActionStep.outcome offset changed");
-#endif
-
-uintptr_t ad_action_step_size(void);
-
-/*
- * Result for action calls. `post_state->states` contains `state_count` strings
- * when present. `steps` contains `step_count` activation-chain entries
- * (`label`, `outcome`) when the adapter recorded how the action was attempted.
- * Non-empty owned arrays are additionally null-sentinel terminated by Rust; C
- * callers should use the counts for reads and release the unmodified result via
- * `ad_free_action_result`.
- */
typedef struct AdActionResult {
const char *action;
const char *ref_id;
@@ -305,19 +437,6 @@ typedef struct AdActionResult {
uint32_t step_count;
} AdActionResult;
-#define AD_ACTION_RESULT_SIZE (sizeof(AdActionResult))
-#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
-_Static_assert(sizeof(AdActionResult) == 40, "AdActionResult ABI size changed");
-_Static_assert(_Alignof(AdActionResult) == 8, "AdActionResult ABI alignment changed");
-_Static_assert(offsetof(AdActionResult, action) == 0, "AdActionResult.action offset changed");
-_Static_assert(offsetof(AdActionResult, ref_id) == 8, "AdActionResult.ref_id offset changed");
-_Static_assert(offsetof(AdActionResult, post_state) == 16, "AdActionResult.post_state offset changed");
-_Static_assert(offsetof(AdActionResult, steps) == 24, "AdActionResult.steps offset changed");
-_Static_assert(offsetof(AdActionResult, step_count) == 32, "AdActionResult.step_count offset changed");
-#endif
-
-uintptr_t ad_action_result_size(void);
-
typedef struct AdRect {
double x;
double y;
@@ -332,9 +451,9 @@ typedef struct AdRefEntry {
const char *value;
const char *description;
const char *const *states;
- uintptr_t state_count;
+ size_t state_count;
const char *const *available_actions;
- uintptr_t available_action_count;
+ size_t available_action_count;
struct AdRect bounds;
bool has_bounds;
uint64_t bounds_hash;
@@ -346,34 +465,9 @@ typedef struct AdRefEntry {
const char *root_ref;
bool path_is_absolute;
const uint32_t *path;
- uintptr_t path_count;
+ size_t path_count;
} AdRefEntry;
-#define AD_REF_ENTRY_SIZE (sizeof(AdRefEntry))
-#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
-_Static_assert(sizeof(AdRefEntry) == 192, "AdRefEntry ABI size changed");
-_Static_assert(_Alignof(AdRefEntry) == 8, "AdRefEntry ABI alignment changed");
-#endif
-
-/*
- * Per-field input caps enforced when an `AdRefEntry` crosses the boundary
- * (`ad_resolve_element`, `ad_execute_ref_action_with_policy`). Counts above
- * a cap are rejected with `AD_RESULT_ERR_INVALID_ARGS`.
- */
-#define AD_MAX_REF_STATES 64
-#define AD_MAX_REF_ACTIONS 32
-#define AD_MAX_REF_PATH_DEPTH 128
-
-/*
- * Maximum byte length (excluding the NUL terminator) accepted for any C
- * string field on any call. Longer or unterminated strings are rejected
- * with `AD_RESULT_ERR_INVALID_ARGS`. Sized to roughly match the CLI's argv
- * ceiling so payload-bearing calls (clipboard, type) keep CLI parity.
- */
-#define AD_MAX_STRING_BYTES 1048576
-
-uintptr_t ad_ref_entry_size(void);
-
typedef struct AdWindowInfo {
const char *id;
const char *title;
@@ -390,6 +484,78 @@ typedef struct AdAppInfo {
const char *bundle_id;
} AdAppInfo;
+/**
+ * Arguments for `ad_wait`, mirroring `core::commands::wait::WaitArgs`.
+ *
+ * Fields map as follows:
+ * - `Option<u64>` → `u64` value + `bool has_*` sentinel (ms, count).
+ * - `Option<String>` → nullable `*const c_char` (null = absent).
+ * - `bool` → `bool`.
+ *
+ * Callers must zero-initialize before use and verify layout via
+ * `AD_WAIT_ARGS_SIZE` / `ad_wait_args_size()`.
+ */
+typedef struct AdWaitArgs {
+ /**
+ * Milliseconds to sleep (WaitMode::ms).
+ */
+ uint64_t ms;
+ bool has_ms;
+ /**
+ * Element ref id to wait for (WaitMode::element).
+ */
+ const char *element;
+ /**
+ * Window title to wait for (WaitMode::window).
+ */
+ const char *window;
+ /**
+ * Text to wait for (WaitMode::text / WaitMode::notification text).
+ */
+ const char *text;
+ /**
+ * Wait for menu to open (true) or close (false via menu_closed).
+ */
+ bool menu;
+ /**
+ * Wait for menu to close.
+ */
+ bool menu_closed;
+ /**
+ * Wait for a notification.
+ */
+ bool notification;
+ /**
+ * Snapshot id for element predicate (WaitPredicateArgs::snapshot_id).
+ */
+ const char *snapshot_id;
+ /**
+ * Predicate kind string (WaitPredicateArgs::predicate).
+ */
+ const char *predicate;
+ /**
+ * Expected value for value-predicate (WaitPredicateArgs::value).
+ */
+ const char *value;
+ /**
+ * Action name for actionability-predicate (WaitPredicateArgs::action).
+ */
+ const char *action;
+ /**
+ * Expected match count for text waits (WaitPredicateArgs::count).
+ */
+ size_t count;
+ bool has_count;
+ /**
+ * Timeout in milliseconds.
+ */
+ uint64_t timeout_ms;
+ /**
+ * App name filter (null = any). Maps to WaitArgs::app.
+ */
+ const char *app;
+} AdWaitArgs;
+
/**
* Mouse event dispatched by `ad_mouse_event`.
*
@@ -502,9 +668,34 @@ typedef struct AdWindowOp {
} AdWindowOp;
/**
- * Low-level native-handle action. This does not perform strict ref
- * re-identification or actionability preflight; callers that want CLI parity
- * should use `ad_execute_ref_action_with_policy`.
+ * Returns the packed ABI major version of this dylib build.
+ *
+ * A consumer should compare this to `AD_ABI_VERSION_MAJOR` from the header it
+ * compiled against. If they differ, call nothing further — the ABI is
+ * incompatible.
+ */
+uint32_t ad_abi_version(void);
+
+/**
+ * Checks that the consumer's expected ABI major matches this dylib.
+ *
+ * It is recommended to call this once after `dlopen` / `LoadLibrary` to verify
+ * the header and dylib agree on the major ABI version; a mismatch means they
+ * are incompatible. No global state is initialised by this call — skipping it
+ * does not prevent adapter functions from operating, but undetected ABI
+ * mismatches may cause memory corruption. Returns `AD_RESULT_OK` when
+ * `expected_major == AD_ABI_VERSION_MAJOR`. Returns
+ * `AD_RESULT_ERR_INVALID_ARGS` with a diagnostic last-error when the version
+ * does not match.
+ */
+AdResult ad_init(uint32_t expected_major);
+
+/**
+ * Low-level native-handle action. Dispatches directly to the platform adapter
+ * without strict ref re-identification or actionability preflight. This is a
+ * raw escape hatch for callers that already hold a live native handle. Callers
+ * wanting CLI-semantics parity (RefStore load → strict resolution → preflight
+ * → dispatch) should use `ad_execute_by_ref` instead.
*
* # Safety
*
@@ -520,9 +711,13 @@ AdResult ad_execute_action(const struct AdAdapter *adapter,
struct AdActionResult *out);
/**
- * Low-level native-handle action with explicit interaction policy. This does
- * not perform strict ref re-identification or actionability preflight; callers
- * that want CLI parity should use `ad_execute_ref_action_with_policy`.
+ * Low-level native-handle action with explicit interaction policy. Dispatches
+ * directly to the platform adapter without strict ref re-identification or
+ * actionability preflight. The `policy` discriminant is applied verbatim — no
+ * base-policy elevation is performed. This is a raw escape hatch for callers
+ * that already hold a live native handle. Callers wanting CLI-semantics parity
+ * (RefStore load → strict resolution → preflight → dispatch with base-policy
+ * join) should use `ad_execute_by_ref` instead.
*
* # Safety
*
@@ -539,8 +734,20 @@ AdResult ad_execute_action_with_policy(const struct AdAdapter *adapter,
struct AdActionResult *out);
/**
- * Strict ref action path matching CLI semantics: resolve the full ref identity,
- * run actionability preflight, then dispatch using the requested policy.
+ * Low-level struct-based ref-action path: takes a pre-resolved `AdRefEntry`,
+ * runs strict element re-identification and actionability preflight, then
+ * dispatches using the caller-supplied `policy` verbatim (no base-policy
+ * elevation). The adapter's session context (from `ad_adapter_create_with_session`)
+ * is threaded through so that trace events carry the correct session id.
+ *
+ * This is the low-level escape hatch for callers that have already resolved
+ * a `RefEntry` outside the `RefStore` pipeline (e.g. serialized from an
+ * external snapshot). The `policy` discriminant is applied as-is — there is
+ * no `Action::base_interaction_policy` join here.
+ *
+ * Callers wanting full CLI-semantics parity (RefStore load → `RefMap` lookup
+ * → strict resolution → preflight → dispatch with base-policy join) should
+ * use `ad_execute_by_ref` instead.
*
* # Safety
*
@@ -572,8 +779,7 @@ AdResult ad_execute_ref_action_with_policy(const struct AdAdapter *adapter,
* `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. The adapter that
- * produced the handle must stay alive until the handle is freed.
+ * Callers that legitimately need a "copy" should re-resolve.
*
* # Safety
*
@@ -619,10 +825,37 @@ void ad_free_action_result(struct AdActionResult *result);
struct AdAdapter *ad_adapter_create(void);
/**
+ * Builds a session-scoped platform adapter. `session` may be:
+ * - null: equivalent to `ad_adapter_create()` (no session).
+ * - a valid session id (1-64 ASCII alphanumeric / `-` / `_` chars): associates
+ * the adapter with that session for refmap persistence.
+ * - empty, too long, containing invalid characters, or invalid UTF-8: sets
+ * `ErrInvalidArgs` in the last-error slot and returns null; no adapter is
+ * allocated.
+ *
+ * The returned pointer must be released with `ad_adapter_destroy`.
+ *
* # 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.
+ * `session` must be null or point to readable memory that is NUL-terminated
+ * within `AD_MAX_STRING_BYTES + 1` bytes.
+ */
+struct AdAdapter *ad_adapter_create_with_session(const char *session);
+
+/**
+ * # Safety
+ *
+ * `adapter` must be a pointer returned by `ad_adapter_create` or
+ * `ad_adapter_create_with_session`, or null. After this call the pointer
+ * is invalid and must not be used.
+ *
+ * The adapter must not be destroyed while any other call on it is still in
+ * flight on another thread. Destroying the handle concurrently with an
+ * in-flight call (e.g. `ad_wait` blocking on the main thread while this
+ * function is called from a worker thread) is undefined behaviour — the
+ * `Box` is freed while the blocked call still dereferences it. The caller
+ * owns this synchronisation: ensure all calls on the handle have returned
+ * before calling `ad_adapter_destroy`.
*/
void ad_adapter_destroy(struct AdAdapter *adapter);
@@ -637,8 +870,12 @@ 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, sends SIGTERM, escalates survivors to SIGKILL,
- * and returns success only after termination is verified.
+ * graceful-shutdown path, terminates matching app processes, and escalates
+ * survivors when the platform supports it. Session-critical
+ * processes (loginwindow, WindowServer, Dock, Finder, launchd) are
+ * refused with `AD_RESULT_ERR_INVALID_ARGS` — the protected-process
+ * guard is enforced inside the adapter, so FFI and CLI behave
+ * identically.
*
* # Safety
* `adapter` must be non-null. `id` must be a non-null UTF-8 C string.
@@ -698,6 +935,194 @@ const struct AdAppInfo *ad_app_list_get(const struct AdAppList *list, uint32_t i
*/
void ad_app_list_free(struct AdAppList *list);
+/**
+ * Drives a ref action (`@e5`, action) through the canonical ref-action
+ * pipeline: `RefStore` load → `RefMap` lookup (→ `STALE_REF` on missing) →
+ * strict element resolution (→ `STALE_REF`/`AMBIGUOUS_TARGET`) → live
+ * actionability preflight → dispatch → handle release.
+ *
+ * Policy: `TypeText` defaults to `focus_fallback` (matching the CLI `type`
+ * command); `PressKey` shares that `focus_fallback` base (a ref-targeted key
+ * press may need the target focused); every other action defaults to
+ * `headless`. An explicit `policy` discriminant may *elevate* to headed but
+ * must not downgrade an action below its base. Base and elevation are computed
+ * by `agent_desktop_core::commands::execute_by_ref::execute` via
+ * `Action::base_interaction_policy` + `InteractionPolicy::join`, so CLI and
+ * FFI share a single source of policy truth.
+ *
+ * `ref_id` tri-state: null → `ErrInvalidArgs`; non-null invalid UTF-8 →
+ * `ErrInvalidArgs`; valid UTF-8 but bad `@e{N}` format → `ErrInvalidArgs`.
+ *
+ * `snapshot_id` tri-state: null → use the latest snapshot for the session
+ * (CLI `--snapshot` omitted); valid UTF-8 → pin to that snapshot id; non-null
+ * invalid UTF-8 → `ErrInvalidArgs`.
+ *
+ * `policy` is an `AdPolicyKind` discriminant (0=Headless, 1=FocusFallback,
+ * 2=Headed). An out-of-range value returns `ErrInvalidArgs`. `Headless (0)`
+ * accepts the action's own CLI base (so `TypeText` still uses
+ * `focus_fallback`). `Headed (2)` opts in to cursor-based fallbacks.
+ *
+ * On success `*out` is set to a NUL-terminated JSON envelope (command
+ * `"execute_by_ref"`); free with `ad_free_string`. On guard or decode
+ * failure (invalid args before the command runs) `*out` remains null.
+ * On a command-level error (STALE_REF, AMBIGUOUS_TARGET, etc.) `*out`
+ * holds the error JSON envelope and must still be freed with
+ * `ad_free_string`. The last-error slot is populated on all failures.
+ *
+ * **Dispatch-before-serialize ordering**: the action is dispatched (and any
+ * side effects committed) before the result JSON is serialized. In the
+ * near-impossible event that serialization of an already-valid
+ * `ActionResult` fails, `*out` is null and `ErrInternal` is returned while
+ * the side effect has already occurred. No pre-validation machinery is
+ * needed because serialization of a valid envelope effectively never fails.
+ *
+ * # Safety
+ *
+ * `adapter` must be a non-null pointer from `ad_adapter_create[_with_session]`.
+ * `ref_id` must be a non-null pointer to a NUL-terminated C string within
+ * `AD_MAX_STRING_BYTES + 1` bytes; null is **not** optional — it is defined
+ * behaviour (no UB) but is rejected immediately with `ErrInvalidArgs`.
+ * `snapshot_id` may be null (meaning: use the latest snapshot for this
+ * session) or a non-null NUL-terminated C string within
+ * `AD_MAX_STRING_BYTES + 1` bytes. `action` must be a non-null pointer to a
+ * valid `AdAction`. `out` must be a non-null writable pointer. All pointers
+ * must remain valid for the duration of the call. Must be called from the
+ * main thread on macOS.
+ */
+AdResult ad_execute_by_ref(const struct AdAdapter *adapter,
+ const char *ref_id,
+ const char *snapshot_id,
+ const struct AdAction *action,
+ int32_t policy,
+ char **out);
+
+/**
+ * Takes a full CLI-format snapshot of the target application window,
+ * allocates `@e` refs for all interactive elements, persists the refmap
+ * to disk, and writes the JSON envelope into `*out`.
+ *
+ * The JSON shape matches `agent-desktop snapshot`:
+ * `{"version":"2.0","ok":true,"command":"snapshot","data":{"app":"...","window":{...},"ref_count":N,"snapshot_id":"...","tree":{...}}}`.
+ *
+ * **`*out` ownership and error behaviour:**
+ * - On success (`AD_RESULT_OK`): `*out` is a heap-allocated JSON string with `"ok":true`.
+ * Caller must free it with `ad_free_string`.
+ * - On a command-level error (e.g. app not found, snapshot failure): `*out` is a
+ * heap-allocated JSON string with `"ok":false` and an `"error"` payload. Caller
+ * must still free it with `ad_free_string`. The last-error slot is also set.
+ * - On an argument or infrastructure error (null adapter, off-main-thread, invalid
+ * UTF-8, bad surface discriminant, context failure): `*out` is set to null and no
+ * allocation is made. Only the last-error slot is set.
+ *
+ * `app` is tri-state:
+ * - null — snapshot the currently focused window (same as running the command with no `--app`).
+ * - valid UTF-8 string — snapshot the named application's focused window.
+ * - non-null but invalid UTF-8 or exceeding `AD_MAX_STRING_BYTES` — returns `ErrInvalidArgs`.
+ *
+ * `surface` is an `AdSnapshotSurface` discriminant (0 = Window, 1 = Focused, …).
+ * An out-of-range value returns `ErrInvalidArgs`.
+ *
+ * This entrypoint always targets the active focused window of the requested
+ * application; explicit window targeting (`window_id`) is not yet exposed
+ * over the ABI. Progressive traversal (skeleton mode and `--root` drill-down)
+ * is likewise not exposed here. Both are planned fast-follows to this
+ * entrypoint — agents needing them should use the CLI in the meantime.
+ *
+ * **Dispatch-before-serialize ordering**: the snapshot and refmap persistence
+ * occur before the result JSON is serialised. In the near-impossible event
+ * that serialisation of an already-valid result fails, `*out` is set to null
+ * and `ErrInternal` is returned while the refmap is already written.
+ *
+ * # Safety
+ *
+ * `adapter` must be a non-null pointer from `ad_adapter_create` or
+ * `ad_adapter_create_with_session`. `out` must be a non-null writable
+ * `*mut *mut c_char`. `app` must be null or a NUL-terminated string within
+ * `AD_MAX_STRING_BYTES + 1` bytes. All pointers must remain valid for the
+ * duration of the call. `adapter` must be used from the main thread on macOS.
+ */
+AdResult ad_snapshot(const struct AdAdapter *adapter,
+ const char *app,
+ int32_t surface,
+ uint8_t max_depth,
+ bool interactive_only,
+ bool compact,
+ char **out);
+
+/**
+ * Returns the adapter's current health and permission state as a JSON
+ * envelope matching the `agent-desktop status` CLI output.
+ *
+ * `ad_status` does not query the accessibility tree; it reads the
+ * permission report and ref-store metadata only, so it is safe to call
+ * from any thread (unlike tree-traversal commands that require the
+ * macOS main thread). On success `*out` is a NUL-terminated,
+ * heap-allocated JSON string freed with `ad_free_string`.
+ *
+ * On a command-level failure `*out` is set to a heap-allocated JSON string
+ * with `"ok":false` and an `"error"` payload. The caller must still release
+ * it with `ad_free_string(*out)`. The last-error slot is also set.
+ *
+ * On an argument or infrastructure failure (null adapter, null out, context
+ * error) `*out` is zeroed and only the last-error slot is populated.
+ *
+ * # Safety
+ *
+ * `adapter` must be a non-null pointer returned by `ad_adapter_create`
+ * that has not been destroyed. `out` must be a non-null writable
+ * `*mut *mut c_char`.
+ */
+AdResult ad_status(const struct AdAdapter *adapter, char **out);
+
+/**
+ * Returns the `agent-desktop` version envelope as an owned JSON C string.
+ *
+ * The returned string has the same `{version, ok, command, data}` shape
+ * as `agent-desktop version` on the CLI. Free it with `ad_free_string`.
+ *
+ * On success `*out` points to the envelope JSON.
+ * On error `*out` is null and the last-error slot is populated.
+ *
+ * # Safety
+ * `out` must be a non-null writable `*mut *mut c_char`.
+ */
+AdResult ad_version(char **out);
+
+/**
+ * Runs `wait` with the given args, blocking the calling thread until the
+ * condition is met or `timeout_ms` elapses.
+ *
+ * On success `*out` is set to a freshly allocated JSON string containing the
+ * CLI-format wait envelope (`{version, ok, command, data}`). The caller must
+ * release the string with `ad_free_string(*out)`.
+ *
+ * On a command-level failure (e.g. `TIMEOUT`, `ELEMENT_NOT_FOUND`) `*out` is
+ * set to a freshly allocated JSON string with `"ok":false` and an `"error"`
+ * payload. The caller must still release it with `ad_free_string(*out)`. The
+ * last-error slot is also set.
+ *
+ * On an argument or infrastructure failure (null adapter, null args, null out,
+ * off-main-thread, invalid UTF-8 field) `*out` is zeroed, the last-error slot
+ * is set, and a negative `AdResult` code is returned. No allocation is made.
+ *
+ * # Safety
+ *
+ * `adapter` must be a non-null pointer returned by `ad_adapter_create` that
+ * has not been destroyed. `args` must be non-null and point to a valid
+ * zero-initialized `AdWaitArgs`. `out` must be non-null and point to a
+ * writable `*mut c_char`.
+ *
+ * All `*const c_char` fields inside `AdWaitArgs` must be null or point to
+ * readable, NUL-terminated memory within `AD_MAX_STRING_BYTES + 1` bytes.
+ *
+ * `ad_wait` blocks the calling thread for up to `timeout_ms` milliseconds
+ * while it holds a live reference into the adapter's allocation. The adapter
+ * must outlive the call: do not call `ad_adapter_destroy` on this handle from
+ * another thread while `ad_wait` is running — that is a use-after-free. Ensure
+ * the wait has returned before destroying the adapter.
+ */
+AdResult ad_wait(const struct AdAdapter *adapter, const struct AdWaitArgs *args, char **out);
+
/**
* Last-error lifetime — errno-style.
*
@@ -743,11 +1168,11 @@ const char *ad_last_error_suggestion(void);
const char *ad_last_error_platform_detail(void);
/**
- * Returns a borrowed JSON string with structured details for the last
- * error, or null if the adapter didn't supply one. Same lifetime rules
- * as `ad_last_error_message`. Details may contain element names, values,
- * and window titles from the user's screen; treat as sensitive
- * diagnostics and avoid routing to shared log surfaces.
+ * Returns a borrowed JSON string carrying structured details for the last
+ * error, or null if the adapter didn't supply any. Same lifetime rules as
+ * `ad_last_error_message`. Details may contain element names, values, and
+ * window titles from the user's screen; treat as sensitive diagnostics and
+ * avoid routing to shared log surfaces.
*/
const char *ad_last_error_details(void);
@@ -794,9 +1219,7 @@ void ad_free_string(char *s);
/**
* Synthesizes an explicit physical 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.
- * `params.drop_delay_ms` holds the item over the destination before releasing
- * so the drop target activates; zero uses the adapter default. Callers that
+ * a non-zero value asks the platform adapter to interpolate. Callers that
* need headless policy enforcement should use ref actions with policy.
*
* # Safety
@@ -808,8 +1231,8 @@ AdResult ad_drag(const struct AdAdapter *adapter, const struct AdDragParams *par
/**
* Dispatches an explicit physical 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). Callers that need
- * headless policy enforcement should use ref actions with policy.
+ * is `CLICK` (e.g., `click_count == 2` for a double-click). Callers that
+ * need headless policy enforcement should use ref actions with policy.
*
* # Safety
* `adapter` must be a non-null pointer returned by `ad_adapter_create`.
@@ -817,6 +1240,49 @@ AdResult ad_drag(const struct AdAdapter *adapter, const struct AdDragParams *par
*/
AdResult ad_mouse_event(const struct AdAdapter *adapter, const struct AdMouseEvent *event);
+/**
+ * Registers a callback to receive `tracing` events, or unregisters the
+ * current callback when `cb` is `NULL`.
+ *
+ * # Install semantics
+ *
+ * The subscriber layer is installed exactly once — on the first call with a
+ * non-null `cb`. If a foreign global subscriber already owns the process at
+ * that point, the install fails and this function returns
+ * `AD_RESULT_ERR_INTERNAL` with a diagnostic last-error. No callback pointer
+ * is stored in that case; events will never be delivered until the consumer
+ * remedies the conflict. Subsequent calls with a non-null `cb` after a
+ * **successful** install only swap the stored pointer and always return
+ * `AD_RESULT_OK`.
+ *
+ * `NULL` always returns `AD_RESULT_OK` — unregistering cannot fail.
+ *
+ * # Callback contract
+ *
+ * - `level` — 1 (ERROR) … 5 (TRACE)
+ * - `msg` — a NUL-terminated JSON string; valid only for the call's duration
+ *
+ * Sensitive field values (password, token, text, …) are replaced with
+ * `{"redacted":true}` before the message is formatted.
+ *
+ * Invocations are best-effort. A panicking callback is caught and silently
+ * discarded; no command fails because of a trace delivery error. A callback
+ * that emits `tracing` events is safe: the recursive `on_event` is dropped
+ * by a per-thread guard before it reaches the callback again.
+ *
+ * # Safety
+ *
+ * `cb` must be null or a valid function pointer with the declared signature.
+ * The pointer is stored atomically; the subscriber may call it from threads
+ * other than the registering thread.
+ *
+ * A callback unregistered via `NULL` may still be invoked from another thread
+ * for a brief window after this call returns. The callback (and any data it
+ * captures) must remain valid for the process lifetime, or the caller must
+ * quiesce all tracing sources before unregistering.
+ */
+AdResult ad_set_log_callback(void (*cb)(int32_t level, const char *msg));
+
/**
* Triggers the named action on the notification at `index`. Typical
* action names are those reported in `AdNotificationInfo.actions`
@@ -952,6 +1418,11 @@ void ad_notification_list_free(struct AdNotificationList *list);
* - `name_substring` against `AccessibilityNode.name`
* - `value_substring` against `AccessibilityNode.value`
*
+ * The internal tree fetch always sets `include_bounds: true` so
+ * `resolve_element_strict` can disambiguate duplicate-label siblings via
+ * `bounds_hash`; without bounds on the matched node the resolver falls
+ * back to role+name alone and may pick the wrong element.
+ *
* # Safety
* `adapter`, `win`, and `query` must be valid pointers. `out_handle`
* must be a valid writable `*mut AdNativeHandle`. On
@@ -1139,27 +1610,32 @@ void ad_free_tree(struct AdNodeTree *tree);
*
* # 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.
+ * This is a **raw adapter tree** — ref-less, no refmap persistence, and
+ * no JSON envelope. Differences the caller must know about:
+ *
+ * - `ref_id` is always null on every `AdNode`. `ref_alloc::allocate_refs`
+ * is not run; `@e` ref assignment is a snapshot-pipeline concern.
+ * - `include_bounds`, `interactive_only`, and `compact` are honoured via
+ * `ref_alloc::transform_tree` after the adapter returns. Because refs are
+ * not allocated, the `interactive_only` cut is role-based rather than
+ * ref-based; otherwise the semantics match the 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.
+ * # When to use this function vs `ad_snapshot`
+ *
+ * **Observe–act agents** that need `@e` refs and refmap persistence should
+ * call `ad_snapshot` instead. `ad_snapshot` runs the full snapshot pipeline
+ * (ref allocation, refmap write to disk, JSON envelope with
+ * `{"version":"2.0","ok":true,...}`) and is the correct starting point for
+ * any workflow that drives subsequent ref-based actions via
+ * `ad_execute_by_ref` (with an `AdAction`).
+ *
+ * Use `ad_get_tree` when you need the raw flat BFS layout without refs —
+ * for example, to drive your own traversal logic or to populate a UI
+ * inspector that does not use the ref-based action API. For point lookups
+ * that bypass tree shape entirely, `ad_find` + `ad_get` / `ad_is` are
+ * another alternative.
*
* On error `*out` is zeroed so `ad_free_tree` on it is a safe no-op.
*
@@ -1172,6 +1648,25 @@ AdResult ad_get_tree(const struct AdAdapter *adapter,
const struct AdTreeOptions *opts,
struct AdNodeTree *out);
+size_t ad_action_size(void);
+
+size_t ad_action_result_size(void);
+
+size_t ad_action_step_size(void);
+
+size_t ad_drag_params_size(void);
+
+size_t ad_element_state_size(void);
+
+size_t ad_ref_entry_size(void);
+
+/**
+ * Returns the size of `AdWaitArgs` as compiled. Ctypes and other
+ * foreign bindings must call this and compare against their own
+ * `sizeof` before passing args to `ad_wait`.
+ */
+size_t ad_wait_args_size(void);
+
/**
* Brings `win` to the foreground on the current space. Returns
* `AD_RESULT_ERR_WINDOW_NOT_FOUND` when the referenced window no longer
@@ -1252,3 +1747,35 @@ AdResult ad_window_op(const struct AdAdapter *adapter,
struct AdWindowOp op);
#endif /* AGENT_DESKTOP_H */
+
+/* C11 ABI layout guards — auto-generated; do not hand-edit.
+ * Each sizeof check references the AD_*_SIZE macro defined above so the
+ * size literal lives in exactly one place (the Rust source). Alignment
+ * and offset values are structurally fixed on all 64-bit targets.
+ * The one-shot guard makes double-include safe regardless of C standard. */
+#ifndef AGENT_DESKTOP_ABI_ASSERTS
+#define AGENT_DESKTOP_ABI_ASSERTS
+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
+_Static_assert(sizeof(AdDragParams) == AD_DRAG_PARAMS_SIZE, "AdDragParams ABI size changed");
+_Static_assert(_Alignof(AdDragParams) == 8, "AdDragParams ABI alignment changed");
+_Static_assert(sizeof(AdAction) == AD_ACTION_SIZE, "AdAction ABI size changed");
+_Static_assert(_Alignof(AdAction) == 8, "AdAction ABI alignment changed");
+_Static_assert(sizeof(AdElementState) == AD_ELEMENT_STATE_SIZE, "AdElementState ABI size changed");
+_Static_assert(_Alignof(AdElementState) == 8, "AdElementState ABI alignment changed");
+_Static_assert(sizeof(AdActionStep) == AD_ACTION_STEP_SIZE, "AdActionStep ABI size changed");
+_Static_assert(_Alignof(AdActionStep) == 8, "AdActionStep ABI alignment changed");
+_Static_assert(offsetof(AdActionStep, label) == 0, "AdActionStep.label offset changed");
+_Static_assert(offsetof(AdActionStep, outcome) == 8, "AdActionStep.outcome offset changed");
+_Static_assert(sizeof(AdActionResult) == AD_ACTION_RESULT_SIZE, "AdActionResult ABI size changed");
+_Static_assert(_Alignof(AdActionResult) == 8, "AdActionResult ABI alignment changed");
+_Static_assert(offsetof(AdActionResult, action) == 0, "AdActionResult.action offset changed");
+_Static_assert(offsetof(AdActionResult, ref_id) == 8, "AdActionResult.ref_id offset changed");
+_Static_assert(offsetof(AdActionResult, post_state) == 16, "AdActionResult.post_state offset changed");
+_Static_assert(offsetof(AdActionResult, steps) == 24, "AdActionResult.steps offset changed");
+_Static_assert(offsetof(AdActionResult, step_count) == 32, "AdActionResult.step_count offset changed");
+_Static_assert(sizeof(AdRefEntry) == AD_REF_ENTRY_SIZE, "AdRefEntry ABI size changed");
+_Static_assert(_Alignof(AdRefEntry) == 8, "AdRefEntry ABI alignment changed");
+_Static_assert(sizeof(struct AdWaitArgs) == AD_WAIT_ARGS_SIZE, "AdWaitArgs ABI size drift");
+_Static_assert(_Alignof(struct AdWaitArgs) == 8, "AdWaitArgs ABI alignment changed");
+#endif /* __STDC_VERSION__ >= 201112L */
+#endif /* AGENT_DESKTOP_ABI_ASSERTS */
diff --git a/crates/ffi/src/abi_version.rs b/crates/ffi/src/abi_version.rs
new file mode 100644
index 000000000..c2c50ee54
--- /dev/null
+++ b/crates/ffi/src/abi_version.rs
@@ -0,0 +1,50 @@
+use crate::error::{AdResult, set_last_error_static};
+use crate::ffi_try::trap_panic;
+use std::ffi::CStr;
+
+/// The major ABI version of this build of `libagent_desktop_ffi`.
+///
+/// Version-bump rule: increment this constant (and update the header via
+/// `scripts/update-ffi-header.sh`) whenever a breaking change is made to the
+/// C ABI — a removed or incompatibly-changed `ad_*` symbol, or a layout
+/// change to any `repr(C)` struct. Additive changes (new `ad_*` symbols, new
+/// error codes) do **not** require a bump. It is recommended to call `ad_init`
+/// with the major compiled against the header to verify ABI compatibility; a
+/// mismatch means the header and dylib are incompatible and the consumer should
+/// refuse to proceed rather than risk undefined behaviour.
+pub const AD_ABI_VERSION_MAJOR: u32 = 1;
+
+static MISMATCH_MESSAGE: &CStr =
+ c"ABI major version mismatch: recompile against the installed header";
+
+/// Returns the packed ABI major version of this dylib build.
+///
+/// A consumer should compare this to `AD_ABI_VERSION_MAJOR` from the header it
+/// compiled against. If they differ, call nothing further — the ABI is
+/// incompatible.
+#[unsafe(no_mangle)]
+pub extern "C" fn ad_abi_version() -> u32 {
+ AD_ABI_VERSION_MAJOR
+}
+
+/// Checks that the consumer's expected ABI major matches this dylib.
+///
+/// It is recommended to call this once after `dlopen` / `LoadLibrary` to verify
+/// the header and dylib agree on the major ABI version; a mismatch means they
+/// are incompatible. No global state is initialised by this call — skipping it
+/// does not prevent adapter functions from operating, but undetected ABI
+/// mismatches may cause memory corruption. Returns `AD_RESULT_OK` when
+/// `expected_major == AD_ABI_VERSION_MAJOR`. Returns
+/// `AD_RESULT_ERR_INVALID_ARGS` with a diagnostic last-error when the version
+/// does not match.
+#[unsafe(no_mangle)]
+pub extern "C" fn ad_init(expected_major: u32) -> AdResult {
+ trap_panic(|| {
+ if expected_major == AD_ABI_VERSION_MAJOR {
+ AdResult::Ok
+ } else {
+ set_last_error_static(AdResult::ErrInvalidArgs, MISMATCH_MESSAGE);
+ AdResult::ErrInvalidArgs
+ }
+ })
+}
diff --git a/crates/ffi/src/actions/execute.rs b/crates/ffi/src/actions/execute.rs
index c3a2ee38b..e4ea8889a 100644
--- a/crates/ffi/src/actions/execute.rs
+++ b/crates/ffi/src/actions/execute.rs
@@ -1,11 +1,18 @@
use crate::AdAdapter;
use crate::actions::conversion::action_from_c;
use crate::actions::result::action_result_to_c;
+use crate::commands::app_error_to_adapter;
use crate::error::{self, AdResult};
use crate::ffi_try::trap_panic;
use crate::types::{AdAction, AdActionResult, AdNativeHandle, AdPolicyKind, AdRefEntry};
use agent_desktop_core::{action::Action, action_request::ActionRequest, adapter::NativeHandle};
+/// Low-level native-handle action. Dispatches directly to the platform adapter
+/// without strict ref re-identification or actionability preflight. This is a
+/// raw escape hatch for callers that already hold a live native handle. Callers
+/// wanting CLI-semantics parity (RefStore load → strict resolution → preflight
+/// → dispatch) should use `ad_execute_by_ref` instead.
+///
/// # Safety
///
/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.
@@ -25,6 +32,14 @@ pub unsafe extern "C" fn ad_execute_action(
}
}
+/// Low-level native-handle action with explicit interaction policy. Dispatches
+/// directly to the platform adapter without strict ref re-identification or
+/// actionability preflight. The `policy` discriminant is applied verbatim — no
+/// base-policy elevation is performed. This is a raw escape hatch for callers
+/// that already hold a live native handle. Callers wanting CLI-semantics parity
+/// (RefStore load → strict resolution → preflight → dispatch with base-policy
+/// join) should use `ad_execute_by_ref` instead.
+///
/// # Safety
///
/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.
@@ -81,6 +96,21 @@ pub unsafe extern "C" fn ad_execute_action_with_policy(
})
}
+/// Low-level struct-based ref-action path: takes a pre-resolved `AdRefEntry`,
+/// runs strict element re-identification and actionability preflight, then
+/// dispatches using the caller-supplied `policy` verbatim (no base-policy
+/// elevation). The adapter's session context (from `ad_adapter_create_with_session`)
+/// is threaded through so that trace events carry the correct session id.
+///
+/// This is the low-level escape hatch for callers that have already resolved
+/// a `RefEntry` outside the `RefStore` pipeline (e.g. serialized from an
+/// external snapshot). The `policy` discriminant is applied as-is — there is
+/// no `Action::base_interaction_policy` join here.
+///
+/// Callers wanting full CLI-semantics parity (RefStore load → `RefMap` lookup
+/// → strict resolution → preflight → dispatch with base-policy join) should
+/// use `ad_execute_by_ref` instead.
+///
/// # Safety
///
/// `adapter` must be a non-null pointer returned by `ad_adapter_create`.
@@ -104,7 +134,7 @@ pub unsafe extern "C" fn ad_execute_ref_action_with_policy(
crate::pointer_guard::guard_non_null!(adapter, c"adapter is null");
crate::pointer_guard::guard_non_null!(entry, c"entry is null");
crate::pointer_guard::guard_non_null!(action, c"action is null");
- let adapter = &*adapter;
+ let adapter_ref = &*adapter;
let entry_ref = &*entry;
let core_entry = match crate::actions::resolve::core_ref_entry_from_ffi(entry_ref) {
Ok(entry) => entry,
@@ -122,10 +152,18 @@ pub unsafe extern "C" fn ad_execute_ref_action_with_policy(
Err(result) => return result,
};
let request = action_request(policy, core_action);
- match agent_desktop_core::ref_action::execute_entry(
- adapter.inner.as_ref(),
+ let context = match adapter_ref.command_context() {
+ Ok(ctx) => ctx,
+ Err(err) => {
+ error::set_last_error(&app_error_to_adapter(err));
+ return error::last_error_code();
+ }
+ };
+ match agent_desktop_core::ref_action::execute_entry_with_context(
+ adapter_ref.inner.as_ref(),
&core_entry,
request,
+ &context,
) {
Ok(result) => {
*out = action_result_to_c(&result);
@@ -160,10 +198,9 @@ fn decode_policy(policy: i32) -> Result<AdPolicyKind, AdResult> {
}
fn action_request(policy: AdPolicyKind, action: Action) -> ActionRequest {
- match policy {
- AdPolicyKind::Headless => ActionRequest::headless(action),
- AdPolicyKind::FocusFallback => ActionRequest::focus_fallback(action),
- AdPolicyKind::Headed => ActionRequest::headed(action),
+ ActionRequest {
+ action,
+ policy: policy.to_interaction_policy(),
}
}
diff --git a/crates/ffi/src/actions/resolve_tests.rs b/crates/ffi/src/actions/resolve_tests.rs
index d96084835..a26637438 100644
--- a/crates/ffi/src/actions/resolve_tests.rs
+++ b/crates/ffi/src/actions/resolve_tests.rs
@@ -196,7 +196,7 @@ fn ffi_ref_entry_rejects_oversized_path_count() {
#[test]
fn ffi_ref_entry_rejects_unterminated_name_within_byte_cap() {
let role = CString::new("button").unwrap();
- let unterminated = vec![b'a'; crate::convert::string::MAX_C_STRING_BYTES + 1];
+ let unterminated = vec![b'a'; crate::convert::string::AD_MAX_STRING_BYTES + 1];
let mut entry = test_ref_entry();
entry.role = role.as_ptr();
entry.name = unterminated.as_ptr().cast();
diff --git a/crates/ffi/src/adapter.rs b/crates/ffi/src/adapter.rs
index 163d1b0c0..f5b5c65f5 100644
--- a/crates/ffi/src/adapter.rs
+++ b/crates/ffi/src/adapter.rs
@@ -1,9 +1,14 @@
+use crate::convert::string::optional_adapter_string;
use crate::error::{self, AdResult};
use crate::ffi_try::{trap_panic, trap_panic_ptr, trap_panic_void};
+use agent_desktop_core::context::{CommandContext, validate_session_id};
+use agent_desktop_core::error::{AdapterError, AppError};
use agent_desktop_core::{PermissionState, adapter::PlatformAdapter};
+use std::ffi::c_char;
pub struct AdAdapter {
pub(crate) inner: Box<dyn PlatformAdapter>,
+ pub(crate) session_id: Option<String>,
}
fn build_adapter() -> Box<dyn PlatformAdapter> {
@@ -38,15 +43,70 @@ pub extern "C" fn ad_adapter_create() -> *mut AdAdapter {
trap_panic_ptr(|| {
let adapter = AdAdapter {
inner: build_adapter(),
+ session_id: None,
};
Box::into_raw(Box::new(adapter))
})
}
+/// Builds a session-scoped platform adapter. `session` may be:
+/// - null: equivalent to `ad_adapter_create()` (no session).
+/// - a valid session id (1-64 ASCII alphanumeric / `-` / `_` chars): associates
+/// the adapter with that session for refmap persistence.
+/// - empty, too long, containing invalid characters, or invalid UTF-8: sets
+/// `ErrInvalidArgs` in the last-error slot and returns null; no adapter is
+/// allocated.
+///
+/// The returned pointer must be released with `ad_adapter_destroy`.
+///
/// # 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.
+/// `session` must be null or point to readable memory that is NUL-terminated
+/// within `AD_MAX_STRING_BYTES + 1` bytes.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn ad_adapter_create_with_session(session: *const c_char) -> *mut AdAdapter {
+ trap_panic_ptr(|| {
+ let session_id = match optional_adapter_string(session, "session") {
+ Ok(opt) => opt,
+ Err(err) => {
+ error::set_last_error(&err);
+ return std::ptr::null_mut();
+ }
+ };
+ if let Some(id) = session_id.as_deref() {
+ if let Err(app_err) = validate_session_id(id) {
+ let adapter_err = match app_err {
+ AppError::Adapter(e) => e,
+ other => AdapterError::new(
+ agent_desktop_core::error::ErrorCode::InvalidArgs,
+ other.to_string(),
+ ),
+ };
+ error::set_last_error(&adapter_err);
+ return std::ptr::null_mut();
+ }
+ }
+ let adapter = AdAdapter {
+ inner: build_adapter(),
+ session_id,
+ };
+ Box::into_raw(Box::new(adapter))
+ })
+}
+
+/// # Safety
+///
+/// `adapter` must be a pointer returned by `ad_adapter_create` or
+/// `ad_adapter_create_with_session`, or null. After this call the pointer
+/// is invalid and must not be used.
+///
+/// The adapter must not be destroyed while any other call on it is still in
+/// flight on another thread. Destroying the handle concurrently with an
+/// in-flight call (e.g. `ad_wait` blocking on the main thread while this
+/// function is called from a worker thread) is undefined behaviour — the
+/// `Box` is freed while the blocked call still dereferences it. The caller
+/// owns this synchronisation: ensure all calls on the handle have returned
+/// before calling `ad_adapter_destroy`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn ad_adapter_destroy(adapter: *mut AdAdapter) {
trap_panic_void(|| {
@@ -83,6 +143,15 @@ pub unsafe extern "C" fn ad_check_permissions(adapter: *const AdAdapter) -> AdRe
})
}
+impl AdAdapter {
+ /// Builds a `CommandContext` from this adapter's session. Callers that
+ /// need a context for context-taking commands (snapshot, status, wait)
+ /// call this at the FFI entry boundary.
+ pub fn command_context(&self) -> Result<CommandContext, AppError> {
+ CommandContext::new(self.session_id.clone(), None, false)
+ }
+}
+
fn unknown_permission_result(adapter: &dyn PlatformAdapter) -> AdResult {
let (code, message, suggestion) = if adapter.unknown_accessibility_means_unsupported() {
(
@@ -135,6 +204,7 @@ mod tests {
fn check_permissions_maps_default_unknown_accessibility_to_platform_unsupported() {
let adapter = AdAdapter {
inner: Box::new(UnknownPermissionAdapter),
+ session_id: None,
};
let result = unsafe { ad_check_permissions(&adapter) };
@@ -162,6 +232,7 @@ mod tests {
fn check_permissions_preserves_ambiguous_unknown_accessibility_as_internal() {
let adapter = AdAdapter {
inner: Box::new(AmbiguousPermissionAdapter),
+ session_id: None,
};
let result = unsafe { ad_check_permissions(&adapter) };
diff --git a/crates/ffi/src/apps/mod.rs b/crates/ffi/src/apps/mod.rs
index 214338fbd..7a5a9ef62 100644
--- a/crates/ffi/src/apps/mod.rs
+++ b/crates/ffi/src/apps/mod.rs
@@ -12,7 +12,7 @@ fn decode_app_id(id: *const c_char) -> Result<String, AdapterError> {
#[cfg(test)]
mod tests {
use super::*;
- use crate::convert::string::{MAX_C_STRING_BYTES, string_to_c};
+ use crate::convert::string::{AD_MAX_STRING_BYTES, string_to_c};
#[test]
fn app_id_rejects_null() {
@@ -31,7 +31,7 @@ mod tests {
#[test]
fn app_id_rejects_overlong_input() {
- let bytes = vec![b'a'; MAX_C_STRING_BYTES + 1];
+ let bytes = vec![b'a'; AD_MAX_STRING_BYTES + 1];
let err = decode_app_id(bytes.as_ptr().cast()).unwrap_err();
assert!(
diff --git a/crates/ffi/src/commands/envelope_out.rs b/crates/ffi/src/commands/envelope_out.rs
new file mode 100644
index 000000000..ecba38d64
--- /dev/null
+++ b/crates/ffi/src/commands/envelope_out.rs
@@ -0,0 +1,157 @@
+use crate::commands::app_error_to_adapter;
+use crate::convert::string::string_to_c;
+use crate::error::{AdResult, set_last_error};
+use agent_desktop_core::error::{AdapterError, AppError, ErrorCode};
+use agent_desktop_core::output::{ErrorPayload, Response};
+use serde_json::Value;
+use std::ffi::c_char;
+
+/// Serialises a command result into a JSON envelope and writes the heap-allocated
+/// C string into `*out`.
+///
+/// **Ok path** (`result` is `Ok(data)`): builds `Response::ok(command, data)`,
+/// serialises it, writes the pointer into `*out`, and returns `AdResult::Ok`.
+/// The last-error slot is not touched — preserving any prior error across
+/// successful calls (errno invariant).
+///
+/// **Err path** (`result` is `Err(app_err)`): builds `Response::err(command,
+/// payload)` with the full error details, serialises it into `*out` (so
+/// JSON-first consumers can inspect the error envelope), sets last-error, and
+/// returns the matching negative `AdResult` code via `last_error_code()`.
+/// The returned code is always identical to the code stored in last-error
+/// (errno invariant).
+///
+/// **Serialisation/NUL failure** (interior NUL or `serde_json` error): sets
+/// last-error to `ErrInternal`, leaves `*out` null, and returns `ErrInternal`.
+///
+/// # Contract
+///
+/// This helper covers only **command-level** results — i.e. after all argument
+/// guards have passed and the command has actually executed. Pointer-guard
+/// rejections (null `adapter`, null `out`, invalid-UTF-8 args) must keep
+/// returning early with `*out` null; they must never call this helper.
+///
+/// The caller is responsible for zeroing `*out` before entering the command
+/// body. `ad_free_string` must be called on any non-null `*out` after use,
+/// regardless of whether the envelope carries `"ok":true` or `"ok":false`.
+///
+/// # Safety
+///
+/// `out` must be a non-null writable `*mut *mut c_char`. The caller guarantees
+/// this via the `guard_non_null!(out, …)` check that precedes every command
+/// body — this function does not re-validate it.
+pub(crate) unsafe fn write_command_envelope(
+ command: &str,
+ result: Result<Value, AppError>,
+ out: *mut *mut c_char,
+) -> AdResult {
+ let (envelope, had_error) = match result {
+ Ok(data) => (Response::ok(command, data), false),
+ Err(app_err) => {
+ let payload = ErrorPayload::from_app_error(&app_err);
+ let ae = app_error_to_adapter(app_err);
+ set_last_error(&ae);
+ (Response::err(command, payload), true)
+ }
+ };
+
+ let json = match serde_json::to_string(&envelope) {
+ Ok(s) => s,
+ Err(e) => {
+ let ae = AdapterError::new(
+ ErrorCode::Internal,
+ format!("failed to serialize {command} envelope: {e}"),
+ );
+ set_last_error(&ae);
+ return AdResult::ErrInternal;
+ }
+ };
+
+ let c_ptr = string_to_c(&json);
+ if c_ptr.is_null() {
+ let ae = AdapterError::new(
+ ErrorCode::Internal,
+ format!("{command} JSON contains interior NUL"),
+ );
+ set_last_error(&ae);
+ return AdResult::ErrInternal;
+ }
+
+ unsafe { *out = c_ptr };
+
+ if had_error {
+ crate::error::last_error_code()
+ } else {
+ AdResult::Ok
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::convert::string::free_c_string;
+ use crate::error::{clear_last_error, last_error_code};
+ use agent_desktop_core::error::AdapterError;
+ use std::ffi::CStr;
+
+ unsafe fn read_and_free(out: *mut c_char) -> String {
+ let s = unsafe { CStr::from_ptr(out) }
+ .to_string_lossy()
+ .into_owned();
+ unsafe { free_c_string(out) };
+ s
+ }
+
+ #[test]
+ fn err_path_writes_envelope_and_sets_errno() {
+ clear_last_error();
+ let mut out: *mut c_char = std::ptr::null_mut();
+ let err = AppError::stale_ref("@e99");
+ let rc = unsafe { write_command_envelope("wait", Err(err), &mut out) };
+
+ assert_eq!(
+ rc,
+ AdResult::ErrStaleRef,
+ "returned code must be ErrStaleRef"
+ );
+ assert_eq!(
+ last_error_code(),
+ AdResult::ErrStaleRef,
+ "errno must equal returned code"
+ );
+ assert!(
+ !out.is_null(),
+ "*out must be non-null on command-level error"
+ );
+
+ let json = unsafe { read_and_free(out) };
+ let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
+ assert_eq!(parsed["ok"], false);
+ assert_eq!(parsed["command"], "wait");
+ assert_eq!(parsed["error"]["code"], "STALE_REF");
+ }
+
+ #[test]
+ fn ok_path_writes_envelope_and_preserves_prior_errno() {
+ let prior = AdapterError::new(ErrorCode::Timeout, "prior error");
+ set_last_error(&prior);
+
+ let mut out: *mut c_char = std::ptr::null_mut();
+ let rc = unsafe {
+ write_command_envelope("status", Ok(serde_json::json!({"running": true})), &mut out)
+ };
+
+ assert_eq!(rc, AdResult::Ok, "returned code must be Ok on success");
+ assert_eq!(
+ last_error_code(),
+ AdResult::ErrTimeout,
+ "success must not clear prior last-error"
+ );
+ assert!(!out.is_null(), "*out must be non-null on success");
+
+ let json = unsafe { read_and_free(out) };
+ let parsed: serde_json::Value = serde_json::from_str(&json).expect("valid JSON");
+ assert_eq!(parsed["ok"], true);
+ assert_eq!(parsed["command"], "status");
+ }
+}
diff --git a/crates/ffi/src/commands/execute_by_ref.rs b/crates/ffi/src/commands/execute_by_ref.rs
new file mode 100644
index 000000000..94d209bda
--- /dev/null
+++ b/crates/ffi/src/commands/execute_by_ref.rs
@@ -0,0 +1,224 @@
+use crate::AdAdapter;
+use crate::actions::conversion::action_from_c;
+use crate::commands::app_error_to_adapter;
+use crate::commands::envelope_out::write_command_envelope;
+use crate::convert::string::{optional_adapter_string, required_adapter_string};
+use crate::error::{AdResult, set_last_error};
+use crate::ffi_try::trap_panic;
+use crate::main_thread::require_main_thread;
+use crate::pointer_guard::guard_non_null;
+use crate::types::{AdAction, AdPolicyKind};
+use agent_desktop_core::error::{AdapterError, ErrorCode};
+use agent_desktop_core::refs::validate_ref_id;
+use std::ffi::c_char;
+use std::ptr;
+
+/// Drives a ref action (`@e5`, action) through the canonical ref-action
+/// pipeline: `RefStore` load → `RefMap` lookup (→ `STALE_REF` on missing) →
+/// strict element resolution (→ `STALE_REF`/`AMBIGUOUS_TARGET`) → live
+/// actionability preflight → dispatch → handle release.
+///
+/// Policy: `TypeText` defaults to `focus_fallback` (matching the CLI `type`
+/// command); `PressKey` shares that `focus_fallback` base (a ref-targeted key
+/// press may need the target focused); every other action defaults to
+/// `headless`. An explicit `policy` discriminant may *elevate* to headed but
+/// must not downgrade an action below its base. Base and elevation are computed
+/// by `agent_desktop_core::commands::execute_by_ref::execute` via
+/// `Action::base_interaction_policy` + `InteractionPolicy::join`, so CLI and
+/// FFI share a single source of policy truth.
+///
+/// `ref_id` tri-state: null → `ErrInvalidArgs`; non-null invalid UTF-8 →
+/// `ErrInvalidArgs`; valid UTF-8 but bad `@e{N}` format → `ErrInvalidArgs`.
+///
+/// `snapshot_id` tri-state: null → use the latest snapshot for the session
+/// (CLI `--snapshot` omitted); valid UTF-8 → pin to that snapshot id; non-null
+/// invalid UTF-8 → `ErrInvalidArgs`.
+///
+/// `policy` is an `AdPolicyKind` discriminant (0=Headless, 1=FocusFallback,
+/// 2=Headed). An out-of-range value returns `ErrInvalidArgs`. `Headless (0)`
+/// accepts the action's own CLI base (so `TypeText` still uses
+/// `focus_fallback`). `Headed (2)` opts in to cursor-based fallbacks.
+///
+/// On success `*out` is set to a NUL-terminated JSON envelope (command
+/// `"execute_by_ref"`); free with `ad_free_string`. On guard or decode
+/// failure (invalid args before the command runs) `*out` remains null.
+/// On a command-level error (STALE_REF, AMBIGUOUS_TARGET, etc.) `*out`
+/// holds the error JSON envelope and must still be freed with
+/// `ad_free_string`. The last-error slot is populated on all failures.
+///
+/// **Dispatch-before-serialize ordering**: the action is dispatched (and any
+/// side effects committed) before the result JSON is serialized. In the
+/// near-impossible event that serialization of an already-valid
+/// `ActionResult` fails, `*out` is null and `ErrInternal` is returned while
+/// the side effect has already occurred. No pre-validation machinery is
+/// needed because serialization of a valid envelope effectively never fails.
+///
+/// # Safety
+///
+/// `adapter` must be a non-null pointer from `ad_adapter_create[_with_session]`.
+/// `ref_id` must be a non-null pointer to a NUL-terminated C string within
+/// `AD_MAX_STRING_BYTES + 1` bytes; null is **not** optional — it is defined
+/// behaviour (no UB) but is rejected immediately with `ErrInvalidArgs`.
+/// `snapshot_id` may be null (meaning: use the latest snapshot for this
+/// session) or a non-null NUL-terminated C string within
+/// `AD_MAX_STRING_BYTES + 1` bytes. `action` must be a non-null pointer to a
+/// valid `AdAction`. `out` must be a non-null writable pointer. All pointers
+/// must remain valid for the duration of the call. Must be called from the
+/// main thread on macOS.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn ad_execute_by_ref(
+ adapter: *const AdAdapter,
+ ref_id: *const c_char,
+ snapshot_id: *const c_char,
+ action: *const AdAction,
+ policy: i32,
+ out: *mut *mut c_char,
+) -> AdResult {
+ guard_non_null!(out, c"out is null");
+ unsafe { *out = ptr::null_mut() };
+ trap_panic(|| {
+ if let Err(rc) = require_main_thread() {
+ return rc;
+ }
+ guard_non_null!(adapter, c"adapter is null");
+ guard_non_null!(action, c"action is null");
+
+ let ref_str = match required_adapter_string(ref_id, "ref_id") {
+ Ok(s) => s,
+ Err(e) => {
+ set_last_error(&e);
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+
+ if let Err(app_err) = validate_ref_id(&ref_str) {
+ let ae = app_error_to_adapter(app_err);
+ set_last_error(&ae);
+ return crate::error::last_error_code();
+ }
+
+ let snapshot_str = match optional_adapter_string(snapshot_id, "snapshot_id") {
+ Ok(opt) => opt,
+ Err(e) => {
+ set_last_error(&e);
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+
+ let caller_policy = match AdPolicyKind::from_c(policy) {
+ Some(p) => p,
+ None => {
+ set_last_error(&AdapterError::new(
+ ErrorCode::InvalidArgs,
+ "invalid policy kind discriminant",
+ ));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+
+ let core_action = match unsafe { action_from_c(&*action) } {
+ Ok(a) => a,
+ Err(msg) => {
+ set_last_error(&AdapterError::new(ErrorCode::InvalidArgs, msg));
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+
+ let caller_ip = caller_policy.to_interaction_policy();
+
+ let adapter_ref = unsafe { &*adapter };
+ let context = match adapter_ref.command_context() {
+ Ok(ctx) => ctx,
+ Err(e) => {
+ let ae = app_error_to_adapter(e);
+ set_last_error(&ae);
+ return crate::error::last_error_code();
+ }
+ };
+
+ let result = agent_desktop_core::commands::execute_by_ref::execute(
+ &ref_str,
+ snapshot_str.as_deref(),
+ core_action,
+ caller_ip,
+ adapter_ref.inner.as_ref(),
+ &context,
+ );
+
+ unsafe { write_command_envelope("execute_by_ref", result, out) }
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use agent_desktop_core::action::Action;
+ use agent_desktop_core::interaction_policy::InteractionPolicy;
+
+ #[test]
+ fn policy_kind_headless_maps_to_headless() {
+ assert_eq!(
+ AdPolicyKind::Headless.to_interaction_policy(),
+ InteractionPolicy::headless()
+ );
+ }
+
+ #[test]
+ fn policy_kind_focus_fallback_maps_to_focus_fallback() {
+ assert_eq!(
+ AdPolicyKind::FocusFallback.to_interaction_policy(),
+ InteractionPolicy::focus_fallback()
+ );
+ }
+
+ #[test]
+ fn policy_kind_headed_maps_to_headed() {
+ assert_eq!(
+ AdPolicyKind::Headed.to_interaction_policy(),
+ InteractionPolicy::headed()
+ );
+ }
+
+ #[test]
+ fn type_text_base_plus_headless_caller_gives_focus_fallback() {
+ let base = Action::TypeText("hi".into()).base_interaction_policy();
+ let effective = base.join(InteractionPolicy::headless());
+ assert_eq!(effective, InteractionPolicy::focus_fallback());
+ }
+
+ #[test]
+ fn click_base_plus_headless_caller_stays_headless() {
+ let base = Action::Click.base_interaction_policy();
+ let effective = base.join(InteractionPolicy::headless());
+ assert_eq!(effective, InteractionPolicy::headless());
+ }
+
+ #[test]
+ fn click_base_plus_headed_caller_becomes_headed() {
+ let base = Action::Click.base_interaction_policy();
+ let effective = base.join(InteractionPolicy::headed());
+ assert_eq!(effective, InteractionPolicy::headed());
+ }
+
+ #[test]
+ fn type_text_base_plus_headed_caller_becomes_headed() {
+ let base = Action::TypeText("x".into()).base_interaction_policy();
+ let effective = base.join(InteractionPolicy::headed());
+ assert_eq!(effective, InteractionPolicy::headed());
+ }
+
+ #[test]
+ fn headless_caller_cannot_downgrade_type_text_base() {
+ let base = Action::TypeText("x".into()).base_interaction_policy();
+ assert_eq!(base, InteractionPolicy::focus_fallback());
+ let effective = base.join(InteractionPolicy::headless());
+ assert_eq!(effective, InteractionPolicy::focus_fallback());
+ }
+
+ #[test]
+ fn click_base_plus_focus_fallback_caller_gives_focus_fallback() {
+ let base = Action::Click.base_interaction_policy();
+ let effective = base.join(InteractionPolicy::focus_fallback());
+ assert_eq!(effective, InteractionPolicy::focus_fallback());
+ }
+}
diff --git a/crates/ffi/src/commands/mod.rs b/crates/ffi/src/commands/mod.rs
new file mode 100644
index 000000000..598142067
--- /dev/null
+++ b/crates/ffi/src/commands/mod.rs
@@ -0,0 +1,20 @@
+pub(crate) mod envelope_out;
+pub mod execute_by_ref;
+pub mod snapshot;
+pub(crate) mod status;
+pub(crate) mod version;
+pub mod wait;
+
+use agent_desktop_core::error::{AdapterError, AppError, ErrorCode};
+
+/// Converts a core `AppError` into an `AdapterError` for use with
+/// `set_last_error`. `AppError::Adapter` is already an `AdapterError`;
+/// the other variants wrap their payload as `ErrorCode::Internal`.
+pub(crate) fn app_error_to_adapter(err: AppError) -> AdapterError {
+ match err {
+ AppError::Adapter(e) => e,
+ AppError::Io(e) => AdapterError::new(ErrorCode::Internal, e.to_string()),
+ AppError::Json(e) => AdapterError::new(ErrorCode::Internal, e.to_string()),
+ AppError::Internal(msg) => AdapterError::new(ErrorCode::Internal, msg),
+ }
+}
diff --git a/crates/ffi/src/commands/snapshot.rs b/crates/ffi/src/commands/snapshot.rs
new file mode 100644
index 000000000..17319d084
--- /dev/null
+++ b/crates/ffi/src/commands/snapshot.rs
@@ -0,0 +1,116 @@
+use crate::AdAdapter;
+use crate::commands::app_error_to_adapter;
+use crate::commands::envelope_out::write_command_envelope;
+use crate::convert::string::decode_optional_filter;
+use crate::convert::surface::snapshot_surface_from_c;
+use crate::error::{AdResult, set_last_error};
+use crate::ffi_try::trap_panic;
+use crate::main_thread::require_main_thread;
+use crate::pointer_guard::guard_non_null;
+use agent_desktop_core::commands::snapshot::SnapshotArgs;
+use std::ffi::c_char;
+use std::ptr;
+
+/// Takes a full CLI-format snapshot of the target application window,
+/// allocates `@e` refs for all interactive elements, persists the refmap
+/// to disk, and writes the JSON envelope into `*out`.
+///
+/// The JSON shape matches `agent-desktop snapshot`:
+/// `{"version":"2.0","ok":true,"command":"snapshot","data":{"app":"...","window":{...},"ref_count":N,"snapshot_id":"...","tree":{...}}}`.
+///
+/// **`*out` ownership and error behaviour:**
+/// - On success (`AD_RESULT_OK`): `*out` is a heap-allocated JSON string with `"ok":true`.
+/// Caller must free it with `ad_free_string`.
+/// - On a command-level error (e.g. app not found, snapshot failure): `*out` is a
+/// heap-allocated JSON string with `"ok":false` and an `"error"` payload. Caller
+/// must still free it with `ad_free_string`. The last-error slot is also set.
+/// - On an argument or infrastructure error (null adapter, off-main-thread, invalid
+/// UTF-8, bad surface discriminant, context failure): `*out` is set to null and no
+/// allocation is made. Only the last-error slot is set.
+///
+/// `app` is tri-state:
+/// - null — snapshot the currently focused window (same as running the command with no `--app`).
+/// - valid UTF-8 string — snapshot the named application's focused window.
+/// - non-null but invalid UTF-8 or exceeding `AD_MAX_STRING_BYTES` — returns `ErrInvalidArgs`.
+///
+/// `surface` is an `AdSnapshotSurface` discriminant (0 = Window, 1 = Focused, …).
+/// An out-of-range value returns `ErrInvalidArgs`.
+///
+/// This entrypoint always targets the active focused window of the requested
+/// application; explicit window targeting (`window_id`) is not yet exposed
+/// over the ABI. Progressive traversal (skeleton mode and `--root` drill-down)
+/// is likewise not exposed here. Both are planned fast-follows to this
+/// entrypoint — agents needing them should use the CLI in the meantime.
+///
+/// **Dispatch-before-serialize ordering**: the snapshot and refmap persistence
+/// occur before the result JSON is serialised. In the near-impossible event
+/// that serialisation of an already-valid result fails, `*out` is set to null
+/// and `ErrInternal` is returned while the refmap is already written.
+///
+/// # Safety
+///
+/// `adapter` must be a non-null pointer from `ad_adapter_create` or
+/// `ad_adapter_create_with_session`. `out` must be a non-null writable
+/// `*mut *mut c_char`. `app` must be null or a NUL-terminated string within
+/// `AD_MAX_STRING_BYTES + 1` bytes. All pointers must remain valid for the
+/// duration of the call. `adapter` must be used from the main thread on macOS.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn ad_snapshot(
+ adapter: *const AdAdapter,
+ app: *const c_char,
+ surface: i32,
+ max_depth: u8,
+ interactive_only: bool,
+ compact: bool,
+ out: *mut *mut c_char,
+) -> AdResult {
+ guard_non_null!(out, c"out is null");
+ unsafe { *out = ptr::null_mut() };
+ trap_panic(|| {
+ if let Err(rc) = require_main_thread() {
+ return rc;
+ }
+ guard_non_null!(adapter, c"adapter is null");
+
+ let app_filter = unsafe { decode_optional_filter!(app, "app") };
+
+ let core_surface = match snapshot_surface_from_c(surface, "surface") {
+ Ok(s) => s,
+ Err(e) => {
+ set_last_error(&e);
+ return AdResult::ErrInvalidArgs;
+ }
+ };
+
+ let adapter_ref = unsafe { &*adapter };
+ let context = match adapter_ref.command_context() {
+ Ok(ctx) => ctx,
+ Err(e) => {
+ let ae = app_error_to_adapter(e);
+ set_last_error(&ae);
+ return crate::error::last_error_code();
+ }
+ };
+
+ let args = SnapshotArgs {
+ app: app_filter,
+ window_id: None,
+ max_depth,
+ include_bounds: false,
+ interactive_only,
+ compact,
+ surface: core_surface,
+ skeleton: false,
+ root_ref: None,
+ snapshot_id: None,
+ };
+
+ let result = agent_desktop_core::commands::snapshot::execute(
+ args,
+ adapter_ref.inner.as_ref(),
+ &context,
+ );
+
+ unsafe { write_command_envelope("snapshot", result, out) }
+ })
+}
diff --git a/crates/ffi/src/commands/status.rs b/crates/ffi/src/commands/status.rs
new file mode 100644
index 000000000..f66163a87
--- /dev/null
+++ b/crates/ffi/src/commands/status.rs
@@ -0,0 +1,59 @@
+use crate::commands::app_error_to_adapter;
+use crate::commands::envelope_out::write_command_envelope;
+use crate::error::{self, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::pointer_guard::guard_non_null;
+use agent_desktop_core::commands::status::execute_with_report_with_context;
+use agent_desktop_core::error::AppError;
+use std::ffi::c_char;
+
+/// Returns the adapter's current health and permission state as a JSON
+/// envelope matching the `agent-desktop status` CLI output.
+///
+/// `ad_status` does not query the accessibility tree; it reads the
+/// permission report and ref-store metadata only, so it is safe to call
+/// from any thread (unlike tree-traversal commands that require the
+/// macOS main thread). On success `*out` is a NUL-terminated,
+/// heap-allocated JSON string freed with `ad_free_string`.
+///
+/// On a command-level failure `*out` is set to a heap-allocated JSON string
+/// with `"ok":false` and an `"error"` payload. The caller must still release
+/// it with `ad_free_string(*out)`. The last-error slot is also set.
+///
+/// On an argument or infrastructure failure (null adapter, null out, context
+/// error) `*out` is zeroed and only the last-error slot is populated.
+///
+/// # Safety
+///
+/// `adapter` must be a non-null pointer returned by `ad_adapter_create`
+/// that has not been destroyed. `out` must be a non-null writable
+/// `*mut *mut c_char`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn ad_status(
+ adapter: *const crate::AdAdapter,
+ out: *mut *mut c_char,
+) -> AdResult {
+ guard_non_null!(out, c"out is null");
+ unsafe { *out = std::ptr::null_mut() };
+ guard_non_null!(adapter, c"adapter is null");
+
+ trap_panic(|| {
+ let adapter = unsafe { &*adapter };
+
+ let ctx = match adapter.command_context() {
+ Ok(c) => c,
+ Err(app_err) => {
+ let ae = app_error_to_adapter(app_err);
+ error::set_last_error(&ae);
+ return error::last_error_code();
+ }
+ };
+
+ let report = adapter.inner.permission_report();
+
+ let result: Result<serde_json::Value, AppError> =
+ execute_with_report_with_context(&*adapter.inner, &report, &ctx);
+
+ unsafe { write_command_envelope("status", result, out) }
+ })
+}
diff --git a/crates/ffi/src/commands/version.rs b/crates/ffi/src/commands/version.rs
new file mode 100644
index 000000000..ff571a5da
--- /dev/null
+++ b/crates/ffi/src/commands/version.rs
@@ -0,0 +1,25 @@
+use crate::commands::envelope_out::write_command_envelope;
+use crate::error::AdResult;
+use crate::ffi_try::trap_panic;
+use crate::pointer_guard::guard_non_null;
+use std::os::raw::c_char;
+
+/// Returns the `agent-desktop` version envelope as an owned JSON C string.
+///
+/// The returned string has the same `{version, ok, command, data}` shape
+/// as `agent-desktop version` on the CLI. Free it with `ad_free_string`.
+///
+/// On success `*out` points to the envelope JSON.
+/// On error `*out` is null and the last-error slot is populated.
+///
+/// # Safety
+/// `out` must be a non-null writable `*mut *mut c_char`.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn ad_version(out: *mut *mut c_char) -> AdResult {
+ trap_panic(|| unsafe {
+ guard_non_null!(out, c"out is null");
+ *out = std::ptr::null_mut();
+ let result = agent_desktop_core::commands::version::execute();
+ write_command_envelope("version", result, out)
+ })
+}
diff --git a/crates/ffi/src/commands/wait.rs b/crates/ffi/src/commands/wait.rs
new file mode 100644
index 000000000..ea3d24507
--- /dev/null
+++ b/crates/ffi/src/commands/wait.rs
@@ -0,0 +1,112 @@
+use crate::adapter::AdAdapter;
+use crate::commands::app_error_to_adapter;
+use crate::commands::envelope_out::write_command_envelope;
+use crate::convert::string::decode_optional_filter;
+use crate::error::{self, AdResult};
+use crate::ffi_try::trap_panic;
+use crate::main_thread::require_main_thread;
+use crate::pointer_guard::guard_non_null;
+use crate::types::wait_args::AdWaitArgs;
+use agent_desktop_core::commands::wait::{WaitArgs, WaitModeArgs, WaitPredicateArgs};
+use std::ffi::c_char;
+
+/// Runs `wait` with the given args, blocking the calling thread until the
+/// condition is met or `timeout_ms` elapses.
+///
+/// On success `*out` is set to a freshly allocated JSON string containing the
+/// CLI-format wait envelope (`{version, ok, command, data}`). The caller must
+/// release the string with `ad_free_string(*out)`.
+///
+/// On a command-level failure (e.g. `TIMEOUT`, `ELEMENT_NOT_FOUND`) `*out` is
+/// set to a freshly allocated JSON string with `"ok":false` and an `"error"`
+/// payload. The caller must still release it with `ad_free_string(*out)`. The
+/// last-error slot is also set.
+///
+/// On an argument or infrastructure failure (null adapter, null args, null out,
+/// off-main-thread, invalid UTF-8 field) `*out` is zeroed, the last-error slot
+/// is set, and a negative `AdResult` code is returned. No allocation is made.
+///
+/// # Safety
+///
+/// `adapter` must be a non-null pointer returned by `ad_adapter_create` that
+/// has not been destroyed. `args` must be non-null and point to a valid
+/// zero-initialized `AdWaitArgs`. `out` must be non-null and point to a
+/// writable `*mut c_char`.
+///
+/// All `*const c_char` fields inside `AdWaitArgs` must be null or point to
+/// readable, NUL-terminated memory within `AD_MAX_STRING_BYTES + 1` bytes.
+///
+/// `ad_wait` blocks the calling thread for up to `timeout_ms` milliseconds
+/// while it holds a live reference into the adapter's allocation. The adapter
+/// must outlive the call: do not call `ad_adapter_destroy` on this handle from
+/// another thread while `ad_wait` is running — that is a use-after-free. Ensure
+/// the wait has returned before destroying the adapter.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn ad_wait(
+ adapter: *const AdAdapter,
+ args: *const AdWaitArgs,
+ out: *mut *mut c_char,
+) -> AdResult {
+ guard_non_null!(out, c"out is null");
+ unsafe { *out = std::ptr::null_mut() };
+ guard_non_null!(args, c"args is null");
+
+ trap_panic(|| {
+ if let Err(rc) = require_main_thread() {
+ return rc;
+ }
+ guard_non_null!(adapter, c"adapter is null");
+
+ let args = unsafe { &*args };
+ let adapter_ref = unsafe { &*adapter };
+
+ let ms = args.has_ms.then_some(args.ms);
+
+ let element = unsafe { decode_optional_filter!(args.element, "element") };
+ let window = unsafe { decode_optional_filter!(args.window, "window") };
+ let text = unsafe { decode_optional_filter!(args.text, "text") };
+ let snapshot_id = unsafe { decode_optional_filter!(args.snapshot_id, "snapshot_id") };
+ let predicate = unsafe { decode_optional_filter!(args.predicate, "predicate") };
+ let value = unsafe { decode_optional_filter!(args.value, "value") };
+ let action_field = unsafe { decode_optional_filter!(args.action, "action") };
+ let app = unsafe { decode_optional_filter!(args.app, "app") };
+
+ let wait_args = WaitArgs {
+ mode: WaitModeArgs {
+ ms,
+ element,
+ window,
+ text,
+ menu: args.menu,
+ menu_closed: args.menu_closed,
+ notification: args.notification,
+ },
+ predicate: WaitPredicateArgs {
+ snapshot_id,
+ predicate,
+ value,
+ action: action_field,
+ count: args.has_count.then_some(args.count),
+ },
+ timeout_ms: args.timeout_ms,
+ app,
+ };
+
+ let ctx = match adapter_ref.command_context() {
+ Ok(c) => c,
+ Err(app_err) => {
+ let adapter_err = app_error_to_adapter(app_err);
+ error::set_last_error(&adapter_err);
+ return error::last_error_code();
+ }
+ };
+
+ let result = agent_desktop_core::commands::wait::execute(
+ wait_args,
+ adapter_ref.inner.as_ref(),
+ &ctx,
+ );
+
+ unsafe { write_command_envelope("wait", result, out) }
+ })
+}
diff --git a/crates/ffi/src/convert/string.rs b/crates/ffi/src/convert/string.rs
index 73afacc0f..c549653f8 100644
--- a/crates/ffi/src/convert/string.rs
+++ b/crates/ffi/src/convert/string.rs
@@ -52,7 +52,7 @@ pub(crate) unsafe fn free_c_string(ptr: *mut c_char) {
/// payload-bearing calls (clipboard-set, type) keep CLI parity rather than
/// being cut off at a ref-field-sized cap. Mirrored in the header as
/// `AD_MAX_STRING_BYTES`.
-pub const MAX_C_STRING_BYTES: usize = 1024 * 1024;
+pub const AD_MAX_STRING_BYTES: usize = 1024 * 1024;
pub(crate) enum CStrDecodeError {
NotUtf8,
@@ -64,14 +64,14 @@ impl CStrDecodeError {
match self {
Self::NotUtf8 => format!("{field} is not valid UTF-8"),
Self::TooLong => {
- format!("{field} exceeds AD_MAX_STRING_BYTES ({MAX_C_STRING_BYTES} bytes)")
+ format!("{field} exceeds AD_MAX_STRING_BYTES ({AD_MAX_STRING_BYTES} bytes)")
}
}
}
}
unsafe fn bounded_c_bytes<'a>(ptr: *const c_char) -> Result<&'a [u8], CStrDecodeError> {
- for len in 0..=MAX_C_STRING_BYTES {
+ for len in 0..=AD_MAX_STRING_BYTES {
if unsafe { *ptr.add(len) } == 0 {
return Ok(unsafe { std::slice::from_raw_parts(ptr.cast::<u8>(), len) });
}
@@ -90,7 +90,7 @@ pub(crate) unsafe fn c_to_string(ptr: *const c_char) -> Option<String> {
/// - `Ok(None)` — pointer is null. Caller should treat as "filter
/// absent".
/// - `Ok(Some(s))` — pointer is non-null, NUL-terminated within
-/// `MAX_C_STRING_BYTES`, and decodes as valid UTF-8.
+/// `AD_MAX_STRING_BYTES`, and decodes as valid UTF-8.
/// - `Err(e)` — pointer is non-null but the bytes are not UTF-8 or no
/// terminator was found within the byte cap. Caller should surface
/// `AD_RESULT_ERR_INVALID_ARGS` (via `e.describe(field)`) instead of
@@ -98,7 +98,7 @@ pub(crate) unsafe fn c_to_string(ptr: *const c_char) -> Option<String> {
///
/// # Safety
/// `ptr` must be null or point to readable memory that is NUL-terminated
-/// within `MAX_C_STRING_BYTES + 1` bytes.
+/// within `AD_MAX_STRING_BYTES + 1` bytes.
pub(crate) unsafe fn try_c_to_string(
ptr: *const c_char,
) -> Result<Option<String>, CStrDecodeError> {
@@ -225,19 +225,19 @@ mod tests {
#[test]
fn try_c_to_string_caps_unterminated_input() {
- let unterminated = vec![b'a'; MAX_C_STRING_BYTES + 1];
+ let unterminated = vec![b'a'; AD_MAX_STRING_BYTES + 1];
let result = unsafe { try_c_to_string(unterminated.as_ptr() as *const c_char) };
assert!(matches!(result, Err(CStrDecodeError::TooLong)));
}
#[test]
fn try_c_to_string_accepts_exact_cap_length() {
- let mut max_len = vec![b'a'; MAX_C_STRING_BYTES];
+ let mut max_len = vec![b'a'; AD_MAX_STRING_BYTES];
max_len.push(0);
let result = unsafe { try_c_to_string(max_len.as_ptr() as *const c_char) };
assert_eq!(
result.ok().flatten().map(|s| s.len()),
- Some(MAX_C_STRING_BYTES)
+ Some(AD_MAX_STRING_BYTES)
);
}
diff --git a/crates/ffi/src/error.rs b/crates/ffi/src/error.rs
index a8df68e42..e3521d177 100644
--- a/crates/ffi/src/error.rs
+++ b/crates/ffi/src/error.rs
@@ -2,6 +2,8 @@ use agent_desktop_core::error::{AdapterError, ErrorCode};
use std::cell::RefCell;
use std::ffi::{CStr, CString, c_char};
+/// New result codes may be appended in future releases. Always handle values
+/// outside this list.
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AdResult {
@@ -229,7 +231,9 @@ pub extern "C" fn ad_last_error_platform_detail() -> *const c_char {
/// Returns a borrowed JSON string carrying structured details for the last
/// error, or null if the adapter didn't supply any. Same lifetime rules as
-/// `ad_last_error_message`.
+/// `ad_last_error_message`. Details may contain element names, values, and
+/// window titles from the user's screen; treat as sensitive diagnostics and
+/// avoid routing to shared log surfaces.
#[unsafe(no_mangle)]
pub extern "C" fn ad_last_error_details() -> *const c_char {
crate::ffi_try::trap_panic_const_ptr(|| {
diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rs
index 4717153d7..4db892a14 100644
--- a/crates/ffi/src/lib.rs
+++ b/crates/ffi/src/lib.rs
@@ -14,9 +14,10 @@
//!
//! Operations exempt from the guard (safe from any thread):
//!
+//! - `ad_abi_version` / `ad_init` (no adapter, no AX/Cocoa state)
//! - `ad_adapter_create` / `ad_adapter_destroy`
//! - `ad_last_error_*` readers
-//! - `ad_check_permissions` (process-wide query, no AX/Cocoa state)
+//! - `ad_check_permissions`, `ad_status` (permission + ref-store reads, no AX tree traversal)
//! - All `ad_*_list_{count,get,free}` accessors and
//! `ad_image_buffer_*` accessors
//! - `ad_release_window_fields`, `ad_free_handle`, `ad_free_tree`,
@@ -41,14 +42,17 @@
//! any number of subsequent successful calls on the same thread; only
//! the next *failing* call rotates it. Matches POSIX `errno` semantics.
+pub(crate) mod abi_version;
pub(crate) mod actions;
pub(crate) mod adapter;
pub(crate) mod apps;
+pub(crate) mod commands;
pub(crate) mod convert;
pub(crate) mod enum_validation;
pub mod error;
pub(crate) mod ffi_try;
pub(crate) mod input;
+pub(crate) mod log_callback;
pub(crate) mod main_thread;
pub(crate) mod notifications;
pub(crate) mod observation;
@@ -59,6 +63,7 @@ pub(crate) mod tree;
pub mod types;
pub(crate) mod windows;
+pub use abi_version::AD_ABI_VERSION_MAJOR;
pub use adapter::AdAdapter;
pub use error::AdResult;
pub use types::action::AdAction;
@@ -95,6 +100,7 @@ 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::wait_args::AdWaitArgs;
pub use types::window_info::AdWindowInfo;
pub use types::window_list::AdWindowList;
pub use types::window_op::AdWindowOp;
diff --git a/crates/ffi/src/log_callback.rs b/crates/ffi/src/log_callback.rs
new file mode 100644
index 000000000..32621890d
--- /dev/null
+++ b/crates/ffi/src/log_callback.rs
@@ -0,0 +1,276 @@
+//! `ad_set_log_callback` — forward `tracing` events to a consumer callback.
+//!
+//! # Thread-safety
+//!
+//! `tracing` events fire from arbitrary threads. The callback pointer is
+//! stored in a global `AtomicPtr` (lock-free). A `tracing_subscriber` layer
+//! is installed exactly once (via [`OnceLock`]) when the first non-null callback
+//! is registered; subsequent registrations only swap the pointer. If a foreign
+//! global subscriber already owns the process at the time of the first
+//! registration, the install fails and `AD_RESULT_ERR_INTERNAL` is returned —
+//! the callback is never stored and events will not be delivered.
+//!
+//! Re-entrancy is prevented by a per-thread flag: if a consumer callback
+//! itself emits a `tracing` event, the recursive `on_event` invocation is
+//! silently discarded rather than overflowing the stack.
+//!
+//! # Level mapping
+//!
+//! | `tracing` level | `level` passed to callback |
+//! |-----------------|---------------------------|
+//! | ERROR | 1 |
+//! | WARN | 2 |
+//! | INFO | 3 |
+//! | DEBUG | 4 |
+//! | TRACE | 5 |
+//!
+//! # Pointer lifetime
+//!
+//! The `msg` pointer passed to the callback is valid **only for the duration
+//! of the call**. The consumer must copy the string before returning.
+//!
+//! # Redaction
+//!
+//! Fields whose keys match `SENSITIVE_KEYS` (password, token, text, …) are
+//! replaced with `{"redacted":true}` before the message is formatted, using
+//! the same logic as the file-trace writer.
+
+use std::cell::Cell;
+use std::ffi::{CString, c_char};
+use std::os::raw::c_void;
+use std::panic::{AssertUnwindSafe, catch_unwind};
+use std::sync::OnceLock;
+use std::sync::atomic::{AtomicPtr, Ordering};
+
+use agent_desktop_core::sanitize_trace_value;
+use serde_json::{Map, Value};
+use tracing::field::{Field, Visit};
+use tracing::{Event, Level, Subscriber};
+use tracing_subscriber::Layer;
+use tracing_subscriber::layer::SubscriberExt;
+use tracing_subscriber::util::SubscriberInitExt;
+
+use crate::error::AdResult;
+
+/// Raw storage for the consumer callback. Null means no callback registered.
+/// Stored as `*mut c_void` to avoid `fn` pointer restrictions on `AtomicPtr`.
+static CALLBACK_SLOT: AtomicPtr<c_void> = AtomicPtr::new(std::ptr::null_mut());
+
+/// Memoises the outcome of the one-time subscriber install attempt.
+///
+/// `true` — our `CallbackLayer` subscriber is installed and callback delivery works.
+/// `false` — `try_init` failed because a foreign global subscriber already owns the
+/// process; our layer was never installed.
+static INSTALL_RESULT: OnceLock<bool> = OnceLock::new();
+
+thread_local! {
+ static IN_CALLBACK: Cell<bool> = const { Cell::new(false) };
+}
+
+/// RAII guard that resets [`IN_CALLBACK`] on drop, so a panicking callback
+/// does not permanently poison the flag on its thread.
+struct CallbackGuard;
+
+impl Drop for CallbackGuard {
+ fn drop(&mut self) {
+ IN_CALLBACK.with(|g| g.set(false));
+ }
+}
+
+/// The concrete type of the consumer callback.
+type LogCb = unsafe extern "C" fn(level: i32, msg: *const c_char);
+
+/// Soundness guard: `fn` pointer and data pointer must be the same size so
+/// the `transmute` in `on_event` is layout-safe on every target.
+const _: () = assert!(
+ std::mem::size_of::<LogCb>() == std::mem::size_of::<*mut c_void>(),
+ "fn pointer size must equal data pointer size for LogCb transmute"
+);
+
+fn level_to_i32(level: &Level) -> i32 {
+ match *level {
+ Level::ERROR => 1,
+ Level::WARN => 2,
+ Level::INFO => 3,
+ Level::DEBUG => 4,
+ Level::TRACE => 5,
+ }
+}
+
+/// Collects event fields into a `serde_json::Map`.
+struct FieldCollector {
+ map: Map<String, Value>,
+}
+
+impl Visit for FieldCollector {
+ fn record_str(&mut self, field: &Field, value: &str) {
+ self.map
+ .insert(field.name().to_owned(), Value::String(value.to_owned()));
+ }
+
+ fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
+ self.map
+ .insert(field.name().to_owned(), Value::String(format!("{value:?}")));
+ }
+
+ fn record_i64(&mut self, field: &Field, value: i64) {
+ self.map.insert(field.name().to_owned(), Value::from(value));
+ }
+
+ fn record_u64(&mut self, field: &Field, value: u64) {
+ self.map.insert(field.name().to_owned(), Value::from(value));
+ }
+
+ fn record_bool(&mut self, field: &Field, value: bool) {
+ self.map.insert(field.name().to_owned(), Value::Bool(value));
+ }
+}
+
+/// `tracing_subscriber` layer that forwards events to the registered callback.
+struct CallbackLayer;
+
+impl<S: Subscriber> Layer<S> for CallbackLayer {
+ fn on_event(&self, event: &Event<'_>, _ctx: tracing_subscriber::layer::Context<'_, S>) {
+ let ptr = CALLBACK_SLOT.load(Ordering::Acquire);
+ if ptr.is_null() {
+ return;
+ }
+
+ if IN_CALLBACK.with(Cell::get) {
+ return;
+ }
+
+ let _ = catch_unwind(AssertUnwindSafe(|| {
+ let level_i32 = level_to_i32(event.metadata().level());
+
+ let mut collector = FieldCollector { map: Map::new() };
+ event.record(&mut collector);
+
+ let sanitized = sanitize_trace_value(Value::Object(collector.map));
+ let msg_str = serde_json::to_string(&sanitized).unwrap_or_default();
+
+ let Ok(c_msg) = CString::new(msg_str) else {
+ return;
+ };
+
+ IN_CALLBACK.with(|g| g.set(true));
+ let cb: LogCb = unsafe { std::mem::transmute(ptr) };
+ let _reset = CallbackGuard;
+ unsafe { cb(level_i32, c_msg.as_ptr()) };
+ }));
+ }
+}
+
+fn install_layer_once() -> bool {
+ *INSTALL_RESULT.get_or_init(|| {
+ tracing_subscriber::registry()
+ .with(CallbackLayer)
+ .try_init()
+ .is_ok()
+ })
+}
+
+/// Maps an install outcome to the `AdResult` that `ad_set_log_callback` should
+/// return when registering a non-null callback.
+///
+/// Extracted as a named function so the routing logic can be unit-tested
+/// independently of global subscriber state.
+#[cfg(test)]
+fn result_for_install(succeeded: bool) -> AdResult {
+ if succeeded {
+ AdResult::Ok
+ } else {
+ AdResult::ErrInternal
+ }
+}
+
+/// Registers a callback to receive `tracing` events, or unregisters the
+/// current callback when `cb` is `NULL`.
+///
+/// # Install semantics
+///
+/// The subscriber layer is installed exactly once — on the first call with a
+/// non-null `cb`. If a foreign global subscriber already owns the process at
+/// that point, the install fails and this function returns
+/// `AD_RESULT_ERR_INTERNAL` with a diagnostic last-error. No callback pointer
+/// is stored in that case; events will never be delivered until the consumer
+/// remedies the conflict. Subsequent calls with a non-null `cb` after a
+/// **successful** install only swap the stored pointer and always return
+/// `AD_RESULT_OK`.
+///
+/// `NULL` always returns `AD_RESULT_OK` — unregistering cannot fail.
+///
+/// # Callback contract
+///
+/// - `level` — 1 (ERROR) … 5 (TRACE)
+/// - `msg` — a NUL-terminated JSON string; valid only for the call's duration
+///
+/// Sensitive field values (password, token, text, …) are replaced with
+/// `{"redacted":true}` before the message is formatted.
+///
+/// Invocations are best-effort. A panicking callback is caught and silently
+/// discarded; no command fails because of a trace delivery error. A callback
+/// that emits `tracing` events is safe: the recursive `on_event` is dropped
+/// by a per-thread guard before it reaches the callback again.
+///
+/// # Safety
+///
+/// `cb` must be null or a valid function pointer with the declared signature.
+/// The pointer is stored atomically; the subscriber may call it from threads
+/// other than the registering thread.
+///
+/// A callback unregistered via `NULL` may still be invoked from another thread
+/// for a brief window after this call returns. The callback (and any data it
+/// captures) must remain valid for the process lifetime, or the caller must
+/// quiesce all tracing sources before unregistering.
+#[unsafe(no_mangle)]
+pub extern "C" fn ad_set_log_callback(
+ cb: Option<unsafe extern "C" fn(level: i32, msg: *const c_char)>,
+) -> AdResult {
+ crate::ffi_try::trap_panic(|| {
+ match cb {
+ Some(f) => {
+ if !install_layer_once() {
+ crate::error::set_last_error_static(
+ AdResult::ErrInternal,
+ c"ad_set_log_callback: a foreign tracing subscriber already owns this \
+ process; our CallbackLayer was not installed and events will not be \
+ delivered",
+ );
+ return AdResult::ErrInternal;
+ }
+ let raw = f as *mut c_void;
+ CALLBACK_SLOT.store(raw, Ordering::Release);
+ }
+ None => {
+ CALLBACK_SLOT.store(std::ptr::null_mut(), Ordering::Release);
+ }
+ }
+ AdResult::Ok
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn result_for_install_success_returns_ok() {
+ assert_eq!(result_for_install(true), AdResult::Ok);
+ }
+
+ #[test]
+ fn result_for_install_failure_returns_err_internal() {
+ assert_eq!(result_for_install(false), AdResult::ErrInternal);
+ }
+
+ #[test]
+ fn null_unregister_always_ok_independent_of_install_state() {
+ let result = ad_set_log_callback(None);
+ assert_eq!(
+ result,
+ AdResult::Ok,
+ "NULL unregister must return Ok regardless of install state"
+ );
+ }
+}
diff --git a/crates/ffi/src/tree/get.rs b/crates/ffi/src/tree/get.rs
index a9c49e260..1d1eff494 100644
--- a/crates/ffi/src/tree/get.rs
+++ b/crates/ffi/src/tree/get.rs
@@ -19,27 +19,32 @@ use std::ptr;
///
/// # Raw-tree contract
///
-/// This is a **raw adapter tree**, not the snapshot the CLI `snapshot`
-/// subcommand returns. Differences the caller must know about:
+/// This is a **raw adapter tree** — ref-less, no refmap persistence, and
+/// no JSON envelope. 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.
+/// - `ref_id` is always null on every `AdNode`. `ref_alloc::allocate_refs`
+/// is not run; `@e` ref assignment is a snapshot-pipeline concern.
+/// - `include_bounds`, `interactive_only`, and `compact` are honoured via
+/// `ref_alloc::transform_tree` after the adapter returns. Because refs are
+/// not allocated, the `interactive_only` cut is role-based rather than
+/// ref-based; otherwise the semantics match the 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.
+/// # When to use this function vs `ad_snapshot`
+///
+/// **Observe–act agents** that need `@e` refs and refmap persistence should
+/// call `ad_snapshot` instead. `ad_snapshot` runs the full snapshot pipeline
+/// (ref allocation, refmap write to disk, JSON envelope with
+/// `{"version":"2.0","ok":true,...}`) and is the correct starting point for
+/// any workflow that drives subsequent ref-based actions via
+/// `ad_execute_by_ref` (with an `AdAction`).
+///
+/// Use `ad_get_tree` when you need the raw flat BFS layout without refs —
+/// for example, to drive your own traversal logic or to populate a UI
+/// inspector that does not use the ref-based action API. For point lookups
+/// that bypass tree shape entirely, `ad_find` + `ad_get` / `ad_is` are
+/// another alternative.
///
/// On error `*out` is zeroed so `ad_free_tree` on it is a safe no-op.
///
diff --git a/crates/ffi/src/types/mod.rs b/crates/ffi/src/types/mod.rs
index fd8b2cdcb..515c76f64 100644
--- a/crates/ffi/src/types/mod.rs
+++ b/crates/ffi/src/types/mod.rs
@@ -32,6 +32,7 @@ pub mod snapshot_surface;
pub mod surface_info;
pub mod surface_list;
pub mod tree_options;
+pub mod wait_args;
pub mod window_info;
pub mod window_list;
pub mod window_op;
@@ -71,6 +72,7 @@ pub use snapshot_surface::AdSnapshotSurface;
pub use surface_info::AdSurfaceInfo;
pub use surface_list::AdSurfaceList;
pub use tree_options::AdTreeOptions;
+pub use wait_args::AdWaitArgs;
pub use window_info::AdWindowInfo;
pub use window_list::AdWindowList;
pub use window_op::AdWindowOp;
diff --git a/crates/ffi/src/types/policy_kind.rs b/crates/ffi/src/types/policy_kind.rs
index 7c0ab6a24..cd9867a36 100644
--- a/crates/ffi/src/types/policy_kind.rs
+++ b/crates/ffi/src/types/policy_kind.rs
@@ -6,6 +6,20 @@ pub enum AdPolicyKind {
Headed = 2,
}
+impl AdPolicyKind {
+ pub(crate) fn to_interaction_policy(
+ self,
+ ) -> agent_desktop_core::interaction_policy::InteractionPolicy {
+ match self {
+ Self::Headless => agent_desktop_core::interaction_policy::InteractionPolicy::headless(),
+ Self::FocusFallback => {
+ agent_desktop_core::interaction_policy::InteractionPolicy::focus_fallback()
+ }
+ Self::Headed => agent_desktop_core::interaction_policy::InteractionPolicy::headed(),
+ }
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/crates/ffi/src/types/wait_args.rs b/crates/ffi/src/types/wait_args.rs
new file mode 100644
index 000000000..ef925c67a
--- /dev/null
+++ b/crates/ffi/src/types/wait_args.rs
@@ -0,0 +1,71 @@
+use std::os::raw::c_char;
+
+/// Arguments for `ad_wait`, mirroring `core::commands::wait::WaitArgs`.
+///
+/// Fields map as follows:
+/// - `Option<u64>` → `u64` value + `bool has_*` sentinel (ms, count).
+/// - `Option<String>` → nullable `*const c_char` (null = absent).
+/// - `bool` → `bool`.
+///
+/// Callers must zero-initialize before use and verify layout via
+/// `AD_WAIT_ARGS_SIZE` / `ad_wait_args_size()`.
+#[repr(C)]
+pub struct AdWaitArgs {
+ /// Milliseconds to sleep (WaitMode::ms).
+ pub ms: u64,
+ pub has_ms: bool,
+
+ /// Element ref id to wait for (WaitMode::element).
+ pub element: *const c_char,
+
+ /// Window title to wait for (WaitMode::window).
+ pub window: *const c_char,
+
+ /// Text to wait for (WaitMode::text / WaitMode::notification text).
+ pub text: *const c_char,
+
+ /// Wait for menu to open (true) or close (false via menu_closed).
+ pub menu: bool,
+ /// Wait for menu to close.
+ pub menu_closed: bool,
+ /// Wait for a notification.
+ pub notification: bool,
+
+ /// Snapshot id for element predicate (WaitPredicateArgs::snapshot_id).
+ pub snapshot_id: *const c_char,
+
+ /// Predicate kind string (WaitPredicateArgs::predicate).
+ pub predicate: *const c_char,
+
+ /// Expected value for value-predicate (WaitPredicateArgs::value).
+ pub value: *const c_char,
+
+ /// Action name for actionability-predicate (WaitPredicateArgs::action).
+ pub action: *const c_char,
+
+ /// Expected match count for text waits (WaitPredicateArgs::count).
+ pub count: usize,
+ pub has_count: bool,
+
+ /// Timeout in milliseconds.
+ pub timeout_ms: u64,
+
+ /// App name filter (null = any). Maps to WaitArgs::app.
+ pub app: *const c_char,
+}
+
+/// Pinned size of `AdWaitArgs` on 64-bit targets. The compile-time
+/// assert below and the `ad_wait_args_size()` runtime getter form the
+/// 3-layer pin: Rust const assert, C `_Static_assert` in the header,
+/// and the test in `c_abi_layout.rs`.
+pub const AD_WAIT_ARGS_SIZE: usize = 112;
+
+const _: () = assert!(std::mem::size_of::<AdWaitArgs>() == AD_WAIT_ARGS_SIZE);
+
+/// Returns the size of `AdWaitArgs` as compiled. Ctypes and other
+/// foreign bindings must call this and compare against their own
+/// `sizeof` before passing args to `ad_wait`.
+#[unsafe(no_mangle)]
+pub extern "C" fn ad_wait_args_size() -> usize {
+ std::mem::size_of::<AdWaitArgs>()
+}
diff --git a/crates/ffi/src/windows/to_core.rs b/crates/ffi/src/windows/to_core.rs
index 9ae9428d0..e7d3572d6 100644
--- a/crates/ffi/src/windows/to_core.rs
+++ b/crates/ffi/src/windows/to_core.rs
@@ -39,7 +39,7 @@ pub(crate) fn ad_window_to_core(
#[cfg(test)]
mod tests {
use super::*;
- use crate::convert::string::MAX_C_STRING_BYTES;
+ use crate::convert::string::AD_MAX_STRING_BYTES;
use crate::types::AdRect;
use agent_desktop_core::error::ErrorCode;
use std::ffi::CString;
@@ -48,7 +48,7 @@ mod tests {
fn window_app_name_rejects_oversized_string() {
let id = CString::new("w-1").unwrap();
let title = CString::new("Main").unwrap();
- let mut app = vec![b'a'; MAX_C_STRING_BYTES + 1];
+ let mut app = vec![b'a'; AD_MAX_STRING_BYTES + 1];
app.push(0);
let win = window(id.as_ptr(), title.as_ptr(), app.as_ptr().cast());
diff --git a/crates/ffi/tests/c_abi_actions.rs b/crates/ffi/tests/c_abi_actions.rs
index 19c125cb9..4a9909a5e 100644
--- a/crates/ffi/tests/c_abi_actions.rs
+++ b/crates/ffi/tests/c_abi_actions.rs
@@ -1,7 +1,8 @@
mod common;
use common::{
- AdActionResult, AdActionStep, AdNativeHandle, AdPolicyKind, AdResult, ad_execute_action,
+ AdActionResult, AdActionStep, AdNativeHandle, AdPolicyKind, AdResult,
+ ad_adapter_create_with_session, ad_adapter_destroy, ad_execute_action,
ad_execute_action_with_policy, ad_execute_ref_action_with_policy, ad_free_action_result,
default_action, default_ref_entry, with_adapter,
};
@@ -112,6 +113,44 @@ fn execute_action_policy_requires_main_thread_on_macos() {
assert_eq!(rc, AdResult::ErrInvalidArgs);
}
+/// Verifies that `ad_execute_ref_action_with_policy` uses the adapter's session
+/// context rather than a default one. The observable contract is that resolution
+/// fails (stale ref) identically whether a session id is present or absent —
+/// the session id is wired into trace emission, not into the error path.
+#[test]
+fn execute_ref_action_with_session_adapter_wires_context() {
+ unsafe {
+ let session = CString::new("test-session-01").unwrap();
+ let adapter = ad_adapter_create_with_session(session.as_ptr());
+ assert!(!adapter.is_null());
+
+ let role = CString::new("button").unwrap();
+ let mut entry = default_ref_entry();
+ entry.role = role.as_ptr();
+ let action = default_action();
+ let mut out: AdActionResult = std::mem::zeroed();
+
+ let rc = ad_execute_ref_action_with_policy(
+ adapter,
+ &entry,
+ &action,
+ AdPolicyKind::Headless as i32,
+ &mut out,
+ );
+
+ assert!(
+ matches!(
+ rc,
+ AdResult::ErrStaleRef | AdResult::ErrElementNotFound | AdResult::ErrInternal
+ ),
+ "session adapter must still reject unresolvable entry, got {:?}",
+ rc
+ );
+
+ ad_adapter_destroy(adapter);
+ }
+}
+
#[test]
fn free_action_result_releases_non_empty_steps_array() {
let mut steps = vec![
diff --git a/crates/ffi/tests/c_abi_execute_by_ref.rs b/crates/ffi/tests/c_abi_execute_by_ref.rs
new file mode 100644
index 000000000..47cdd1abe
--- /dev/null
+++ b/crates/ffi/tests/c_abi_execute_by_ref.rs
@@ -0,0 +1,200 @@
+mod common;
+
+use common::{
+ AdResult, CStr, ad_execute_by_ref, ad_free_string, ad_last_error_code, default_action,
+ with_adapter,
+};
+
+#[test]
+fn execute_by_ref_null_out_returns_invalid_args() {
+ with_adapter(|adapter| unsafe {
+ let ref_id = std::ffi::CString::new("@e1").unwrap();
+ let action = default_action();
+ let rc = ad_execute_by_ref(
+ adapter,
+ ref_id.as_ptr(),
+ std::ptr::null(),
+ &action,
+ 0,
+ std::ptr::null_mut(),
+ );
+ assert_eq!(
+ rc,
+ AdResult::ErrInvalidArgs,
+ "null out is rejected by the outer guard before any thread or adapter check"
+ );
+ });
+}
+
+#[test]
+fn execute_by_ref_null_adapter_rejected() {
+ unsafe {
+ let ref_id = std::ffi::CString::new("@e1").unwrap();
+ let action = default_action();
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_execute_by_ref(
+ std::ptr::null(),
+ ref_id.as_ptr(),
+ std::ptr::null(),
+ &action,
+ 0,
+ &mut out,
+ );
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "null adapter must fail — got {rc:?} (ErrInternal on macOS off-main-thread is expected)"
+ );
+ assert!(out.is_null(), "out must stay null on failure");
+ }
+}
+
+#[test]
+fn execute_by_ref_null_ref_id_returns_invalid_args() {
+ with_adapter(|adapter| unsafe {
+ let action = default_action();
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_execute_by_ref(
+ adapter,
+ std::ptr::null(),
+ std::ptr::null(),
+ &action,
+ 0,
+ &mut out,
+ );
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "null ref_id must fail — got {rc:?}"
+ );
+ assert!(out.is_null(), "out must stay null on null ref_id");
+ });
+}
+
+#[test]
+fn execute_by_ref_invalid_utf8_ref_id_returns_invalid_args() {
+ with_adapter(|adapter| unsafe {
+ let bad: [u8; 3] = [0xC3, 0xFF, 0x00];
+ let action = default_action();
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_execute_by_ref(
+ adapter,
+ bad.as_ptr() as *const std::os::raw::c_char,
+ std::ptr::null(),
+ &action,
+ 0,
+ &mut out,
+ );
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "invalid UTF-8 ref_id must fail — got {rc:?}"
+ );
+ assert!(out.is_null(), "out must stay null on invalid UTF-8 ref_id");
+ });
+}
+
+#[test]
+fn execute_by_ref_null_action_rejected() {
+ with_adapter(|adapter| unsafe {
+ let ref_id = std::ffi::CString::new("@e1").unwrap();
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_execute_by_ref(
+ adapter,
+ ref_id.as_ptr(),
+ std::ptr::null(),
+ std::ptr::null(),
+ 0,
+ &mut out,
+ );
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "null action must fail — got {rc:?}"
+ );
+ assert!(out.is_null(), "out must stay null on null action");
+ });
+}
+
+#[test]
+fn execute_by_ref_invalid_ref_format_returns_invalid_args() {
+ with_adapter(|adapter| unsafe {
+ let bad_ref = std::ffi::CString::new("@e0").unwrap();
+ let action = default_action();
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_execute_by_ref(
+ adapter,
+ bad_ref.as_ptr(),
+ std::ptr::null(),
+ &action,
+ 0,
+ &mut out,
+ );
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "bad ref format must fail — got {rc:?}"
+ );
+ assert!(out.is_null(), "out must stay null on bad ref format");
+ });
+}
+
+#[test]
+fn execute_by_ref_returns_error_envelope_when_no_refmap_exists() {
+ with_adapter(|adapter| unsafe {
+ let ref_id = std::ffi::CString::new("@e1").unwrap();
+ let action = default_action();
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_execute_by_ref(
+ adapter,
+ ref_id.as_ptr(),
+ std::ptr::null(),
+ &action,
+ 0,
+ &mut out,
+ );
+ let rc_i32 = rc as i32;
+ assert!(
+ rc_i32 <= 0,
+ "must return a valid AdResult (<=0), got {rc_i32}"
+ );
+ if !out.is_null() {
+ let s = CStr::from_ptr(out).to_string_lossy();
+ assert!(
+ s.contains("\"version\""),
+ "envelope must carry 'version', got: {s}"
+ );
+ assert!(s.contains("\"ok\""), "envelope must carry 'ok', got: {s}");
+ assert!(
+ s.contains("\"command\""),
+ "envelope must carry 'command', got: {s}"
+ );
+ ad_free_string(out);
+ }
+ });
+}
+
+#[test]
+fn execute_by_ref_out_of_range_policy_returns_invalid_args() {
+ with_adapter(|adapter| unsafe {
+ let ref_id = std::ffi::CString::new("@e1").unwrap();
+ let action = default_action();
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_execute_by_ref(
+ adapter,
+ ref_id.as_ptr(),
+ std::ptr::null(),
+ &action,
+ 99,
+ &mut out,
+ );
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "out-of-range policy discriminant must fail — got {rc:?} \
+ (ErrInternal on macOS off-main-thread is expected)"
+ );
+ assert!(out.is_null(), "out must stay null on invalid policy");
+ if rc == AdResult::ErrInvalidArgs {
+ assert_eq!(
+ ad_last_error_code(),
+ AdResult::ErrInvalidArgs,
+ "last-error code must reflect the invalid-args rejection"
+ );
+ }
+ });
+}
diff --git a/crates/ffi/tests/c_abi_init.rs b/crates/ffi/tests/c_abi_init.rs
new file mode 100644
index 000000000..8e7185f95
--- /dev/null
+++ b/crates/ffi/tests/c_abi_init.rs
@@ -0,0 +1,54 @@
+mod common;
+
+use common::{AdResult, CStr, ad_abi_version, ad_init, ad_last_error_code, ad_last_error_message};
+
+#[test]
+fn abi_version_matches_rust_constant() {
+ unsafe {
+ assert_eq!(
+ ad_abi_version(),
+ agent_desktop_ffi::AD_ABI_VERSION_MAJOR,
+ "ad_abi_version() must equal AD_ABI_VERSION_MAJOR"
+ );
+ }
+}
+
+#[test]
+fn ad_init_succeeds_with_current_major() {
+ unsafe {
+ assert_eq!(
+ ad_init(agent_desktop_ffi::AD_ABI_VERSION_MAJOR),
+ AdResult::Ok
+ );
+ }
+}
+
+#[test]
+fn ad_init_rejects_future_major_and_sets_last_error() {
+ unsafe {
+ let rc = ad_init(agent_desktop_ffi::AD_ABI_VERSION_MAJOR + 1);
+ assert_eq!(rc, AdResult::ErrInvalidArgs);
+ let msg = ad_last_error_message();
+ assert!(
+ !msg.is_null(),
+ "last-error message must be non-null after mismatch"
+ );
+ let _ = CStr::from_ptr(msg).to_string_lossy();
+ assert_eq!(ad_last_error_code(), AdResult::ErrInvalidArgs);
+ }
+}
+
+#[test]
+fn ad_init_rejects_zero_major_and_sets_last_error() {
+ unsafe {
+ let rc = ad_init(0);
+ assert_eq!(rc, AdResult::ErrInvalidArgs);
+ let msg = ad_last_error_message();
+ assert!(
+ !msg.is_null(),
+ "last-error message must be non-null after zero-major mismatch"
+ );
+ let _ = CStr::from_ptr(msg).to_string_lossy();
+ assert_eq!(ad_last_error_code(), AdResult::ErrInvalidArgs);
+ }
+}
diff --git a/crates/ffi/tests/c_abi_json_commands.rs b/crates/ffi/tests/c_abi_json_commands.rs
new file mode 100644
index 000000000..34395d700
--- /dev/null
+++ b/crates/ffi/tests/c_abi_json_commands.rs
@@ -0,0 +1,165 @@
+mod common;
+
+use common::{
+ AdResult, CStr, ad_free_string, ad_last_error_code, ad_status, ad_version, with_adapter,
+};
+
+#[test]
+fn ad_version_returns_ok_with_valid_json_envelope() {
+ unsafe {
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_version(&mut out);
+ assert_eq!(rc, AdResult::Ok, "ad_version must return OK");
+ assert!(!out.is_null(), "out must be non-null on success");
+
+ let json_str = CStr::from_ptr(out).to_string_lossy();
+ let parsed: serde_json::Value =
+ serde_json::from_str(&json_str).expect("output must be valid JSON");
+
+ assert_eq!(
+ parsed["ok"].as_bool(),
+ Some(true),
+ "envelope ok must be true"
+ );
+ assert_eq!(
+ parsed["command"].as_str(),
+ Some("version"),
+ "envelope command must be 'version'"
+ );
+ assert!(
+ parsed["data"]["version"].is_string(),
+ "data.version must be a string"
+ );
+ assert!(
+ parsed["data"]["target"].is_string(),
+ "data.target must be a string"
+ );
+ assert!(parsed["data"]["os"].is_string(), "data.os must be a string");
+
+ let envelope_version = parsed["version"]
+ .as_str()
+ .expect("version field must exist");
+ assert_eq!(
+ envelope_version,
+ agent_desktop_core::output::ENVELOPE_VERSION,
+ "envelope version must match ENVELOPE_VERSION constant"
+ );
+
+ ad_free_string(out);
+ }
+}
+
+#[test]
+fn ad_version_null_out_returns_invalid_args() {
+ unsafe {
+ let rc = ad_version(std::ptr::null_mut());
+ assert_eq!(
+ rc,
+ AdResult::ErrInvalidArgs,
+ "null out must return ErrInvalidArgs"
+ );
+ }
+}
+
+#[test]
+fn ad_version_success_preserves_prior_last_error() {
+ unsafe {
+ let rc_fail = ad_version(std::ptr::null_mut());
+ assert_eq!(rc_fail, AdResult::ErrInvalidArgs);
+ let err_before = ad_last_error_code();
+ assert_eq!(err_before, AdResult::ErrInvalidArgs);
+
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc_ok = ad_version(&mut out);
+ assert_eq!(rc_ok, AdResult::Ok);
+
+ assert_eq!(
+ ad_last_error_code(),
+ AdResult::ErrInvalidArgs,
+ "success must not clear the prior last-error"
+ );
+
+ ad_free_string(out);
+ }
+}
+
+#[test]
+fn status_null_adapter_returns_invalid_args() {
+ unsafe {
+ let mut out: *mut std::os::raw::c_char = 0xDEAD_BEEF as *mut std::os::raw::c_char;
+ let rc = ad_status(std::ptr::null(), &mut out);
+ assert_eq!(
+ rc,
+ AdResult::ErrInvalidArgs,
+ "null adapter must return ErrInvalidArgs"
+ );
+ assert!(
+ out.is_null(),
+ "dirty out-param must be zeroed before early return on null adapter"
+ );
+ }
+}
+
+#[test]
+fn status_null_out_returns_invalid_args() {
+ with_adapter(|adapter| unsafe {
+ let rc = ad_status(adapter, std::ptr::null_mut());
+ assert_eq!(
+ rc,
+ AdResult::ErrInvalidArgs,
+ "null out must return ErrInvalidArgs"
+ );
+ });
+}
+
+#[test]
+fn status_returns_ok_envelope_with_required_fields() {
+ with_adapter(|adapter| unsafe {
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_status(adapter, &mut out);
+ assert_eq!(rc, AdResult::Ok, "ad_status must return Ok");
+ assert!(!out.is_null(), "out must be non-null on success");
+
+ let json_str = CStr::from_ptr(out)
+ .to_str()
+ .expect("status output must be valid UTF-8");
+ let val: serde_json::Value =
+ serde_json::from_str(json_str).expect("status output must be valid JSON");
+
+ assert_eq!(
+ val["version"].as_str(),
+ Some(agent_desktop_core::output::ENVELOPE_VERSION),
+ "envelope version must match ENVELOPE_VERSION constant"
+ );
+ assert_eq!(val["ok"].as_bool(), Some(true), "ok must be true");
+ assert_eq!(
+ val["command"].as_str(),
+ Some("status"),
+ "command must be \"status\""
+ );
+
+ let data = &val["data"];
+ assert!(
+ data["platform"].is_string(),
+ "data.platform must be present"
+ );
+ assert!(data["version"].is_string(), "data.version must be present");
+ assert!(
+ data["permissions"].is_object(),
+ "data.permissions must be present"
+ );
+
+ ad_free_string(out);
+ });
+}
+
+#[test]
+fn status_free_string_cleans_up() {
+ with_adapter(|adapter| unsafe {
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_status(adapter, &mut out);
+ assert_eq!(rc, AdResult::Ok);
+ assert!(!out.is_null());
+ ad_free_string(out);
+ });
+}
diff --git a/crates/ffi/tests/c_abi_layout.rs b/crates/ffi/tests/c_abi_layout.rs
index 14201eb80..eec240f3f 100644
--- a/crates/ffi/tests/c_abi_layout.rs
+++ b/crates/ffi/tests/c_abi_layout.rs
@@ -1,6 +1,8 @@
mod common;
-use common::{AdAction, AdActionResult, AdActionStep, AdElementState, AdPoint, AdRect, AdRefEntry};
+use common::{
+ AdAction, AdActionResult, AdActionStep, AdElementState, AdPoint, AdRect, AdRefEntry, AdWaitArgs,
+};
use std::mem::{MaybeUninit, align_of, offset_of, size_of};
#[test]
@@ -153,3 +155,35 @@ fn ref_entry_layout_is_guarded_for_c_consumers() {
assert_eq!(copied.pid, 0);
assert_eq!(copied.path_count, 0);
}
+
+#[test]
+fn wait_args_layout_is_guarded_for_c_consumers() {
+ assert_eq!(agent_desktop_ffi::types::wait_args::AD_WAIT_ARGS_SIZE, 112);
+ assert_eq!(
+ unsafe { common::ad_wait_args_size() },
+ agent_desktop_ffi::types::wait_args::AD_WAIT_ARGS_SIZE
+ );
+ assert_eq!(size_of::<AdWaitArgs>(), 112);
+ assert_eq!(align_of::<AdWaitArgs>(), align_of::<usize>());
+
+ let offsets = [
+ offset_of!(AdWaitArgs, ms),
+ offset_of!(AdWaitArgs, has_ms),
+ offset_of!(AdWaitArgs, element),
+ offset_of!(AdWaitArgs, window),
+ offset_of!(AdWaitArgs, text),
+ offset_of!(AdWaitArgs, menu),
+ offset_of!(AdWaitArgs, snapshot_id),
+ offset_of!(AdWaitArgs, count),
+ offset_of!(AdWaitArgs, timeout_ms),
+ offset_of!(AdWaitArgs, app),
+ ];
+ assert!(offsets.windows(2).all(|pair| pair[0] < pair[1]));
+
+ let zeroed = unsafe { MaybeUninit::<AdWaitArgs>::zeroed().assume_init() };
+ assert_eq!(zeroed.ms, 0);
+ assert!(!zeroed.has_ms);
+ assert!(zeroed.element.is_null());
+ assert!(!zeroed.menu);
+ assert_eq!(zeroed.timeout_ms, 0);
+}
diff --git a/crates/ffi/tests/c_abi_lifecycle.rs b/crates/ffi/tests/c_abi_lifecycle.rs
index 24821aab1..295dd4481 100644
--- a/crates/ffi/tests/c_abi_lifecycle.rs
+++ b/crates/ffi/tests/c_abi_lifecycle.rs
@@ -1,16 +1,16 @@
mod common;
use common::{
- AdAppList, AdFindQuery, AdNativeHandle, AdResult, AdWindowInfo, AdWindowList, CStr,
- ad_adapter_create, ad_adapter_destroy, ad_app_list_count, ad_app_list_free, ad_app_list_get,
- ad_check_permissions, ad_find, ad_free_handle, ad_last_error_code, ad_last_error_message,
- ad_list_apps, ad_list_windows, ad_window_list_count, ad_window_list_free, with_adapter,
+ AdFindQuery, AdNativeHandle, AdResult, AdWindowInfo, AdWindowList, CStr, ad_adapter_create,
+ ad_adapter_destroy, ad_app_list_count, ad_app_list_free, ad_app_list_get, ad_check_permissions,
+ ad_find, ad_free_handle, ad_last_error_code, ad_last_error_message, ad_list_apps,
+ ad_list_windows, ad_window_list_count, ad_window_list_free, with_adapter,
};
#[test]
fn null_adapter_rejected_without_ub() {
unsafe {
- let mut list: *mut AdAppList = std::ptr::null_mut();
+ let mut list = std::ptr::null_mut();
let rc = ad_list_apps(std::ptr::null(), &mut list);
assert!(matches!(
rc,
@@ -49,8 +49,8 @@ fn null_tolerance_on_list_accessors_and_free() {
#[test]
fn dirty_out_param_is_cleared_before_early_return_on_worker_thread() {
with_adapter(|adapter| unsafe {
- let fake_ptr = 0xDEAD_BEEF as *mut AdAppList;
- let mut list: *mut AdAppList = fake_ptr;
+ let fake_ptr = 0xDEAD_BEEF as *mut common::AdAppList;
+ let mut list = fake_ptr;
let rc = ad_list_apps(adapter, &mut list);
if rc != AdResult::Ok {
assert!(
@@ -65,7 +65,7 @@ fn dirty_out_param_is_cleared_before_early_return_on_worker_thread() {
#[test]
fn list_handle_lifecycle_roundtrip() {
with_adapter(|adapter| unsafe {
- let mut list: *mut AdAppList = std::ptr::null_mut();
+ let mut list = std::ptr::null_mut();
let rc = ad_list_apps(adapter, &mut list);
if rc == AdResult::Ok {
assert!(!list.is_null());
diff --git a/crates/ffi/tests/c_abi_log_callback.rs b/crates/ffi/tests/c_abi_log_callback.rs
new file mode 100644
index 000000000..c3dcc9c6b
--- /dev/null
+++ b/crates/ffi/tests/c_abi_log_callback.rs
@@ -0,0 +1,182 @@
+mod common;
+
+use common::{AdResult, CStr, ad_set_log_callback};
+use std::os::raw::c_char;
+use std::sync::Mutex;
+
+struct Delivery {
+ level: i32,
+ message: String,
+}
+
+static RECORDER: Mutex<Vec<Delivery>> = Mutex::new(Vec::new());
+static LOG_TEST_LOCK: Mutex<()> = Mutex::new(());
+
+unsafe extern "C" fn recorder_cb(level: i32, msg: *const c_char) {
+ if msg.is_null() {
+ return;
+ }
+ let message = unsafe { CStr::from_ptr(msg) }
+ .to_string_lossy()
+ .into_owned();
+ if let Ok(mut guard) = RECORDER.lock() {
+ guard.push(Delivery { level, message });
+ }
+}
+
+fn clear_recorder() {
+ if let Ok(mut g) = RECORDER.lock() {
+ g.clear();
+ }
+}
+
+fn drain_recorder() -> Vec<Delivery> {
+ RECORDER
+ .lock()
+ .map(|mut g| g.drain(..).collect())
+ .unwrap_or_default()
+}
+
+#[test]
+fn log_callback_register_delivers_event() {
+ let _guard = LOG_TEST_LOCK.lock().unwrap();
+ clear_recorder();
+
+ unsafe {
+ let rc = ad_set_log_callback(Some(recorder_cb));
+ assert_eq!(rc, AdResult::Ok, "register must succeed");
+ }
+
+ tracing::error!(
+ test_marker = "deliver_event",
+ "log_callback_register_delivers_event"
+ );
+
+ let deliveries = drain_recorder();
+ assert!(
+ !deliveries.is_empty(),
+ "at least one delivery expected after tracing::error!"
+ );
+ let d = deliveries
+ .iter()
+ .find(|d| d.message.contains("deliver_event"))
+ .unwrap_or(&deliveries[0]);
+ assert_eq!(d.level, 1, "ERROR maps to level 1");
+ assert!(!d.message.is_empty(), "message must be non-empty");
+
+ unsafe {
+ let _ = ad_set_log_callback(None);
+ }
+}
+
+#[test]
+fn log_callback_spawned_thread_does_not_panic() {
+ let _guard = LOG_TEST_LOCK.lock().unwrap();
+ clear_recorder();
+
+ unsafe {
+ let rc = ad_set_log_callback(Some(recorder_cb));
+ assert_eq!(rc, AdResult::Ok);
+ }
+
+ let handle = std::thread::spawn(|| {
+ tracing::warn!(
+ source = "spawned_thread",
+ "log_callback_spawned_thread_does_not_panic"
+ );
+ });
+ handle.join().expect("spawned thread must not panic");
+
+ let deliveries = drain_recorder();
+ assert!(
+ !deliveries.is_empty(),
+ "spawned-thread event must reach the callback"
+ );
+
+ unsafe {
+ let _ = ad_set_log_callback(None);
+ }
+}
+
+#[test]
+fn log_callback_null_unregisters() {
+ let _guard = LOG_TEST_LOCK.lock().unwrap();
+ clear_recorder();
+
+ unsafe {
+ let _ = ad_set_log_callback(Some(recorder_cb));
+ let rc = ad_set_log_callback(None);
+ assert_eq!(rc, AdResult::Ok, "NULL unregister must succeed");
+ }
+ clear_recorder();
+
+ tracing::error!(test_marker = "after_null", "log_callback_null_unregisters");
+
+ let deliveries = drain_recorder();
+ assert!(
+ deliveries.is_empty(),
+ "no deliveries expected after NULL unregister, got {}",
+ deliveries.len()
+ );
+}
+
+#[test]
+fn log_callback_redacts_sensitive_fields() {
+ let _guard = LOG_TEST_LOCK.lock().unwrap();
+ clear_recorder();
+
+ unsafe {
+ let rc = ad_set_log_callback(Some(recorder_cb));
+ assert_eq!(rc, AdResult::Ok);
+ }
+
+ tracing::error!(
+ password = "super_secret_password",
+ token = "bearer_xyz",
+ operation = "login_attempt",
+ "log_callback_redacts_sensitive_fields"
+ );
+
+ let deliveries = drain_recorder();
+ assert!(!deliveries.is_empty(), "expected at least one delivery");
+
+ let combined: String = deliveries
+ .iter()
+ .map(|d| d.message.as_str())
+ .collect::<Vec<_>>()
+ .join(" ");
+
+ assert!(
+ !combined.contains("super_secret_password"),
+ "raw password must not appear in callback message; got: {combined}"
+ );
+ assert!(
+ !combined.contains("bearer_xyz"),
+ "raw token must not appear in callback message; got: {combined}"
+ );
+ assert!(
+ combined.contains("redacted"),
+ "redaction marker must appear; got: {combined}"
+ );
+ assert!(
+ combined.contains("login_attempt"),
+ "non-sensitive field value must be preserved; got: {combined}"
+ );
+
+ unsafe {
+ let _ = ad_set_log_callback(None);
+ }
+}
+
+#[test]
+fn log_callback_re_register_is_ok() {
+ let _guard = LOG_TEST_LOCK.lock().unwrap();
+ clear_recorder();
+
+ unsafe {
+ assert_eq!(ad_set_log_callback(Some(recorder_cb)), AdResult::Ok);
+ assert_eq!(ad_set_log_callback(None), AdResult::Ok);
+ assert_eq!(ad_set_log_callback(Some(recorder_cb)), AdResult::Ok);
+ assert_eq!(ad_set_log_callback(None), AdResult::Ok);
+ }
+}
diff --git a/crates/ffi/tests/c_abi_roundtrip.rs b/crates/ffi/tests/c_abi_roundtrip.rs
new file mode 100644
index 000000000..07894b730
--- /dev/null
+++ b/crates/ffi/tests/c_abi_roundtrip.rs
@@ -0,0 +1,285 @@
+/// Integration tests for the observe→act loop at the C boundary.
+///
+/// # Test structure
+///
+/// - `stale_ref_returns_ok_false_error_envelope` — always runs in CI.
+/// Sets a temp HOME (empty refmap), calls `ad_execute_by_ref`, and asserts
+/// that the returned envelope has `ok:false` with both `error.code` (string)
+/// and `error.message` (string), and that `command` equals `"execute_by_ref"`.
+/// On macOS the main-thread guard fires before the command path is reached
+/// (libtest runs bodies off the main thread), returning `ErrInternal` with a
+/// null `*out` — that path is tolerated.
+///
+/// - `snapshot_execute_by_ref_live_roundtrip` — marked `#[ignore]`.
+/// The full observe→act loop (real `ad_snapshot` → `@e` ref →
+/// `ad_execute_by_ref` against a live app) cannot run under the default
+/// libtest harness on macOS: libtest schedules test bodies on worker threads,
+/// and the AX/main-thread guard blocks every AX call made off the main
+/// thread. CI proof of the full loop is tracked as the deferred
+/// external-consumer smoke harness (Python ctypes) — plan unit U9 / Phase B.
+/// To run the roundtrip manually:
+/// ```text
+/// cargo test -p agent-desktop-ffi --tests c_abi_roundtrip \
+/// snapshot_execute_by_ref_live_roundtrip -- --ignored
+/// ```
+/// Run from a process that owns the main thread (e.g. the E2E harness).
+/// AX accessibility permission must be granted and a target app must be open.
+mod common;
+
+use common::{AdResult, CStr, ad_execute_by_ref, ad_free_string, ad_snapshot, default_action};
+use std::sync::Mutex;
+
+static HOME_LOCK: Mutex<()> = Mutex::new(());
+
+struct TestHome {
+ _lock: std::sync::MutexGuard<'static, ()>,
+ dir: std::path::PathBuf,
+ prev: Option<std::ffi::OsString>,
+}
+
+impl TestHome {
+ fn new() -> Self {
+ let lock = HOME_LOCK.lock().unwrap();
+ let dir = std::env::temp_dir().join(format!(
+ "agent-desktop-ffi-roundtrip-{}",
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ std::fs::create_dir_all(&dir).unwrap();
+ let prev = std::env::var_os("HOME");
+ unsafe { std::env::set_var("HOME", &dir) };
+ Self {
+ _lock: lock,
+ dir,
+ prev,
+ }
+ }
+}
+
+impl Drop for TestHome {
+ fn drop(&mut self) {
+ match self.prev.as_ref() {
+ Some(prev) => unsafe { std::env::set_var("HOME", prev) },
+ None => unsafe { std::env::remove_var("HOME") },
+ }
+ let _ = std::fs::remove_dir_all(&self.dir);
+ }
+}
+
+/// Verifies the error-envelope contract at the C boundary when no refmap exists.
+///
+/// Sets a temp HOME so the refmap store is empty. Calls `ad_execute_by_ref`
+/// with a well-formed `@e1` ref. On macOS the main-thread guard fires first
+/// (libtest runs off the main thread), returning `ErrInternal` with `out`
+/// remaining null — that is tolerated. When the command path does execute
+/// (non-macOS or future main-thread execution), the envelope must have
+/// `ok:false` and carry both `error.code` (string) and `error.message`
+/// (string) — the latter guaranteed by the CLAUDE.md error contract — proving
+/// the unified error-envelope contract holds at the ABI boundary. The exact
+/// `error.code` value is not pinned: an empty refmap with an `@e1` ref may
+/// surface either `SNAPSHOT_NOT_FOUND` or `STALE_REF` depending on the load
+/// path; pinning either would make this test flaky.
+#[test]
+fn stale_ref_returns_ok_false_error_envelope() {
+ let _home = TestHome::new();
+
+ with_adapter_raw(|adapter| unsafe {
+ let ref_id = std::ffi::CString::new("@e1").unwrap();
+ let action = default_action();
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+
+ let rc = ad_execute_by_ref(
+ adapter,
+ ref_id.as_ptr(),
+ std::ptr::null(),
+ &action,
+ 0,
+ &mut out,
+ );
+
+ let rc_i32 = rc as i32;
+ assert!(
+ rc_i32 <= 0,
+ "must return a valid AdResult (<=0), got {rc_i32}"
+ );
+
+ if out.is_null() {
+ assert_eq!(
+ rc,
+ AdResult::ErrInternal,
+ "null *out is only expected when ErrInternal (main-thread guard on macOS), got {rc:?}"
+ );
+ return;
+ }
+
+ let s = CStr::from_ptr(out).to_string_lossy();
+ let val: serde_json::Value = serde_json::from_str(&s).expect("response must be valid JSON");
+
+ assert_eq!(
+ val["ok"].as_bool(),
+ Some(false),
+ "error envelope ok must be false; got: {s}"
+ );
+ assert!(
+ val["error"].is_object(),
+ "error envelope must carry an error object; got: {s}"
+ );
+ assert!(
+ val["error"]["code"].is_string(),
+ "error.code must be a string; got: {s}"
+ );
+ assert!(
+ val["error"]["message"].is_string(),
+ "error.message must be a string; got: {s}"
+ );
+ assert!(
+ val["version"].is_string(),
+ "envelope version must be present; got: {s}"
+ );
+ assert_eq!(
+ val["command"].as_str(),
+ Some("execute_by_ref"),
+ "command must be 'execute_by_ref'; got: {s}"
+ );
+
+ ad_free_string(out);
+ });
+}
+
+/// Live snapshot→ref→execute_by_ref roundtrip at the C boundary.
+///
+/// This test is `#[ignore]` by design and must remain so in headless CI.
+///
+/// **Why ignored**: libtest schedules test bodies on worker threads. On macOS
+/// every AX API call (including `ad_snapshot` and `ad_execute_by_ref`) must
+/// originate on the main thread; the AX guard returns `ErrInternal` immediately
+/// when called off it. There is no libtest API to pin a test to the main
+/// thread, so the full observe→act loop cannot be verified inside a libtest
+/// integration test on macOS.
+///
+/// **Deferred CI proof**: the full-loop proof — real `ad_snapshot` producing
+/// `@e` refs consumed by `ad_execute_by_ref` against a live app at the C
+/// boundary — is tracked as plan unit U9 / Phase B: an external-consumer smoke
+/// harness (Python ctypes) that runs in the E2E environment where the process
+/// itself owns the main thread.
+///
+/// **Manual execution** (requires AX permission + a running target app):
+/// ```text
+/// cargo test -p agent-desktop-ffi --tests c_abi_roundtrip \
+/// snapshot_execute_by_ref_live_roundtrip -- --ignored
+/// ```
+/// Run from a process that owns the main thread (e.g. the E2E harness). Do
+/// NOT un-ignore this test — it will fail in any headless CI that uses libtest.
+#[test]
+#[ignore = "requires AX permission, a live app, and main-thread execution — run via E2E harness"]
+fn snapshot_execute_by_ref_live_roundtrip() {
+ let _home = TestHome::new();
+
+ with_adapter_raw(|adapter| unsafe {
+ let mut snap_out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_snapshot(adapter, std::ptr::null(), 0, 6, true, false, &mut snap_out);
+
+ assert_eq!(rc, AdResult::Ok, "snapshot must succeed");
+ assert!(
+ !snap_out.is_null(),
+ "snapshot out must be non-null on success"
+ );
+
+ let snap_str = CStr::from_ptr(snap_out).to_string_lossy();
+ let snap_val: serde_json::Value =
+ serde_json::from_str(&snap_str).expect("snapshot must be valid JSON");
+
+ assert_eq!(
+ snap_val["ok"].as_bool(),
+ Some(true),
+ "snapshot envelope ok must be true"
+ );
+
+ let ref_id = find_first_ref_in_tree(&snap_val)
+ .expect("snapshot must contain at least one @e ref in the tree");
+
+ ad_free_string(snap_out);
+
+ let ref_cstr = std::ffi::CString::new(ref_id.as_str()).unwrap();
+ let action = default_action();
+ let mut exec_out: *mut std::os::raw::c_char = std::ptr::null_mut();
+
+ let exec_rc = ad_execute_by_ref(
+ adapter,
+ ref_cstr.as_ptr(),
+ std::ptr::null(),
+ &action,
+ 0,
+ &mut exec_out,
+ );
+
+ assert!(
+ !exec_out.is_null(),
+ "execute_by_ref must produce an envelope (ok or error), got rc={exec_rc:?}"
+ );
+
+ let exec_str = CStr::from_ptr(exec_out).to_string_lossy();
+ let exec_val: serde_json::Value =
+ serde_json::from_str(&exec_str).expect("execute_by_ref response must be valid JSON");
+
+ assert!(
+ exec_val["version"].is_string(),
+ "response must carry envelope version; got: {exec_str}"
+ );
+ assert!(
+ exec_val["ok"].is_boolean(),
+ "response must carry ok field; got: {exec_str}"
+ );
+ assert_eq!(
+ exec_val["command"].as_str(),
+ Some("execute_by_ref"),
+ "command must be execute_by_ref; got: {exec_str}"
+ );
+
+ ad_free_string(exec_out);
+ });
+}
+
+fn find_first_ref_in_tree(snap: &serde_json::Value) -> Option<String> {
+ search_refs(snap)
+}
+
+fn search_refs(val: &serde_json::Value) -> Option<String> {
+ match val {
+ serde_json::Value::Object(map) => {
+ if let Some(r) = map.get("ref") {
+ if let Some(s) = r.as_str() {
+ if s.starts_with("@e") {
+ return Some(s.to_owned());
+ }
+ }
+ }
+ for v in map.values() {
+ if let Some(found) = search_refs(v) {
+ return Some(found);
+ }
+ }
+ None
+ }
+ serde_json::Value::Array(arr) => {
+ for v in arr {
+ if let Some(found) = search_refs(v) {
+ return Some(found);
+ }
+ }
+ None
+ }
+ _ => None,
+ }
+}
+
+fn with_adapter_raw<F: FnOnce(*mut common::AdAdapter)>(body: F) {
+ unsafe {
+ let adapter = common::ad_adapter_create();
+ assert!(!adapter.is_null(), "ad_adapter_create must not return null");
+ body(adapter);
+ common::ad_adapter_destroy(adapter);
+ }
+}
diff --git a/crates/ffi/tests/c_abi_session.rs b/crates/ffi/tests/c_abi_session.rs
new file mode 100644
index 000000000..2ee2bfaa9
--- /dev/null
+++ b/crates/ffi/tests/c_abi_session.rs
@@ -0,0 +1,88 @@
+mod common;
+
+use common::{
+ AdResult, CStr, ad_adapter_create, ad_adapter_create_with_session, ad_adapter_destroy,
+ ad_last_error_code, ad_last_error_message,
+};
+
+#[test]
+fn sessionless_adapter_has_no_session_id() {
+ unsafe {
+ let ptr = ad_adapter_create();
+ assert!(!ptr.is_null(), "ad_adapter_create must not return null");
+ let ctx = (*ptr)
+ .command_context()
+ .expect("command_context must succeed");
+ assert_eq!(ctx.session_id(), None);
+ ad_adapter_destroy(ptr);
+ }
+}
+
+#[test]
+fn session_adapter_carries_session_id() {
+ unsafe {
+ let session = std::ffi::CString::new("agent-a").unwrap();
+ let ptr = ad_adapter_create_with_session(session.as_ptr());
+ assert!(
+ !ptr.is_null(),
+ "ad_adapter_create_with_session must not return null"
+ );
+ let ctx = (*ptr)
+ .command_context()
+ .expect("command_context must succeed");
+ assert_eq!(ctx.session_id(), Some("agent-a"));
+ ad_adapter_destroy(ptr);
+ }
+}
+
+#[test]
+fn null_session_adapter_is_sessionless() {
+ unsafe {
+ let ptr = ad_adapter_create_with_session(std::ptr::null());
+ assert!(
+ !ptr.is_null(),
+ "null session must yield a sessionless adapter"
+ );
+ let ctx = (*ptr)
+ .command_context()
+ .expect("command_context must succeed");
+ assert_eq!(ctx.session_id(), None);
+ ad_adapter_destroy(ptr);
+ }
+}
+
+#[test]
+fn invalid_utf8_session_returns_null_and_sets_invalid_args() {
+ unsafe {
+ let bad: [u8; 3] = [0xC3, 0xFF, 0x00];
+ let ptr = ad_adapter_create_with_session(bad.as_ptr() as *const std::os::raw::c_char);
+ assert!(ptr.is_null(), "invalid UTF-8 session must return null");
+ assert_eq!(
+ ad_last_error_code(),
+ AdResult::ErrInvalidArgs,
+ "invalid UTF-8 must set ErrInvalidArgs"
+ );
+ let msg = ad_last_error_message();
+ assert!(
+ !msg.is_null(),
+ "error message must be set on invalid UTF-8 session"
+ );
+ }
+}
+
+#[test]
+fn empty_session_returns_null_and_sets_invalid_args() {
+ unsafe {
+ let empty = std::ffi::CString::new("").unwrap();
+ let ptr = ad_adapter_create_with_session(empty.as_ptr());
+ assert!(ptr.is_null(), "empty session id must return null");
+ assert_eq!(
+ ad_last_error_code(),
+ AdResult::ErrInvalidArgs,
+ "empty session id must set ErrInvalidArgs"
+ );
+ let msg = ad_last_error_message();
+ assert!(!msg.is_null(), "error message must be set on empty session");
+ let _ = CStr::from_ptr(msg).to_string_lossy();
+ }
+}
diff --git a/crates/ffi/tests/c_abi_snapshot.rs b/crates/ffi/tests/c_abi_snapshot.rs
new file mode 100644
index 000000000..9992463cc
--- /dev/null
+++ b/crates/ffi/tests/c_abi_snapshot.rs
@@ -0,0 +1,131 @@
+mod common;
+
+use common::{AdResult, CStr, ad_free_string, ad_snapshot, with_adapter};
+
+#[test]
+fn snapshot_null_out_returns_invalid_args() {
+ with_adapter(|adapter| unsafe {
+ let rc = ad_snapshot(
+ adapter,
+ std::ptr::null(),
+ 0,
+ 6,
+ false,
+ false,
+ std::ptr::null_mut(),
+ );
+ assert_eq!(
+ rc,
+ AdResult::ErrInvalidArgs,
+ "null out is rejected by the outer guard before any adapter or thread check"
+ );
+ });
+}
+
+#[test]
+fn snapshot_null_adapter_rejected() {
+ unsafe {
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_snapshot(
+ std::ptr::null(),
+ std::ptr::null(),
+ 0,
+ 6,
+ false,
+ false,
+ &mut out,
+ );
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "null adapter must fail — got {rc:?} (ErrInternal on macOS off-main-thread is expected)"
+ );
+ assert!(out.is_null(), "out must stay null on null-adapter failure");
+ }
+}
+
+#[test]
+fn snapshot_invalid_utf8_app_rejected() {
+ with_adapter(|adapter| unsafe {
+ let bad: [u8; 3] = [0xC3, 0xFF, 0x00];
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_snapshot(
+ adapter,
+ bad.as_ptr() as *const std::os::raw::c_char,
+ 0,
+ 6,
+ false,
+ false,
+ &mut out,
+ );
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "invalid UTF-8 app must fail — got {rc:?}"
+ );
+ assert!(
+ out.is_null(),
+ "out must stay null on arg validation failure"
+ );
+ });
+}
+
+#[test]
+fn snapshot_invalid_surface_rejected() {
+ with_adapter(|adapter| unsafe {
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_snapshot(adapter, std::ptr::null(), 99, 6, false, false, &mut out);
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "out-of-range surface must fail — got {rc:?}"
+ );
+ assert!(out.is_null(), "out must stay null on invalid surface");
+ });
+}
+
+#[test]
+fn snapshot_returns_a_result_code_and_frees_cleanly() {
+ with_adapter(|adapter| unsafe {
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_snapshot(adapter, std::ptr::null(), 0, 6, false, false, &mut out);
+ let rc_i32 = rc as i32;
+ assert!(
+ rc_i32 <= 0,
+ "ad_snapshot must return a valid AdResult (<=0), got {rc_i32}"
+ );
+ if !out.is_null() {
+ let s = CStr::from_ptr(out).to_string_lossy();
+ assert!(!s.is_empty(), "non-null out must be a non-empty string");
+ ad_free_string(out);
+ }
+ });
+}
+
+#[test]
+fn snapshot_out_contains_envelope_fields_on_any_response() {
+ with_adapter(|adapter| unsafe {
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_snapshot(adapter, std::ptr::null(), 0, 6, false, false, &mut out);
+ if !out.is_null() {
+ let s = CStr::from_ptr(out).to_string_lossy();
+ assert!(
+ s.contains("\"version\""),
+ "envelope must carry 'version', got: {s}"
+ );
+ assert!(s.contains("\"ok\""), "envelope must carry 'ok', got: {s}");
+ assert!(
+ s.contains("\"command\""),
+ "envelope must carry 'command', got: {s}"
+ );
+ assert!(
+ s.contains("\"snapshot\""),
+ "command value must be 'snapshot', got: {s}"
+ );
+ ad_free_string(out);
+ } else {
+ let rc_i32 = rc as i32;
+ assert!(
+ rc_i32 < 0,
+ "null out is only valid on failure, got rc={rc_i32}"
+ );
+ }
+ });
+}
diff --git a/crates/ffi/tests/c_abi_wait.rs b/crates/ffi/tests/c_abi_wait.rs
new file mode 100644
index 000000000..89778fbf9
--- /dev/null
+++ b/crates/ffi/tests/c_abi_wait.rs
@@ -0,0 +1,178 @@
+mod common;
+
+use common::{
+ AdResult, AdWaitArgs, CStr, ad_free_string, ad_last_error_code, ad_last_error_message, ad_wait,
+ with_adapter,
+};
+
+#[test]
+fn ad_wait_null_args_rejected() {
+ with_adapter(|adapter| unsafe {
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_wait(adapter, std::ptr::null(), &mut out);
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "null args must be rejected, got {:?}",
+ rc
+ );
+ assert!(out.is_null(), "out must stay null on null-args rejection");
+ assert_eq!(
+ ad_last_error_code(),
+ rc,
+ "last-error code must match returned AdResult (errno invariant)"
+ );
+ });
+}
+
+#[test]
+fn ad_wait_null_out_rejected() {
+ with_adapter(|adapter| unsafe {
+ let args = AdWaitArgs {
+ ms: 1,
+ has_ms: true,
+ element: std::ptr::null(),
+ window: std::ptr::null(),
+ text: std::ptr::null(),
+ menu: false,
+ menu_closed: false,
+ notification: false,
+ snapshot_id: std::ptr::null(),
+ predicate: std::ptr::null(),
+ value: std::ptr::null(),
+ action: std::ptr::null(),
+ count: 0,
+ has_count: false,
+ timeout_ms: 500,
+ app: std::ptr::null(),
+ };
+ let rc = ad_wait(adapter, &args, std::ptr::null_mut());
+ assert!(
+ matches!(rc, AdResult::ErrInvalidArgs | AdResult::ErrInternal),
+ "null out must be rejected, got {:?}",
+ rc
+ );
+ assert_eq!(
+ ad_last_error_code(),
+ rc,
+ "last-error code must match returned AdResult (errno invariant)"
+ );
+ });
+}
+
+#[test]
+fn ad_wait_ms_mode_returns_ok_or_off_thread_error() {
+ with_adapter(|adapter| unsafe {
+ let args = AdWaitArgs {
+ ms: 50,
+ has_ms: true,
+ element: std::ptr::null(),
+ window: std::ptr::null(),
+ text: std::ptr::null(),
+ menu: false,
+ menu_closed: false,
+ notification: false,
+ snapshot_id: std::ptr::null(),
+ predicate: std::ptr::null(),
+ value: std::ptr::null(),
+ action: std::ptr::null(),
+ count: 0,
+ has_count: false,
+ timeout_ms: 500,
+ app: std::ptr::null(),
+ };
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_wait(adapter, &args, &mut out);
+
+ match rc {
+ AdResult::Ok => {
+ assert!(!out.is_null(), "Ok result must set out");
+ let json_cstr = CStr::from_ptr(out);
+ let json: serde_json::Value =
+ serde_json::from_str(json_cstr.to_str().unwrap()).unwrap();
+ assert_eq!(json["ok"], serde_json::Value::Bool(true));
+ assert_eq!(json["command"], "wait");
+ ad_free_string(out);
+ }
+ AdResult::ErrInternal => {
+ assert!(out.is_null(), "ErrInternal must leave out null");
+ let msg = ad_last_error_message();
+ assert!(!msg.is_null(), "error message must be set on failure");
+ assert_eq!(
+ ad_last_error_code(),
+ AdResult::ErrInternal,
+ "last-error code must match returned AdResult (errno invariant)"
+ );
+ }
+ other => panic!("unexpected result from ms-mode ad_wait: {:?}", other),
+ }
+ });
+}
+
+#[test]
+fn ad_wait_command_error_writes_error_envelope_into_out() {
+ with_adapter(|adapter| unsafe {
+ let elem = std::ffi::CString::new("__nonexistent_element__").unwrap();
+ let args = AdWaitArgs {
+ ms: 0,
+ has_ms: false,
+ element: elem.as_ptr(),
+ window: std::ptr::null(),
+ text: std::ptr::null(),
+ menu: false,
+ menu_closed: false,
+ notification: false,
+ snapshot_id: std::ptr::null(),
+ predicate: std::ptr::null(),
+ value: std::ptr::null(),
+ action: std::ptr::null(),
+ count: 0,
+ has_count: false,
+ timeout_ms: 0,
+ app: std::ptr::null(),
+ };
+ let mut out: *mut std::os::raw::c_char = std::ptr::null_mut();
+ let rc = ad_wait(adapter, &args, &mut out);
+
+ match rc {
+ AdResult::Ok => {
+ assert!(!out.is_null(), "Ok result must set out");
+ ad_free_string(out);
+ }
+ AdResult::ErrInternal => {
+ assert!(
+ out.is_null(),
+ "ErrInternal from off-main-thread guard must leave out null"
+ );
+ }
+ _ => {
+ assert!(
+ !out.is_null(),
+ "command-level error must write error envelope into *out, got rc={rc:?}"
+ );
+ let s = CStr::from_ptr(out).to_string_lossy();
+ let val: serde_json::Value =
+ serde_json::from_str(&s).expect("error envelope must be valid JSON");
+ assert_eq!(
+ val["ok"].as_bool(),
+ Some(false),
+ "error envelope ok must be false, got: {s}"
+ );
+ assert_eq!(
+ val["command"].as_str(),
+ Some("wait"),
+ "command field must be 'wait', got: {s}"
+ );
+ assert!(
+ val["error"].is_object(),
+ "error envelope must carry an error object, got: {s}"
+ );
+ assert_eq!(
+ ad_last_error_code(),
+ rc,
+ "last-error code must match returned AdResult (errno invariant)"
+ );
+ ad_free_string(out);
+ }
+ }
+ });
+}
diff --git a/crates/ffi/tests/c_header_double_include.rs b/crates/ffi/tests/c_header_double_include.rs
new file mode 100644
index 000000000..b3c9ad77c
--- /dev/null
+++ b/crates/ffi/tests/c_header_double_include.rs
@@ -0,0 +1,85 @@
+//! Regression test: including `agent_desktop.h` twice in one translation unit
+//! must not produce a compilation error.
+//!
+//! The header emits `_Static_assert` blocks outside its `AGENT_DESKTOP_H`
+//! include guard (cbindgen places the trailer after the closing `#endif`).
+//! C11 §6.7.10 allows repeated file-scope `_Static_assert` declarations, so a
+//! bare double-include is legal; the `AGENT_DESKTOP_ABI_ASSERTS` one-shot guard
+//! in the trailer makes this unambiguously safe in all C standards.
+//!
+//! If this test starts failing, check that the cbindgen.toml trailer still
+//! wraps its `_Static_assert` block in `#ifndef AGENT_DESKTOP_ABI_ASSERTS`.
+//!
+//! 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_survives_double_include() {
+ 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_double_include_test.c");
+ let obj = std::env::temp_dir().join("agent_desktop_double_include_test.o");
+ let src = r#"
+#include <stdint.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include "agent_desktop.h"
+#include "agent_desktop.h"
+
+int check(void) { 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(),
+ "Double-include of agent_desktop.h failed to compile. \
+ Ensure the cbindgen.toml trailer wraps _Static_assert blocks in \
+ #ifndef AGENT_DESKTOP_ABI_ASSERTS so they are not re-emitted on a \
+ second include."
+ );
+}
diff --git a/crates/ffi/tests/common/mod.rs b/crates/ffi/tests/common/mod.rs
index 521e0482a..d52e2f888 100644
--- a/crates/ffi/tests/common/mod.rs
+++ b/crates/ffi/tests/common/mod.rs
@@ -5,19 +5,35 @@ pub use agent_desktop_ffi::error::AdResult;
pub use agent_desktop_ffi::{
AdAction, AdActionResult, AdActionStep, AdAdapter, AdAppList, AdDirection, AdDragParams,
AdElementState, AdFindQuery, AdKeyCombo, AdNativeHandle, AdPoint, AdPolicyKind, AdRect,
- AdRefEntry, AdScrollParams, AdWindowInfo, AdWindowList,
+ AdRefEntry, AdScrollParams, AdWaitArgs, AdWindowInfo, AdWindowList,
};
pub use std::ffi::CStr;
pub use std::os::raw::c_char;
unsafe extern "C" {
+ pub fn ad_abi_version() -> u32;
+ pub fn ad_init(expected_major: u32) -> AdResult;
+ pub fn ad_version(out: *mut *mut c_char) -> AdResult;
+ pub fn ad_free_string(s: *mut c_char);
+ pub fn ad_set_log_callback(
+ cb: Option<unsafe extern "C" fn(level: i32, msg: *const c_char)>,
+ ) -> AdResult;
+
pub fn ad_ref_entry_size() -> usize;
pub fn ad_action_size() -> usize;
pub fn ad_action_step_size() -> usize;
pub fn ad_action_result_size() -> usize;
pub fn ad_element_state_size() -> usize;
+ pub fn ad_wait_args_size() -> usize;
+
+ pub fn ad_wait(
+ adapter: *const AdAdapter,
+ args: *const AdWaitArgs,
+ out: *mut *mut c_char,
+ ) -> AdResult;
pub fn ad_adapter_create() -> *mut AdAdapter;
+ pub fn ad_adapter_create_with_session(session: *const c_char) -> *mut AdAdapter;
pub fn ad_adapter_destroy(adapter: *mut AdAdapter);
pub fn ad_check_permissions(adapter: *const AdAdapter) -> AdResult;
@@ -82,6 +98,27 @@ unsafe extern "C" {
entry: *const AdRefEntry,
out: *mut AdNativeHandle,
) -> AdResult;
+
+ pub fn ad_snapshot(
+ adapter: *const AdAdapter,
+ app: *const c_char,
+ surface: i32,
+ max_depth: u8,
+ interactive_only: bool,
+ compact: bool,
+ out: *mut *mut c_char,
+ ) -> AdResult;
+ pub fn ad_status(adapter: *const AdAdapter, out: *mut *mut c_char) -> AdResult;
+
+ pub fn ad_execute_by_ref(
+ adapter: *const AdAdapter,
+ ref_id: *const c_char,
+ snapshot_id: *const c_char,
+ action: *const AdAction,
+ policy: i32,
+ out: *mut *mut c_char,
+ ) -> AdResult;
+
}
pub fn with_adapter<F: FnOnce(*mut AdAdapter)>(body: F) {
diff --git a/scripts/update-ffi-header.sh b/scripts/update-ffi-header.sh
index 9987b7cf4..fe98ca213 100755
--- a/scripts/update-ffi-header.sh
+++ b/scripts/update-ffi-header.sh
@@ -4,12 +4,27 @@ set -euo pipefail
# Regenerate the committed FFI header from source. This script is deliberately
# outside the normal Cargo build graph so cbindgen never executes during
# ordinary builds, tests, CI, or release packaging.
+#
+# Required cbindgen version: 0.29.4 (verify with `cbindgen --version`)
+# Install: cargo install cbindgen --version 0.29.4 --locked
+# The [const] allow_static_const = false key requires cbindgen >= 0.26;
+# the trailer key requires cbindgen >= 0.25.
ROOT=$(git rev-parse --show-toplevel)
cd "$ROOT"
+REQUIRED_CBINDGEN="0.29.4"
+
if ! command -v cbindgen >/dev/null 2>&1; then
echo "ERROR: cbindgen is not installed. Install and audit it explicitly before regenerating the FFI header." >&2
+ echo " cargo install cbindgen --version ${REQUIRED_CBINDGEN} --locked" >&2
+ exit 1
+fi
+
+ACTUAL_CBINDGEN=$(cbindgen --version 2>&1 | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)
+if [ "${ACTUAL_CBINDGEN}" != "${REQUIRED_CBINDGEN}" ]; then
+ echo "ERROR: cbindgen ${REQUIRED_CBINDGEN} required, found ${ACTUAL_CBINDGEN}." >&2
+ echo " cargo install cbindgen --version ${REQUIRED_CBINDGEN} --locked" >&2
exit 1
fi
diff --git a/src/cli/contract_tests.rs b/src/cli/contract_tests.rs
index 6bb5b2306..40230fbf5 100644
--- a/src/cli/contract_tests.rs
+++ b/src/cli/contract_tests.rs
@@ -4,6 +4,7 @@ use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
const NON_COMMAND_MODULES: &[&str] = &[
+ "execute_by_ref",
"helpers",
"helpers_test_support",
"mod",