eoka-sdk 0.23.0

Rust SDK for controlling eoka browser automation sessions
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
use std::process::Command as StdCommand;
use std::time::Duration;
use tokio::net::UnixStream;

use crate::launch_spec::LaunchSpec;
use crate::session;
use eoka_protocol::wire;
use eoka_protocol::{
    CaptchaDatadomeArgs, CaptchaInjectArgs, CaptchaTurnstileArgs, ClearFlagArgs, CloneFromArgs,
    ConsoleArgs, DeleteCookieArgs, DomainArgs, EmulateArgs, FakeCameraArgs, FetchArgs, FillArgs,
    FrameEvalArgs, HeadersArgs, HeldKeyArgs, IdArgs, InterceptAddArgs, KeyArgs, LoadStateArgs,
    ModeArgs, MouseButtonArgs, MouseMoveArgs, NetworkExportArgs, NetworkLogArgs,
    NetworkRecordStartArgs, NetworkShowArgs, NetworkWaitArgs, ObserveArgs, OpenArgs, PathArgs,
    PathStringArgs, Request, Response, ScreenshotArgs, ScriptArgs, SelectArgs, SetCookieArgs,
    SetStorageArgs, SnapshotArgs, StorageArgs, TabIdArgs, TabNewArgs, TargetArgs, TextArgs,
    WaitArgs, WasmFindArgs, WasmReadArgs, WasmWriteArgs,
};

macro_rules! forward_requests {
    ($(fn $name:ident($($arg:ident: $ty:ty)?) => $variant:ident;)*) => {
        $(
            pub async fn $name(&self $(, $arg: $ty)?) -> anyhow::Result<Response> {
                self.call(Request::$variant $(($arg))?).await
            }
        )*
    };
}

#[derive(Debug, Clone)]
pub struct EokaClient {
    session_name: String,
    spec: LaunchSpec,
}

impl EokaClient {
    pub fn new(session_name: impl Into<String>, spec: LaunchSpec) -> Self {
        Self {
            session_name: session_name.into(),
            spec,
        }
    }

    pub fn session_name(&self) -> &str {
        &self.session_name
    }

    pub fn launch_spec(&self) -> &LaunchSpec {
        &self.spec
    }

    pub async fn call(&self, request: Request) -> anyhow::Result<Response> {
        send_command(&self.session_name, request, self.spec.clone()).await
    }

    pub async fn agent_observe(
        &self,
        args: eoka_protocol::AgentObserveArgs,
    ) -> anyhow::Result<Response> {
        self.call(Request::AgentObserve(args)).await
    }
    pub async fn operation(&self, id: impl Into<String>) -> anyhow::Result<Response> {
        self.call(Request::OperationGet(eoka_protocol::OperationIdArgs {
            id: id.into(),
        }))
        .await
    }
    pub async fn wait_operation(
        &self,
        id: impl Into<String>,
        timeout_ms: u64,
    ) -> anyhow::Result<Response> {
        self.call(Request::OperationWait(eoka_protocol::OperationWaitArgs {
            id: id.into(),
            timeout_ms,
        }))
        .await
    }
    pub async fn cancel_operation(&self, id: impl Into<String>) -> anyhow::Result<Response> {
        self.call(Request::OperationCancel(eoka_protocol::OperationIdArgs {
            id: id.into(),
        }))
        .await
    }

    pub async fn captcha_inject(&self, args: CaptchaInjectArgs) -> anyhow::Result<Response> {
        self.call(Request::CaptchaInject(args)).await
    }

    forward_requests! {
        fn perform(request: eoka_protocol::ActionPerformArgs) => ActionPerform;
        fn agent_step(args: eoka_protocol::AgentStepArgs) => AgentStep;
        fn open(args: OpenArgs) => Open;
        fn back(args: eoka_protocol::ActionSettings) => Back;
        fn forward(args: eoka_protocol::ActionSettings) => Forward;
        fn reload() => Reload;
        fn snapshot(args: SnapshotArgs) => Snapshot;
        fn observe(args: ObserveArgs) => Observe;
        fn screenshot(args: ScreenshotArgs) => Screenshot;
        fn emulate(args: EmulateArgs) => Emulate;
        fn info() => Info;
        fn frames() => Frames;
        fn frame_eval(args: FrameEvalArgs) => FrameEval;
        fn text() => Text;
        fn find(args: TextArgs) => Find;
        fn click(args: eoka_protocol::ClickArgs) => Click;
        fn double_click(args: TargetArgs) => DblClick;
        fn fill(args: FillArgs) => Fill;
        fn select(args: SelectArgs) => Select;
        fn hover(args: TargetArgs) => Hover;
        fn key(args: KeyArgs) => Key;
        fn mouse_down(args: MouseButtonArgs) => MouseDown;
        fn mouse_move(args: MouseMoveArgs) => MouseMove;
        fn mouse_up(args: MouseButtonArgs) => MouseUp;
        fn key_down(args: HeldKeyArgs) => KeyDown;
        fn key_up(args: HeldKeyArgs) => KeyUp;
        fn release_all_inputs() => ReleaseAllInputs;
        fn scroll(args: TargetArgs) => Scroll;
        fn eval(args: ScriptArgs) => Eval;
        fn exec(args: ScriptArgs) => Exec;
        fn fetch(args: FetchArgs) => Fetch;
        fn download_start(args: eoka_protocol::DownloadStartArgs) => DownloadStart;
        fn download_list() => DownloadList;
        fn download_get(args: eoka_protocol::DownloadIdArgs) => DownloadGet;
        fn download_wait(args: eoka_protocol::DownloadWaitArgs) => DownloadWait;
        fn download_cancel(args: eoka_protocol::DownloadIdArgs) => DownloadCancel;
        fn cookies() => Cookies;
        fn set_cookie(args: SetCookieArgs) => SetCookie;
        fn delete_cookie(args: DeleteCookieArgs) => DeleteCookie;
        fn clear_cookies() => ClearCookies;
        fn storage(args: StorageArgs) => Storage;
        fn set_storage(args: SetStorageArgs) => SetStorage;
        fn dump_storage() => DumpStorage;
        fn save_state(args: PathArgs) => SaveState;
        fn load_state(args: LoadStateArgs) => LoadState;
        fn headers(args: HeadersArgs) => Headers;
        fn console(args: ConsoleArgs) => Console;
        fn errors(args: ClearFlagArgs) => Errors;
        fn tab_list() => TabList;
        fn tab_new(args: TabNewArgs) => TabNew;
        fn tab_switch(args: TabIdArgs) => TabSwitch;
        fn tab_close(args: TabIdArgs) => TabClose;
        fn tab_attach(args: TabIdArgs) => TabAttach;
        fn clone_from(args: CloneFromArgs) => CloneFrom;
        fn wait(args: WaitArgs) => Wait;
        fn spa_info() => SpaInfo;
        fn spa_navigate(args: PathStringArgs) => SpaNavigate;
        fn fake_camera(args: FakeCameraArgs) => FakeCamera;
        fn wasm_info() => WasmInfo;
        fn wasm_read(args: WasmReadArgs) => WasmRead;
        fn wasm_write(args: WasmWriteArgs) => WasmWrite;
        fn wasm_find(args: WasmFindArgs) => WasmFind;
        fn intercept_add(args: InterceptAddArgs) => InterceptAdd;
        fn intercept_list() => InterceptList;
        fn intercept_remove(args: IdArgs) => InterceptRemove;
        fn intercept_log(args: ClearFlagArgs) => InterceptLog;
        fn network_record_start(args: NetworkRecordStartArgs) => NetworkRecordStart;
        fn network_record_stop() => NetworkRecordStop;
        fn network_record_status() => NetworkRecordStatus;
        fn network_log(args: NetworkLogArgs) => NetworkLog;
        fn network_show(args: NetworkShowArgs) => NetworkShow;
        fn network_wait(args: NetworkWaitArgs) => NetworkWait;
        fn network_export(args: NetworkExportArgs) => NetworkExport;
        fn network_clear() => NetworkClear;
        fn js_mode(args: ModeArgs) => JsMode;
        fn js_allow(args: DomainArgs) => JsAllow;
        fn js_block(args: DomainArgs) => JsBlock;
        fn js_remove(args: DomainArgs) => JsRemove;
        fn js_list() => JsList;
        fn close() => Close;
        fn shutdown() => Shutdown;
        fn captcha_datadome(args: CaptchaDatadomeArgs) => CaptchaDatadome;
        fn captcha_turnstile(args: CaptchaTurnstileArgs) => CaptchaTurnstile;
    }
}
pub async fn send_command(
    session_name: &str,
    mut request: Request,
    spec: LaunchSpec,
) -> anyhow::Result<Response> {
    let mut reply_limit = None;
    if !matches!(request, Request::SessionHello) {
        if let Ok(stream) = connect_session(session_name).await {
            let hello = match exchange(stream, None, HELLO_LIMIT).await {
                Ok(response) if response.ok => response.data.unwrap_or_default(),
                Ok(_) => return Ok(non_retryable_error("protocol_mismatch", "Daemon compatibility could not be verified. Upgrade explicitly; no browser was restarted and no action was sent.")),
                Err(Lost::Disconnected) => return Ok(other_version(session_name)),
                Err(Lost::Timeout(_)) => return Ok(silent_daemon(session_name)),
            };
            reply_limit = hello["commandLimitMs"].as_u64();
            if hello["protocol"]["major"] != eoka_protocol::sidecar::PROTOCOL_VERSION.major {
                return Ok(non_retryable_error("protocol_mismatch", "Client and daemon protocols differ. Upgrade explicitly; the existing browser was retained."));
            }
            let required_mode = match &spec {
                LaunchSpec::Launch { headless: true, .. } => Some("headless"),
                LaunchSpec::Launch {
                    headless: false, ..
                } => Some("headed"),
                LaunchSpec::Connect { .. } => Some("connect"),
                LaunchSpec::Reuse => None,
            };
            if spec.has_creation_settings()
                && hello["configurationFingerprint"] != spec.configuration_fingerprint()
            {
                return Ok(non_retryable_error("session_configuration_conflict", "Creation settings differ from the existing session. Omit creation flags to reuse it or choose a new session name."));
            }
            if required_mode.is_some_and(|mode| hello["mode"] != mode) {
                return Ok(non_retryable_error("session_mode_conflict", "Existing session mode conflicts with the explicit launch mode. Omit launch flags to reuse it or choose a different session name."));
            }
        }
    }
    if let Request::Open(args) = &mut request {
        args.operation
            .operation_id
            .get_or_insert_with(|| uuid::Uuid::new_v4().to_string());
    }
    if let Request::DownloadStart(args) = &mut request {
        args.operation_id
            .get_or_insert_with(|| uuid::Uuid::new_v4().to_string());
    }
    if let Request::AgentStep(args) = &mut request {
        args.operation_id
            .get_or_insert_with(|| uuid::Uuid::new_v4().to_string());
    }
    if request.is_convenience_action()
        || matches!(
            request,
            Request::AgentStep(_)
                | Request::AgentObserve(_)
                | Request::ActionPerform(_)
                | Request::ActionCommand(_)
                | Request::OperationGet(_)
                | Request::OperationList(_)
                | Request::OperationWait(_)
                | Request::OperationCancel(_)
        )
    {
        return send_operation(session_name, request, &spec, reply_limit).await;
    }
    if matches!(
        request,
        Request::DownloadStart(_)
            | Request::DownloadList
            | Request::DownloadGet(_)
            | Request::DownloadWait(_)
            | Request::DownloadCancel(_)
    ) {
        return Ok(send_download(session_name, &request, &spec, reply_limit).await);
    }
    if let Request::CaptchaDatadome(args) = request {
        return Ok(send_datadome(session_name, args, reply_limit).await);
    }
    if matches!(request, Request::Frames | Request::FrameEval(_)) {
        return Ok(send_existing_session(session_name, &request, "frame_transport_error",
            "This daemon does not support frame operations. Upgrade the daemon explicitly; the existing browser was not restarted.", reply_limit).await);
    }
    send_command_once(session_name, request, &spec, reply_limit).await
}

#[cfg(not(test))]
const HELLO_LIMIT: Duration = Duration::from_secs(5);
#[cfg(test)]
const HELLO_LIMIT: Duration = Duration::from_millis(1000);
const STATUS_LIMIT: Duration = Duration::from_millis(1500);
#[cfg(not(test))]
const REPLY_MARGIN_MS: u64 = 15_000;
#[cfg(test)]
const REPLY_MARGIN_MS: u64 = 200;
const LAUNCH_MARGIN_MS: u64 = 30_000;
const UNKNOWN_COMMAND_LIMIT_MS: u64 = 90_000;

enum Lost {
    Timeout(Duration),
    Disconnected,
}

fn request_wire(request: &Request) -> anyhow::Result<serde_json::Value> {
    Ok(wire::request(request))
}

async fn exchange(
    stream: UnixStream,
    frame: Option<&serde_json::Value>,
    limit: Duration,
) -> Result<Response, Lost> {
    let (reader, mut writer) = stream.into_split();
    let mut reader = tokio::io::BufReader::new(reader);
    let reply = wire::call(&mut reader, &mut writer, frame);
    match tokio::time::timeout(limit, reply).await {
        Ok(Ok(response)) => Ok(response),
        Ok(Err(_)) => Err(Lost::Disconnected),
        Err(_) => Err(Lost::Timeout(limit)),
    }
}

fn configured_reply_ms() -> Option<u64> {
    std::env::var("EOKA_REPLY_TIMEOUT_MS")
        .ok()
        .and_then(|value| value.parse().ok())
        .filter(|limit| *limit > 0)
}

fn reply_budget(request: &Request, command_limit_ms: Option<u64>) -> Duration {
    let args = request.args_json();
    let number = |value: &serde_json::Value| value.as_u64();
    let own = match request {
        Request::SessionHello => return HELLO_LIMIT,
        Request::AgentStep(_) | Request::AgentObserve(_) => {
            return Duration::from_millis(
                number(&args["timeout_ms"]).unwrap_or(10_000).min(60_000) + 1_000,
            )
        }
        Request::Wait(_) => number(&args["ms"])
            .max(number(&args["timeout"]))
            .or(Some(10_000)),
        Request::NetworkWait(_) => number(&args["timeout"]).or(Some(10_000)),
        Request::OperationWait(_) | Request::DownloadWait(_) => {
            number(&args["timeout_ms"]).or(Some(30_000))
        }
        Request::CaptchaDatadome(_) => number(&args["timeout_ms"])
            .map(|limit| limit.saturating_mul(number(&args["max_attempts"]).unwrap_or(1).max(1))),
        Request::CaptchaTurnstile(_) => number(&args["timeout_ms"]),
        Request::Open(_) => Some(
            number(&args["timeout_ms"])
                .unwrap_or(30_000)
                .saturating_add(LAUNCH_MARGIN_MS),
        ),
        Request::TabAttach(_) | Request::TabNew(_) => Some(30_000 + LAUNCH_MARGIN_MS),
        Request::ActionCommand(command) => Some(
            number(&command.arguments["timeout_ms"])
                .max(number(&command.arguments["start_timeout_ms"]))
                .unwrap_or(30_000),
        ),
        Request::ActionPerform(_) => Some(number(&args["options"]["timeout_ms"]).unwrap_or(30_000)),
        Request::Click(_)
        | Request::DblClick(_)
        | Request::Fill(_)
        | Request::Select(_)
        | Request::Hover(_)
        | Request::Key(_)
        | Request::Back(_)
        | Request::Forward(_)
        | Request::HistoryGo(_)
        | Request::Reload => Some(number(&args["timeout_ms"]).unwrap_or(30_000)),
        Request::DownloadStart(_) => number(&args["start_timeout_ms"]).or(Some(30_000)),
        _ => None,
    };
    let limit = own
        .or_else(configured_reply_ms)
        .or(command_limit_ms)
        .unwrap_or(UNKNOWN_COMMAND_LIMIT_MS);
    Duration::from_millis(limit.saturating_add(REPLY_MARGIN_MS))
}

fn log_path(session_name: &str) -> String {
    session::socket_path(session_name)
        .with_extension("log")
        .to_string_lossy()
        .into_owned()
}

fn session_flag(session_name: &str) -> String {
    if session_name == "default" {
        String::new()
    } else {
        format!("--session {session_name} ")
    }
}

fn other_version(session_name: &str) -> Response {
    let flag = session_flag(session_name);
    Response::err_detail(
        eoka_protocol::ErrorDetail::new(
            "protocol_mismatch",
            format!("Session `{session_name}` closed the connection without answering the handshake; it is most likely a daemon from another eoka version. No command was sent."),
        )
        .retryable(false)
        .hint(format!("`eoka update --kill-daemons` stops daemons from other versions, or `eoka {flag}kill` stops this one; both close its browser."))
        .context(eoka_protocol::ErrorContext {
            action_status: Some(eoka_protocol::ActionStatus::NotAttempted),
            ..Default::default()
        }),
    )
}

fn silent_daemon(session_name: &str) -> Response {
    let flag = session_flag(session_name);
    Response::err_detail(
        eoka_protocol::ErrorDetail::new(
            "daemon_unresponsive",
            format!(
                "Session `{session_name}` accepted the connection but did not answer within {:.1} s; its daemon is suspended, overloaded or shutting down. No command was sent.",
                HELLO_LIMIT.as_secs_f64()
            ),
        )
        .retryable(true)
        .hint(format!(
            "Check it with `eoka {flag}status`; the daemon log is {}. If it stays silent, `eoka {flag}kill` force-stops the daemon and closes its browser, losing page state.",
            log_path(session_name)
        ))
        .context(eoka_protocol::ErrorContext {
            action_status: Some(eoka_protocol::ActionStatus::NotAttempted),
            ..Default::default()
        }),
    )
}

pub async fn session_status(session_name: &str) -> Option<serde_json::Value> {
    let stream = connect_session(session_name).await.ok()?;
    exchange(stream, None, STATUS_LIMIT)
        .await
        .ok()
        .filter(|response| response.ok)
        .and_then(|response| response.data)
}

async fn daemon_activity(session_name: &str) -> (String, String) {
    let flag = session_flag(session_name);
    let status = format!("`eoka {flag}status` shows what the session is doing");
    let last_resort = format!(
        "As a last resort `eoka {flag}kill` force-stops the daemon and closes its browser, losing page state; the daemon log is {}.",
        log_path(session_name)
    );
    let Some(hello) = session_status(session_name).await else {
        return (
            "The daemon does not answer status probes either, so its process is suspended or overloaded.".into(),
            last_resort,
        );
    };
    let activity = &hello["activity"];
    let blocker = activity["blocker"]["hint"].as_str();
    let state = match activity["busy"]["cmd"].as_str() {
        Some(command) => format!(
            "The daemon is still running `{command}` ({:.1} s so far).",
            activity["busy"]["for_ms"].as_u64().unwrap_or_default() as f64 / 1000.0
        ),
        None if activity.is_object() => {
            "The daemon is idle again, so the reply was lost after the command ended.".into()
        }
        None => {
            "The daemon still answers status probes but does not report what it is running.".into()
        }
    };
    let hint = match blocker {
        Some(blocker) => format!("{blocker} {status}."),
        None => format!("{status}. {last_resort}"),
    };
    (state, hint)
}

async fn unanswered(session_name: &str, request: &Request, lost: Lost) -> Response {
    let command = request.cmd();
    let read_only = eoka_protocol::operation_by_cmd(command).is_some_and(|spec| spec.read_only);
    let (state, hint) = daemon_activity(session_name).await;
    let (code, cause) = match lost {
        Lost::Timeout(limit) => (
            "reply_timeout",
            format!(
                "No reply to `{command}` from session `{session_name}` within {:.1} s.",
                limit.as_secs_f64()
            ),
        ),
        Lost::Disconnected => (
            "transport_error",
            format!("Session `{session_name}` closed the connection before answering `{command}`."),
        ),
    };
    let consequence = if read_only {
        "Nothing was sent again."
    } else {
        "The command may have run; it was not sent again."
    };
    let detail = eoka_protocol::ErrorDetail::new(code, format!("{cause} {state} {consequence}"))
        .retryable(read_only)
        .hint(hint);
    Response::err_detail(if read_only {
        detail
    } else {
        detail.context(eoka_protocol::ErrorContext {
            action_status: Some(eoka_protocol::ActionStatus::MayHaveExecuted),
            ..Default::default()
        })
    })
}

fn no_session(session_name: &str) -> Response {
    let flag = session_flag(session_name);
    Response::err_detail(
        eoka_protocol::ErrorDetail::new(
            "session_unavailable",
            format!("No session named `{session_name}` is running; nothing was sent."),
        )
        .retryable(false)
        .hint(format!(
            "Start it with `eoka {flag}open URL`. `eoka sessions` lists the sessions that are running."
        )),
    )
}

fn non_retryable_error(code: &str, message: &str) -> Response {
    Response::err_detail(eoka_protocol::ErrorDetail::new(code, message).retryable(false))
}

async fn send_download(
    session_name: &str,
    request: &Request,
    spec: &LaunchSpec,
    reply_limit: Option<u64>,
) -> Response {
    use eoka_protocol::{ActionStatus, ErrorContext};
    let id = match request {
        Request::DownloadStart(args) => args.operation_id.as_deref(),
        Request::DownloadWait(args) => Some(args.id.as_str()),
        Request::DownloadGet(args) | Request::DownloadCancel(args) => Some(args.id.as_str()),
        _ => None,
    };
    let disconnected = |code, message, action_status| {
        Response::err_detail(
            eoka_protocol::ErrorDetail::new(code, message)
                .retryable(false)
                .context(ErrorContext {
                    download_id: id.map(str::to_owned),
                    action_status: Some(action_status),
                    ..Default::default()
                }),
        )
    };
    let stream = match UnixStream::connect(session::socket_path(session_name)).await {
        Ok(stream) => stream,
        Err(_) if !matches!(request, Request::DownloadStart(_)) => {
            match async {
                launch_daemon(session_name, spec)?;
                wait_for_socket(session_name).await
            }
            .await
            {
                Ok(stream) => stream,
                Err(_) => {
                    return disconnected(
                        "session_unavailable",
                        "Could not open the download history service",
                        ActionStatus::NotAttempted,
                    )
                }
            }
        }
        Err(_) => return disconnected(
            "session_unavailable",
            "Existing session unavailable; open the intended page first. No daemon was launched.",
            ActionStatus::NotAttempted,
        ),
    };
    let wire = if let Request::DownloadStart(args) = request {
        Request::ActionCommand(eoka_protocol::ActionCommandArgs {
            operation_id: args.operation_id.clone().unwrap_or_default(),
            command: "download_start".into(),
            arguments: request.args_json(),
        })
    } else {
        request.clone()
    };
    let exchanged = match request_wire(&wire) {
        Ok(message) => exchange(stream, Some(&message), reply_budget(request, reply_limit))
            .await
            .ok(),
        Err(_) => None,
    };
    let mut response = match exchanged {
        Some(response) if response.error.as_deref().is_some_and(|message| {
            message.contains("unknown variant") || message.contains("unknown eoka protocol command")
        }) => disconnected(
            "unsupported_operation",
            "This daemon does not support downloads. Restart it explicitly after upgrading; no action was replayed.",
            ActionStatus::NotAttempted,
        ),
        Some(response) => response,
        None => disconnected(
            "download_transport_error",
            "Session transport failed; the action may have executed. Inspect download list before retrying. No restart or replay was attempted.",
            ActionStatus::MayHaveExecuted,
        ),
    };
    if let (Some(error), Some(id)) = (response.error_detail.as_mut(), id) {
        error
            .context
            .get_or_insert_with(Default::default)
            .download_id
            .get_or_insert_with(|| id.to_owned());
    }
    response
}

async fn send_datadome(
    session_name: &str,
    args: CaptchaDatadomeArgs,
    reply_limit: Option<u64>,
) -> Response {
    if let Err(message) = args.validate() {
        return non_retryable_error("invalid_input", message);
    }
    send_existing_session(session_name, &Request::CaptchaDatadome(args), "datadome_transport_error",
        "This daemon does not support DataDome. Upgrade the daemon explicitly; the existing browser was not restarted.", reply_limit).await
}

async fn send_existing_session(
    session_name: &str,
    request: &Request,
    transport_error: &str,
    unsupported_message: &str,
    reply_limit: Option<u64>,
) -> Response {
    let Ok(stream) = connect_session(session_name).await else {
        return non_retryable_error(
            "session_unavailable",
            "Existing session unavailable; open the intended page first. No browser was launched.",
        );
    };
    let exchanged = match request_wire(request) {
        Ok(wire) => exchange(stream, Some(&wire), reply_budget(request, reply_limit))
            .await
            .ok(),
        Err(_) => None,
    };
    match exchanged {
        Some(response) if response.error.as_deref().is_some_and(|error| error.contains(request.cmd()) && (error.contains("unknown variant") || error.contains("unknown eoka protocol command"))) =>
            non_retryable_error("unsupported_operation", unsupported_message),
        Some(response) => response,
        None => non_retryable_error(transport_error, "Session transport failed; the request may have executed. Inspect the existing page before retrying. No replay was attempted."),
    }
}

async fn send_command_once(
    session_name: &str,
    request: Request,
    spec: &LaunchSpec,
    reply_limit: Option<u64>,
) -> anyhow::Result<Response> {
    let stream = match connect_session(session_name).await {
        Ok(s) => s,
        Err(_)
            if matches!(request, Request::Open(_))
                || (matches!(request, Request::TabAttach(_))
                    && matches!(spec, LaunchSpec::Connect { .. })) =>
        {
            launch_daemon(session_name, spec)?;
            wait_for_socket(session_name).await?
        }
        Err(_) => return Ok(no_session(session_name)),
    };

    let wire = request_wire(&request)?;
    Ok(
        match exchange(stream, Some(&wire), reply_budget(&request, reply_limit)).await {
            Ok(response) => response,
            Err(lost) => unanswered(session_name, &request, lost).await,
        },
    )
}

async fn connect_session(session_name: &str) -> std::io::Result<UnixStream> {
    UnixStream::connect(session::trusted_socket_path(session_name)?).await
}

async fn wait_for_socket(session_name: &str) -> anyhow::Result<UnixStream> {
    let sock = session::socket_path(session_name);
    let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
    loop {
        if tokio::time::Instant::now() > deadline {
            anyhow::bail!(
                "Daemon failed to start (socket {} not found after 5s)",
                sock.display()
            );
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
        if let Ok(s) = connect_session(session_name).await {
            return Ok(s);
        }
    }
}
static DAEMON_PROGRAM: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new();

pub fn serve_daemons_from(program: std::path::PathBuf) {
    let _ = DAEMON_PROGRAM.set(program);
}

fn daemon_program(
    host: Option<&std::path::PathBuf>,
    configured: Option<std::ffi::OsString>,
) -> std::path::PathBuf {
    host.cloned()
        .or_else(|| {
            configured
                .filter(|path| !path.is_empty())
                .map(std::path::PathBuf::from)
        })
        .unwrap_or_else(|| "eoka".into())
}

fn launch_daemon(session_name: &str, spec: &LaunchSpec) -> anyhow::Result<()> {
    session::ensure_runtime_dir()?;

    let program = daemon_program(DAEMON_PROGRAM.get(), std::env::var_os("EOKA_BIN"));
    let mut cmd = StdCommand::new(&program);
    cmd.arg("--daemon").arg("--session").arg(session_name);
    let mut proxy_for_stdin = None;

    match spec {
        LaunchSpec::Reuse => {}
        LaunchSpec::Launch {
            headless,
            from_profile,
            clone_state_from,
            no_stealth,
            proxy,
            no_js,
            js_allow,
            js_block,
            persist,
            geo_align,
            auto_solve_cloudflare,
            sandbox,
        } => {
            if !*headless {
                cmd.arg("--headed");
            }
            if let Some(p) = from_profile {
                cmd.arg("--from-profile").arg(p);
            }
            if let Some(s) = clone_state_from {
                cmd.arg("--clone-state-from").arg(s);
            }
            if *no_stealth {
                cmd.arg("--no-stealth");
            }
            if *persist {
                cmd.arg("--persist");
            }
            if !*geo_align {
                cmd.arg("--no-geo-align");
            }
            if *auto_solve_cloudflare {
                cmd.arg("--auto-solve-cloudflare");
            }
            if !*sandbox {
                cmd.arg("--no-sandbox");
            }
            if let Some(p) = proxy {
                cmd.arg("--proxy-stdin");
                proxy_for_stdin = Some(p.clone());
            }
            if *no_js {
                cmd.arg("--no-js");
            }
            for domain in js_allow {
                cmd.arg("--js-allow").arg(domain);
            }
            for domain in js_block {
                cmd.arg("--js-block").arg(domain);
            }
        }
        LaunchSpec::Connect { ws_url } => {
            cmd.arg("--cdp").arg(ws_url);
        }
    }

    let (log_file, log_path) = session::open_daemon_log(session_name)?;

    cmd.stdin(if proxy_for_stdin.is_some() {
        std::process::Stdio::piped()
    } else {
        std::process::Stdio::null()
    })
    .stdout(std::process::Stdio::null())
    .stderr(log_file);

    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        cmd.process_group(0);
    }

    let mut child = cmd.spawn().map_err(|error| {
        anyhow::anyhow!(
            "Could not start the Eoka daemon with `{}`: {error}. Install the eoka CLI or set EOKA_BIN to its path.",
            program.display()
        )
    })?;
    if let Some(proxy) = proxy_for_stdin {
        use std::io::Write;
        let mut stdin = child
            .stdin
            .take()
            .ok_or_else(|| anyhow::anyhow!("Daemon stdin was not captured"))?;
        stdin.write_all(format!("{proxy}\n").as_bytes())?;
    }
    eprintln!(
        "[eoka] daemon starting (session={}, log={})",
        session_name,
        log_path.display()
    );
    Ok(())
}
pub fn is_daemon_running(session_name: &str) -> bool {
    session::trusted_socket_path(session_name)
        .is_ok_and(|sock| std::os::unix::net::UnixStream::connect(sock).is_ok())
}
pub fn kill_daemon(session_name: &str) -> anyhow::Result<bool> {
    let sock = session::trusted_socket_path(session_name)?;
    let daemon_is_listening = std::os::unix::net::UnixStream::connect(&sock).is_ok();
    let pid_path = session::pid_path(session_name);
    let original_pid = std::fs::read_to_string(&pid_path).ok();
    let killed = if let Some(pid_str) = original_pid.as_ref().filter(|_| daemon_is_listening) {
        if let Ok(pid) = pid_str.trim().parse::<u32>() {
            StdCommand::new("kill")
                .arg(pid.to_string())
                .output()
                .map(|o| o.status.success())
                .unwrap_or(false)
        } else {
            false
        }
    } else {
        false
    };
    if killed {
        let deadline = std::time::Instant::now() + Duration::from_secs(15);
        while std::fs::read_to_string(&pid_path).ok() == original_pid {
            if let Some(pid) = original_pid.as_deref() {
                let alive = StdCommand::new("kill")
                    .args(["-0", pid.trim()])
                    .output()?
                    .status
                    .success();
                if !alive {
                    break;
                }
            }
            if std::time::Instant::now() >= deadline {
                anyhow::bail!("Daemon is still shutting down; its socket was retained");
            }
            std::thread::sleep(Duration::from_millis(25));
        }
        if let Some(pid) = original_pid.as_deref() {
            let exited = std::time::Instant::now() + Duration::from_secs(5);
            while std::time::Instant::now() < exited
                && StdCommand::new("kill")
                    .args(["-0", pid.trim()])
                    .output()
                    .is_ok_and(|probe| probe.status.success())
            {
                std::thread::sleep(Duration::from_millis(10));
            }
        }
    }
    if std::fs::read_to_string(&pid_path).ok() == original_pid {
        let _ = std::fs::remove_file(&sock);
        let _ = std::fs::remove_file(&pid_path);
    }
    Ok(killed)
}

async fn send_operation(
    session_name: &str,
    request: Request,
    spec: &LaunchSpec,
    reply_limit: Option<u64>,
) -> anyhow::Result<Response> {
    let args = request.args_json();
    let id = args["operation_id"]
        .as_str()
        .map(str::to_owned)
        .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
    let wire = if request.is_convenience_action() {
        wire::request_frame(
            "action_command",
            serde_json::json!({"operation_id":id,"command":request.cmd(),"arguments":args}),
        )
    } else {
        let mut params = args.clone();
        let queries_an_operation = request.cmd().starts_with("operation_");
        if !matches!(request, Request::AgentObserve(_))
            && !queries_an_operation
            && params.is_object()
        {
            params["operation_id"] = serde_json::json!(id);
        }
        wire::request_frame(request.cmd(), params)
    };
    let stream = match connect_session(session_name).await {
        Ok(stream) => stream,
        Err(_) if request.cmd().starts_with("operation_") => {
            launch_daemon(session_name, spec)?;
            wait_for_socket(session_name).await?
        }
        Err(_) if matches!(request, Request::AgentObserve(_)) => {
            return Ok(no_session(session_name))
        }
        Err(_) => {
            let mut response = no_session(session_name);
            response.data = Some(serde_json::json!({"operation_id":id,"status":"not_dispatched"}));
            return Ok(response);
        }
    };
    let lost = match exchange(stream, Some(&wire), reply_budget(&request, reply_limit)).await {
        Ok(response) => return Ok(response),
        Err(lost) => lost,
    };
    let (state, hint) = daemon_activity(session_name).await;
    let cause = match lost {
        Lost::Timeout(limit) => format!("No reply within {:.1} s", limit.as_secs_f64()),
        Lost::Disconnected => "Connection lost".to_owned(),
    };
    if matches!(request, Request::AgentObserve(_)) {
        return Ok(Response::err_detail(
            eoka_protocol::ErrorDetail::new(
                "observation_transport_error",
                format!(
                    "{cause}: the observation is unavailable. {state} No action was requested."
                ),
            )
            .retryable(false)
            .hint(hint),
        ));
    }
    let mut response = Response::err_detail(eoka_protocol::ErrorDetail::new("operation_transport_error", format!("{cause}; inspect operation {id}. Its outcome is unknown. {state} No action was replayed.")).retryable(false).hint(hint).context(eoka_protocol::ErrorContext { operation_id: Some(id.clone()), phase: Some("transport".into()), action_status: Some(eoka_protocol::ActionStatus::MayHaveExecuted), ..Default::default() }));
    response.data = Some(serde_json::json!({"operation_id":id,"status":"outcome_unknown"}));
    Ok(response)
}

#[cfg(test)]
mod tests;