Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
refactor(cdp): format native replies without adapter output plans
ldm00c3b9cd6d32d
diff --git a/moli-protocol/src/domains/autofill.rs b/moli-protocol/src/domains/autofill.rsindex 7effe7806..fbfffe0da 100644--- a/moli-protocol/src/domains/autofill.rs+++ b/moli-protocol/src/domains/autofill.rs@@ -85,27 +85,32 @@ pub(crate) fn complete_pending_autofill_command(})});project_outcome(outcome)+ .map(|()| CommandOutputPlan::success())+ .unwrap_or_else(|(code, message)| CommandOutputPlan::error(code, message))}-fn project_outcome(outcome: Result<RendererAutofillTriggerOutcome, String>) -> CommandOutputPlan {+fn project_outcome(+ outcome: Result<RendererAutofillTriggerOutcome, String>,+) -> Result<(), (i32, String)> {match outcome {- Ok(RendererAutofillTriggerOutcome::Applied { .. }) => CommandOutputPlan::success(),+ Ok(RendererAutofillTriggerOutcome::Applied { .. }) => Ok(()),Ok(RendererAutofillTriggerOutcome::FieldNotFound) => {- CommandOutputPlan::error(-32600, "Field not found")+ Err((-32600, "Field not found".to_owned()))}Ok(RendererAutofillTriggerOutcome::FrameNotFound) => {- CommandOutputPlan::error(-32000, "Frame not found")- }- Ok(RendererAutofillTriggerOutcome::CardAndAddressProvided) => {- CommandOutputPlan::error(-32600, "Card and address cannot both be provided")+ Err((-32000, "Frame not found".to_owned()))}+ Ok(RendererAutofillTriggerOutcome::CardAndAddressProvided) => Err((+ -32600,+ "Card and address cannot both be provided".to_owned(),+ )),Ok(RendererAutofillTriggerOutcome::MissingCardOrAddress) => {- CommandOutputPlan::error(-32600, "Either card or address must be provided")+ Err((-32600, "Either card or address must be provided".to_owned()))}Ok(RendererAutofillTriggerOutcome::AddressNotSupported) => {- CommandOutputPlan::error(-32000, "Address autofill is not supported")+ Err((-32000, "Address autofill is not supported".to_owned()))}- Err(message) => CommandOutputPlan::error(-32000, message),+ Err(message) => Err((-32000, message)),}}fn prepare_request(@@ -167,7 +172,10 @@ pub(crate) fn try_start_native_command(conn: &mut CdpConnection,cmd: &Cmd<'_>,) -> Option<super::native::NativeCommandStep> {- use moli_core::{RendererPageCommand as Command, RendererPageReply as Reply};+ use moli_core::{+ RendererNativeProtocolResponse as Response, RendererPageCommand as Command,+ RendererPageReply as Reply,+ };Some(match prepare_request(conn, cmd) {Ok(request) => {super::native::start(conn, cmd, Command::TriggerAutofill(request), |reply| {@@ -176,7 +184,9 @@ pub(crate) fn try_start_native_command(Err(error) => Err(error.to_string()),_ => unreachable!("Autofill trigger reply"),};- project_outcome(outcome).into_native_response()+ project_outcome(outcome)+ .map(|()| Response::success(serde_json::json!({})))+ .unwrap_or_else(|(code, message)| Response::error(code, message))})}Err(plan) => super::native::NativeCommandStep::Complete(plan),diff --git a/moli-protocol/src/domains/command_output.rs b/moli-protocol/src/domains/command_output.rsindex 519e58a05..0ad537d3b 100644--- a/moli-protocol/src/domains/command_output.rs+++ b/moli-protocol/src/domains/command_output.rs@@ -78,34 +78,6 @@ enum CommandOwnerEvent {}impl CommandOutputPlan {- /// Reuses a pure result formatter inside a renderer-owned handler. A- /// formatter requiring Browser events, fences or continuations cannot be- /// moved across this boundary by silently dropping those responsibilities.- pub(crate) fn into_native_response(self) -> moli_core::RendererNativeProtocolResponse {- assert!(self.post_response_events.is_empty());- assert!(self.renderer_output_predecessor.is_none());- assert!(self.renderer_output_boundary.is_none());- assert_eq!(- self.outputs.len(),- 1,- "native result formatter has one terminal"- );- match self.outputs.into_iter().next().unwrap() {- CommandOutput::Command(CommandResponseOutput::Success(result)) => {- moli_core::RendererNativeProtocolResponse::success(match result {- CommandResponseResult::Empty => json!({}),- CommandResponseResult::Json(result) => result,- })- }- CommandOutput::Command(CommandResponseOutput::Error {- code,- message,- data: None,- }) => moli_core::RendererNativeProtocolResponse::error(code, message),- _ => panic!("native result formatter cannot own Browser output"),- }- }-pub(crate) fn success() -> Self {Self::from_devtools_result(DevToolsCommandResult::Empty)}diff --git a/moli-protocol/src/domains/css.rs b/moli-protocol/src/domains/css.rsindex 1827c3a3b..0fee9cbde 100644--- a/moli-protocol/src/domains/css.rs+++ b/moli-protocol/src/domains/css.rs@@ -547,10 +547,8 @@ pub(crate) fn complete_pending_css_command(}};CssCommandDispatchStep::Complete(match page.finish_style_sheet_payload(completion) {- Ok(Some(payload)) => style_sheets::get_style_sheet_command_output_plan(- &style_sheet_id,- &frame_id,- payload,+ Ok(Some(payload)) => CommandOutputPlan::result(+ style_sheets::get_style_sheet_result(&style_sheet_id, &frame_id, payload),),Ok(None) => {CommandOutputPlan::error(-32000, "Could not find stylesheet with given id")@@ -591,7 +589,9 @@ pub(crate) fn complete_pending_css_command(};CssCommandDispatchStep::Complete(match page.finish_computed_style_properties(completion) {- Ok(Some(properties)) => computed_style_command_output_plan(properties),+ Ok(Some(properties)) => {+ CommandOutputPlan::result(computed_style_result(properties))+ }Ok(None) => {CommandOutputPlan::error(-32000, "Could not find node with given id")}@@ -627,13 +627,13 @@ pub(crate) fn complete_pending_css_command(}}-fn computed_style_command_output_plan(properties: Vec<(String, String)>) -> CommandOutputPlan {- CommandOutputPlan::result(json!({+fn computed_style_result(properties: Vec<(String, String)>) -> Value {+ json!({"computedStyle": properties.into_iter().map(|(name, value)| json!({ "name": name, "value": value })).collect::<Vec<_>>()- }))+ })}fn inline_style_result_from_attributes_resolution(diff --git a/moli-protocol/src/domains/css/native.rs b/moli-protocol/src/domains/css/native.rsindex 571ea267f..053fdaa5c 100644--- a/moli-protocol/src/domains/css/native.rs+++ b/moli-protocol/src/domains/css/native.rs@@ -67,10 +67,9 @@ pub(crate) fn try_start(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> Option<Nativstyle_sheet_id: id.clone(),},move |reply| match reply {- Ok(Reply::OptionalStyleSheetPayload(Some(payload))) => {- style_sheets::get_style_sheet_command_output_plan(&id, &frame_id, payload)- .into_native_response()- }+ Ok(Reply::OptionalStyleSheetPayload(Some(payload))) => Response::success(+ style_sheets::get_style_sheet_result(&id, &frame_id, payload),+ ),Ok(Reply::OptionalStyleSheetPayload(None)) => {Response::error(-32000, "Could not find stylesheet with given id")}@@ -192,7 +191,7 @@ fn backend_style_operation(backend_node_id: u32, query: StyleQuery) -> Operationfn project_style(reply: anyhow::Result<Reply>, query: StyleQuery) -> Response {match (query, reply) {(StyleQuery::Computed, Ok(Reply::ComputedStyleProperties(Some(properties)))) => {- computed_style_command_output_plan(properties).into_native_response()+ Response::success(computed_style_result(properties))}(StyleQuery::Computed, Ok(Reply::ComputedStyleProperties(None))) => {Response::error(-32000, "Could not find node with given id")diff --git a/moli-protocol/src/domains/css/style_sheets.rs b/moli-protocol/src/domains/css/style_sheets.rsindex bb945e96f..67fd114fa 100644--- a/moli-protocol/src/domains/css/style_sheets.rs+++ b/moli-protocol/src/domains/css/style_sheets.rs@@ -88,11 +88,11 @@ pub(super) fn complete_enable_command_output_plan(plan}-pub(super) fn get_style_sheet_command_output_plan(+pub(super) fn get_style_sheet_result(style_sheet_id: &str,frame_id: &str,payload: RendererStyleSheetPayload,-) -> CommandOutputPlan {+) -> Value {let RendererStyleSheetPayload {text,title,@@ -102,7 +102,7 @@ pub(super) fn get_style_sheet_command_output_plan(} = payload;let (end_line, end_column) = style_sheet_text_end_position(&text);- CommandOutputPlan::result(json!({+ json!({"styleSheet": {"styleSheetId": style_sheet_id,"frameId": frame_id,@@ -118,7 +118,7 @@ pub(super) fn get_style_sheet_command_output_plan("length": text.len(),"text": text,}- }))+ })}fn set_css_enabled(conn: &mut CdpConnection, cmd: &Cmd<'_>, enabled: bool) {diff --git a/moli-protocol/src/domains/dom/resolve/native.rs b/moli-protocol/src/domains/dom/resolve/native.rsindex db20a3933..4ea975b49 100644--- a/moli-protocol/src/domains/dom/resolve/native.rs+++ b/moli-protocol/src/domains/dom/resolve/native.rs@@ -392,9 +392,7 @@ fn prepare(Ok(Reply::OptionalDocumentNodeGeometry(Some(value))) => {match devtools_dom_geometry_result_from_renderer(geometry, value) {Ok(result) => {- let mut out = DomCommandOutput::default();- push_devtools_dom_geometry_result(&result, &mut out);- out.into_plan().into_native_response()+ Response::success(devtools_dom_geometry_result_value(&result))}Err(error) => Response::error(-32000, error.message),}diff --git a/moli-protocol/src/domains/dom/resolve/node_completion.rs b/moli-protocol/src/domains/dom/resolve/node_completion.rsindex 3a486cfa7..28dc680ab 100644--- a/moli-protocol/src/domains/dom/resolve/node_completion.rs+++ b/moli-protocol/src/domains/dom/resolve/node_completion.rs@@ -2456,8 +2456,12 @@ pub(super) fn push_devtools_dom_geometry_result(result: &DevToolsDomGeometryResult,out: &mut DomCommandOutput,) {+ out.push_result(devtools_dom_geometry_result_value(result));+}++pub(super) fn devtools_dom_geometry_result_value(result: &DevToolsDomGeometryResult) -> Value {if let Some(model) = result.box_model.as_ref() {- out.push_result(json!({+ json!({"model": {"content": model.content.points,"padding": model.padding.points,@@ -2466,10 +2470,10 @@ pub(super) fn push_devtools_dom_geometry_result("width": model.width,"height": model.height,}- }));+ })} else {- out.push_result(json!({+ json!({"quads": result.quads.iter().map(|quad| &quad.points).collect::<Vec<_>>()- }));+ })}}diff --git a/moli-protocol/src/domains/page/native.rs b/moli-protocol/src/domains/page/native.rsindex 2efeb5e69..98817c244 100644--- a/moli-protocol/src/domains/page/native.rs+++ b/moli-protocol/src/domains/page/native.rs@@ -52,12 +52,13 @@ fn prepare(Ok(Operation::new(Command::LayoutMetrics,|reply| match reply {- Ok(Reply::LayoutMetrics(metrics)) => CommandOutputPlan::from_devtools_result(- DevToolsCommandResult::LayoutMetrics(layout_metrics_result_from_renderer(- metrics,- )),- )- .into_native_response(),+ Ok(Reply::LayoutMetrics(metrics)) => {+ Response::success(CommandOutputPlan::devtools_result_payload(+ DevToolsCommandResult::LayoutMetrics(+ layout_metrics_result_from_renderer(metrics),+ ),+ ))+ }Err(error) => Response::error(-32000,format!("Failed to produce layout metrics: {error}"),@@ -87,15 +88,14 @@ fn prepare(|reply| match reply {Ok(Reply::CaptureScreenshot(RendererCaptureScreenshotReply::Captured(image,- ))) => CommandOutputPlan::from_devtools_result(+ ))) => Response::success(CommandOutputPlan::devtools_result_payload(DevToolsCommandResult::CaptureScreenshot(DevToolsCaptureScreenshotResult {mime_type: image.mime_type,width: image.width,height: image.height,bytes: image.bytes,}),- )- .into_native_response(),+ )),Ok(Reply::CaptureScreenshot(RendererCaptureScreenshotReply::LayoutDisabled,)) => Response::error(-32000, CAPTURE_SCREENSHOT_LAYOUT_DISABLED_MESSAGE),diff --git a/moli-protocol/src/domains/page/preload.rs b/moli-protocol/src/domains/page/preload.rsindex e03bfdf56..12ccf3387 100644--- a/moli-protocol/src/domains/page/preload.rs+++ b/moli-protocol/src/domains/page/preload.rs@@ -224,7 +224,11 @@ fn start_document_start_script_remove(}pub(super) fn add_preload_script_result_plan(identifier: String) -> CommandOutputPlan {- CommandOutputPlan::from_devtools_result(DevToolsCommandResult::AddPreloadScript(+ CommandOutputPlan::result(add_preload_script_result(identifier))+}++pub(super) fn add_preload_script_result(identifier: String) -> serde_json::Value {+ CommandOutputPlan::devtools_result_payload(DevToolsCommandResult::AddPreloadScript(DevToolsAddPreloadScriptResult {script_id: DevToolsPreloadScriptId::from(identifier),},diff --git a/moli-protocol/src/domains/page/preload/native.rs b/moli-protocol/src/domains/page/preload/native.rsindex 48d05c649..98c37e8d3 100644--- a/moli-protocol/src/domains/page/preload/native.rs+++ b/moli-protocol/src/domains/page/preload/native.rs@@ -105,7 +105,7 @@ fn add(conn: &mut CdpConnection, cmd: &Cmd<'_>) -> Result<Operation, CommandOutp},move |reply| match reply {Ok(Reply::DocumentStartScriptResult(_)) => {- add_preload_script_result_plan(identifier).into_native_response()+ Response::success(add_preload_script_result(identifier))}Err(error) => Response::error(-32000, error.to_string()),_ => unreachable!("Page preload append reply"),