返回 CodeWhale
daemon_client.rs
根目录 / crates / app-server / src / daemon_client.rs
1 //! Authenticated local control attachment to the already held Runtime owner.
2 //! The private receipt routes; the connected kernel process authenticates it.
3 //! This forwards the existing bounded dispatcher protocol, never HTTP bearers.
4
5 use anyhow::Result;
6 use std::path::PathBuf;
7
8 #[cfg(any(unix, windows))]
9 mod platform {
10 use super::*;
11 use crate::daemon_socket::AuthorizedPeer;
12 #[cfg(windows)]
13 use crate::daemon_socket::default_socket_path;
14 use crate::stdio::{
15 BoundedLines, ParsedStdioLine, is_frame_refusal, parse_stdio_line, serialize_control_frame,
16 write_control_line, write_stdio_line,
17 };
18 use anyhow::{Context as _, bail};
19 use codewhale_app_server_protocol::lifecycle::InitializeResponse;
20 use codewhale_app_server_protocol::rpc::{
21 RequestId, RpcCall, RpcErrorResponse, RpcNotification, RpcResponse,
22 };
23 use codewhale_config::private_directory::PrivateDirectory;
24 #[cfg(unix)]
25 use codewhale_paths::daemon_socket::default_socket_path;
26 use codewhale_protocol::RuntimeOwnerReceipt;
27 use codewhale_runtime::runtime_control::owner_work;
28 use serde_json::{Value, json};
29 use std::sync::Arc;
30 use std::time::Duration;
31 use tokio::io::BufReader;
32 #[cfg(unix)]
33 use tokio::net::UnixStream;
34 #[cfg(unix)]
35 type Connection = UnixStream;
36 #[cfg(windows)]
37 type Connection = tokio::net::windows::named_pipe::NamedPipeClient;
38
39 type OwnerTransport = crate::websocket::LocalWebSocket<
40 tokio::io::ReadHalf<Connection>,
41 tokio::io::WriteHalf<Connection>,
42 >;
43
44 fn resolved_store_form(path: PathBuf) -> Option<PathBuf> {
45 let checked = codewhale_engine::runtime_threads::checked_runtime_store_root(path).ok()?;
46 let mut tail = Vec::new();
47 let mut probe = checked.as_path();
48 loop {
49 match probe.canonicalize() {
50 Ok(real) => {
51 return Some(tail.iter().rev().fold(real, |acc, part| acc.join(part)));
52 }
53 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
54 tail.push(probe.file_name()?.to_owned());
55 probe = probe.parent()?;
56 }
57 Err(_) => return None,
58 }
59 }
60 }
61
62 fn resolved_store_form_of(path: &std::path::Path) -> PathBuf {
63 resolved_store_form(path.to_path_buf()).unwrap_or_else(|| path.to_path_buf())
64 }
65
66 fn same_store_path(left: &std::path::Path, right: &std::path::Path) -> bool {
67 left == right
68 || (cfg!(any(target_os = "macos", windows))
69 && left.to_string_lossy().to_lowercase() == right.to_string_lossy().to_lowercase())
70 }
71
72 fn same_socket_selection(left: &std::path::Path, right: &std::path::Path) -> bool {
73 if left == right {
74 return true;
75 }
76 #[cfg(unix)]
77 {
78 if left.file_name().is_none() || left.file_name() != right.file_name() {
79 return false;
80 }
81 match (
82 left.parent()
83 .map(codewhale_paths::resolve_root_owned_ancestors),
84 right
85 .parent()
86 .map(codewhale_paths::resolve_root_owned_ancestors),
87 ) {
88 (Some(left), Some(right)) => left == right,
89 _ => false,
90 }
91 }
92 #[cfg(windows)]
93 {
94 false
95 }
96 }
97
98 pub struct OwnerClient {
99 read: BoundedLines<BufReader<tokio::io::ReadHalf<OwnerTransport>>>,
100 write: tokio::io::WriteHalf<OwnerTransport>,
101 peer: Arc<AuthorizedPeer>,
102 receipt: RuntimeOwnerReceipt,
103 routing: Option<crate::RuntimeOwnerRouting>,
104 frontend: crate::daemon_socket::AttachFrontend,
105 output_failed: bool,
106 native_initialized: bool,
107 pending_initialize: Option<RequestId>,
108 native: Option<crate::native_runtime::NativeSelection>,
109 publication: Arc<OwnerPublication>,
110 #[cfg(all(test, unix))]
111 receive_test_hook:
112 Option<tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>>,
113 }
114
115 /// Host startup is the only caller allowed to acquire the Runtime lease.
116 /// Unavailable is pre-write transport evidence, never ownership or death.
117 pub enum HostOwnerProbe {
118 Absent,
119 Attached(Box<OwnerClient>),
120 Unavailable(Arc<UnavailablePublication>),
121 }
122
123 #[derive(Debug, thiserror::Error)]
124 #[error("selected owner publication changed before attach; re-observe")]
125 pub struct PublicationChangedBeforeAttach;
126
127 fn owner_receipt_error(error: anyhow::Error) -> anyhow::Error {
128 #[cfg(unix)]
129 if error.is::<codewhale_config::private_directory::UnlinkedPrivateFile>() {
130 return PublicationChangedBeforeAttach.into();
131 }
132 error
133 }
134
135 pub(crate) struct OwnerPublication {
136 pub(crate) parent: Arc<PrivateDirectory>,
137 pub(crate) receipt_name: String,
138 #[cfg(unix)]
139 pub(crate) socket_path: PathBuf,
140 pub(crate) bytes: Vec<u8>,
141 pub(crate) receipt: RuntimeOwnerReceipt,
142 pub(crate) file: std::fs::File,
143 #[cfg(unix)]
144 pub(crate) socket_identity:
145 Option<codewhale_config::private_directory::PrivateSocketIdentity>,
146 }
147 impl OwnerPublication {
148 pub(crate) fn receipt_is_current(&self) -> Result<bool> {
149 if !self.parent.is_at_selected_path()? {
150 return Ok(false);
151 }
152 let current = match self
153 .parent
154 .read_private_receipt(&self.receipt_name, 16384)
155 .map_err(owner_receipt_error)
156 {
157 Err(error) if error.is::<PublicationChangedBeforeAttach>() => return Ok(false),
158 result => result?,
159 };
160 let Some((bytes, file)) = current else {
161 return Ok(false);
162 };
163 Ok(bytes == self.bytes && PrivateDirectory::same_file_identity(&self.file, &file)?)
164 }
165 pub(crate) fn is_current(&self) -> Result<bool> {
166 if !self.receipt_is_current()? {
167 return Ok(false);
168 }
169 #[cfg(unix)]
170 {
171 let name = self
172 .socket_path
173 .file_name()
174 .and_then(|name| name.to_str())
175 .context("invalid owner endpoint basename")?;
176 if self.parent.socket_identity(name)? != self.socket_identity {
177 return Ok(false);
178 }
179 }
180 Ok(true)
181 }
182 }
183
184 /// Opaque retained publication. No public constructor or path-based cleanup.
185 pub struct UnavailablePublication {
186 pub(crate) publication: Arc<OwnerPublication>,
187 cause: std::io::Error,
188 }
189 impl UnavailablePublication {
190 pub fn receipt(&self) -> &RuntimeOwnerReceipt {
191 &self.publication.receipt
192 }
193 fn strict_error(&self) -> anyhow::Error {
194 let cause = match self.cause.raw_os_error() {
195 Some(code) => std::io::Error::from_raw_os_error(code),
196 None => std::io::Error::new(self.cause.kind(), self.cause.to_string()),
197 };
198 anyhow::Error::new(cause)
199 .context("selected owner publication unavailable; canonical host recovery required")
200 }
201 fn require_dead_process(&self) -> Result<()> {
202 let receipt = self.receipt();
203 #[cfg(unix)]
204 let principal = PrivateDirectory::current_user_id().to_string();
205 #[cfg(windows)]
206 let principal =
207 codewhale_config::windows_identity::CurrentWindowsUser::open()?.sid_string()?;
208 anyhow::ensure!(
209 receipt.principal == principal && !receipt.process_start.is_empty(),
210 "selected owner process identity is invalid"
211 );
212 #[cfg(unix)]
213 let (running, start) = {
214 use codewhale_config::private_directory::{UnixProcessStatus, unix_process_status};
215 #[cfg(target_os = "linux")]
216 {
217 use codewhale_config::private_directory::linux_process_start_predates_boot;
218 if linux_process_start_predates_boot(&receipt.process_start)? {
219 return Ok(());
220 }
221 }
222 match unix_process_status(receipt.pid)? {
223 UnixProcessStatus::Absent => return Ok(()),
224 UnixProcessStatus::Present { start } => (true, start),
225 }
226 };
227 #[cfg(windows)]
228 let (running, start) = {
229 use codewhale_config::windows_identity::{
230 WindowsProcessStatus, windows_process_status,
231 };
232 match windows_process_status(receipt.pid)? {
233 WindowsProcessStatus::Absent => return Ok(()),
234 WindowsProcessStatus::Running { start } => (true, start),
235 WindowsProcessStatus::Exited { start } => (false, start),
236 }
237 };
238 if start != receipt.process_start {
239 bail!("selected owner PID was reused; refusing recovery")
240 }
241 if running {
242 bail!("selected owner process is still present; refusing recovery")
243 }
244 Ok(())
245 }
246 pub(crate) fn require_same_selection(
247 &self,
248 owner: &RuntimeOwnerReceipt,
249 endpoint: &std::path::Path,
250 ) -> Result<()> {
251 let old = self.receipt();
252 anyhow::ensure!(
253 old.version == owner.version
254 && old.data_dir == owner.data_dir
255 && old.execution_scope == owner.execution_scope
256 && same_socket_selection(&old.socket_path, endpoint)
257 && old.config_path == owner.config_path
258 && old.principal == owner.principal,
259 "captured stale owner belongs to another selected store/config/principal"
260 );
261 Ok(())
262 }
263 fn discard_if_store_gone_blocking(&self, selected_store: PathBuf) -> Result<bool> {
264 let gone = resolved_store_form(selected_store).is_some_and(|selected| {
265 same_store_path(&selected, &resolved_store_form_of(&self.receipt().data_dir))
266 && matches!(
267 selected.symlink_metadata(),
268 Err(error) if error.kind() == std::io::ErrorKind::NotFound
269 )
270 });
271 if !gone || !matches!(self.revalidate_receipt(), Ok(true)) {
272 return Ok(false);
273 }
274 anyhow::ensure!(
275 self.publication.parent.retire_private_receipt(
276 &self.publication.receipt_name,
277 &self.publication.file
278 )?,
279 PublicationChangedBeforeAttach
280 );
281 Ok(true)
282 }
283 async fn discard_if_store_gone(
284 self: &Arc<Self>,
285 selected_store: &std::path::Path,
286 ) -> Result<bool> {
287 let held = self.clone();
288 let selected_store = selected_store.to_path_buf();
289 owner_work(move || held.discard_if_store_gone_blocking(selected_store)).await
290 }
291 /// Caller retains the real Runtime lease; this checks evidence only.
292 pub(crate) fn revalidate_receipt(&self) -> Result<bool> {
293 if !self.publication.receipt_is_current()? {
294 return Ok(false);
295 }
296 self.require_dead_process()?;
297 Ok(true)
298 }
299 pub(crate) fn revalidate_all(&self) -> Result<bool> {
300 if !self.publication.is_current()? {
301 return Ok(false);
302 }
303 self.require_dead_process()?;
304 Ok(true)
305 }
306 pub async fn revalidate(self: &Arc<Self>) -> Result<bool> {
307 let held = self.clone();
308 owner_work(move || held.revalidate_all()).await
309 }
310 }
311
312 async fn observe_publication(
313 config_path: Option<PathBuf>,
314 selected: Option<PathBuf>,
315 ) -> Result<Option<Arc<OwnerPublication>>> {
316 let socket_path = owner_work(move || match selected {
317 Some(path) => Ok(path),
318 None => default_socket_path().map_err(Into::into),
319 })
320 .await?;
321 #[cfg(unix)]
322 let directory = socket_path
323 .parent()
324 .context("owner endpoint has no private parent")?
325 .to_path_buf();
326 #[cfg(windows)]
327 let directory = owner_work(crate::daemon_windows::owner_directory).await?;
328 #[cfg(unix)]
329 let name = format!(
330 "{}.owner.json",
331 socket_path
332 .file_name()
333 .and_then(|name| name.to_str())
334 .context("invalid owner endpoint basename")?
335 );
336 #[cfg(windows)]
337 let name = "daemon.owner.json".to_string();
338 owner_work(move || {
339 // This runs before the engine has anywhere to log, so a refusal
340 // here is the first thing a user sees and the last thing they can
341 // diagnose. A mount that reports its own ownership (HarmonyOS
342 // hmdfs) makes the strict proof impossible for every object on it,
343 // so discovering an owner — not authenticating one — takes the
344 // measured exception. The receipt is still read through the
345 // retained handle, must be a single-link file, and the socket
346 // identity is still compared.
347 let parent = match PrivateDirectory::inspect_trusting_mount(&directory) {
348 Ok(parent) => Arc::new(parent),
349 Err(error)
350 if error
351 .downcast_ref::<std::io::Error>()
352 .is_some_and(|error| error.kind() == std::io::ErrorKind::NotFound) =>
353 {
354 return Ok(None);
355 }
356 Err(error) => return Err(error),
357 };
358 let Some((bytes, file)) = parent
359 .read_private_receipt(&name, 16384)
360 .map_err(owner_receipt_error)?
361 else {
362 return Ok(None);
363 };
364 let receipt: RuntimeOwnerReceipt = serde_json::from_slice(&bytes)?;
365 anyhow::ensure!(
366 receipt.version == 1
367 && receipt.pid > 0
368 && same_socket_selection(&receipt.socket_path, &socket_path)
369 && !receipt.lease_generation.is_empty(),
370 "selected owner receipt is invalid"
371 );
372 anyhow::ensure!(
373 receipt.config_path == config_path,
374 "selected owner config does not match; refusing another store"
375 );
376 #[cfg(unix)]
377 let socket_identity = parent.socket_identity(
378 socket_path
379 .file_name()
380 .and_then(|name| name.to_str())
381 .context("invalid owner endpoint basename")?,
382 )?;
383 Ok(Some(Arc::new(OwnerPublication {
384 parent,
385 receipt_name: name,
386 bytes,
387 receipt,
388 file,
389 #[cfg(unix)]
390 socket_path,
391 #[cfg(unix)]
392 socket_identity,
393 })))
394 })
395 .await
396 }
397
398 /// Read-only absence recheck after the actual Runtime lease was acquired.
399 pub async fn publication_is_absent(
400 config_path: Option<PathBuf>,
401 selected: Option<PathBuf>,
402 ) -> Result<bool> {
403 Ok(observe_publication(config_path, selected).await?.is_none())
404 }
405
406 pub async fn probe_owner_for_host_startup(
407 config_path: Option<PathBuf>,
408 selected: Option<PathBuf>,
409 selected_store: &std::path::Path,
410 ) -> Result<HostOwnerProbe> {
411 match probe_frontend(
412 config_path,
413 selected,
414 crate::daemon_socket::AttachFrontend::Control,
415 None,
416 None,
417 None,
418 None,
419 None,
420 )
421 .await?
422 {
423 HostOwnerProbe::Unavailable(publication)
424 if publication.discard_if_store_gone(selected_store).await? =>
425 {
426 Ok(HostOwnerProbe::Absent)
427 }
428 probe => Ok(probe),
429 }
430 }
431
432 pub async fn connect(
433 config_path: Option<PathBuf>,
434 selected: Option<PathBuf>,
435 ) -> Result<OwnerClient> {
436 connect_if_published(config_path, selected).await?.context(
437 "the selected Runtime has no authenticated live owner; start its canonical host",
438 )
439 }
440
441 pub async fn connect_if_published(
442 config_path: Option<PathBuf>,
443 selected: Option<PathBuf>,
444 ) -> Result<Option<OwnerClient>> {
445 connect_frontend(
446 config_path,
447 selected,
448 crate::daemon_socket::AttachFrontend::Control,
449 None,
450 None,
451 None,
452 None,
453 None,
454 )
455 .await
456 }
457 pub async fn connect_native(
458 receipt: RuntimeOwnerReceipt,
459 workspace: PathBuf,
460 ) -> Result<OwnerClient> {
461 let native = crate::native_runtime::NativeSelection {
462 capability: codewhale_app_server_protocol::runtime::NATIVE_RUNTIME_CAPABILITY
463 .to_owned(),
464 workspace,
465 };
466 native.validate()?;
467 connect_frontend(
468 receipt.config_path.clone(),
469 Some(receipt.socket_path.clone()),
470 crate::daemon_socket::AttachFrontend::Control,
471 None,
472 Some(receipt),
473 None,
474 None,
475 Some(native),
476 )
477 .await?
478 .context("selected owner is absent")
479 }
480
481 pub async fn connect_acp_if_published(
482 config_path: Option<PathBuf>,
483 selected: Option<PathBuf>,
484 ) -> Result<Option<OwnerClient>> {
485 connect_frontend(
486 config_path,
487 selected,
488 crate::daemon_socket::AttachFrontend::Acp,
489 None,
490 None,
491 None,
492 None,
493 None,
494 )
495 .await
496 }
497 pub async fn connect_listener_if_published(
498 config_path: Option<PathBuf>,
499 selected: Option<PathBuf>,
500 listener: crate::RuntimeListenerSelection,
501 expected_owner: RuntimeOwnerReceipt,
502 ) -> Result<Option<OwnerClient>> {
503 listener.validate_bounds()?;
504 connect_frontend(
505 config_path,
506 selected,
507 crate::daemon_socket::AttachFrontend::Listener,
508 Some(listener),
509 Some(expected_owner),
510 None,
511 None,
512 None,
513 )
514 .await
515 }
516 pub async fn connect_scoped_control_if_published(
517 config_path: Option<PathBuf>,
518 selected: Option<PathBuf>,
519 scope: crate::RuntimeFrontendScope,
520 owner: RuntimeOwnerReceipt,
521 ) -> Result<Option<OwnerClient>> {
522 scope.validate_bounds()?;
523 connect_frontend(
524 config_path,
525 selected,
526 crate::daemon_socket::AttachFrontend::Control,
527 None,
528 Some(owner),
529 Some(scope),
530 None,
531 None,
532 )
533 .await
534 }
535 pub async fn connect_selected_acp_if_published(
536 config_path: Option<PathBuf>,
537 selected: Option<PathBuf>,
538 scope: crate::RuntimeFrontendScope,
539 model: String,
540 owner: RuntimeOwnerReceipt,
541 ) -> Result<Option<OwnerClient>> {
542 scope.validate_bounds()?;
543 anyhow::ensure!(
544 !model.trim().is_empty() && model.len() <= 1024,
545 "invalid selected ACP model"
546 );
547 connect_frontend(
548 config_path,
549 selected,
550 crate::daemon_socket::AttachFrontend::Acp,
551 None,
552 Some(owner),
553 Some(scope),
554 Some(model),
555 None,
556 )
557 .await
558 }
559 async fn connect_frontend(
560 config_path: Option<PathBuf>,
561 selected: Option<PathBuf>,
562 frontend: crate::daemon_socket::AttachFrontend,
563 listener: Option<crate::RuntimeListenerSelection>,
564 expected_owner: Option<RuntimeOwnerReceipt>,
565 scope: Option<crate::RuntimeFrontendScope>,
566 acp_model: Option<String>,
567 native: Option<crate::native_runtime::NativeSelection>,
568 ) -> Result<Option<OwnerClient>> {
569 match probe_frontend(
570 config_path,
571 selected,
572 frontend,
573 listener,
574 expected_owner,
575 scope,
576 acp_model,
577 native,
578 )
579 .await?
580 {
581 HostOwnerProbe::Absent => Ok(None),
582 HostOwnerProbe::Attached(client) => Ok(Some(*client)),
583 HostOwnerProbe::Unavailable(publication) => Err(publication.strict_error()),
584 }
585 }
586
587 async fn probe_frontend(
588 config_path: Option<PathBuf>,
589 selected: Option<PathBuf>,
590 frontend: crate::daemon_socket::AttachFrontend,
591 listener: Option<crate::RuntimeListenerSelection>,
592 expected_owner: Option<RuntimeOwnerReceipt>,
593 scope: Option<crate::RuntimeFrontendScope>,
594 acp_model: Option<String>,
595 native: Option<crate::native_runtime::NativeSelection>,
596 ) -> Result<HostOwnerProbe> {
597 let Some(publication) = observe_publication(config_path, selected).await? else {
598 return Ok(HostOwnerProbe::Absent);
599 };
600 #[cfg(unix)]
601 let socket_path = publication.socket_path.clone();
602 let receipt = publication.receipt.clone();
603 #[cfg(unix)]
604 let (stream, peer) = {
605 let stream = match tokio::time::timeout(
606 Duration::from_secs(5),
607 UnixStream::connect(&socket_path),
608 )
609 .await
610 .context("owner connect deadline expired")?
611 {
612 Ok(stream) => stream,
613 Err(cause) => {
614 let held = publication.clone();
615 anyhow::ensure!(
616 owner_work(move || held.is_current()).await?,
617 PublicationChangedBeforeAttach
618 );
619 if cause.kind() == std::io::ErrorKind::ConnectionRefused
620 || (cause.kind() == std::io::ErrorKind::NotFound
621 && publication.socket_identity.is_none())
622 {
623 return Ok(HostOwnerProbe::Unavailable(Arc::new(
624 UnavailablePublication { publication, cause },
625 )));
626 }
627 return Err(cause.into());
628 }
629 };
630 let credential = stream
631 .peer_cred()
632 .context("owner peer credentials unavailable")?;
633 let pid = credential
634 .pid()
635 .and_then(|pid| u32::try_from(pid).ok())
636 .context("owner peer PID unavailable")?;
637 if credential.uid() != PrivateDirectory::current_user_id()
638 || receipt.principal != credential.uid().to_string()
639 || pid != receipt.pid
640 {
641 let held = publication.clone();
642 anyhow::ensure!(
643 owner_work(move || held.is_current()).await?,
644 PublicationChangedBeforeAttach
645 );
646 bail!("connected process is not the selected Runtime owner");
647 }
648 (
649 stream,
650 Arc::new(AuthorizedPeer {
651 pid,
652 start: receipt.process_start.clone(),
653 }),
654 )
655 };
656 #[cfg(windows)]
657 let (stream, peer) = {
658 let (stream, process) = match crate::daemon_windows::connect_owner(&receipt).await {
659 Ok(connected) => connected,
660 Err(error) => {
661 let held = publication.clone();
662 anyhow::ensure!(
663 owner_work(move || held.is_current()).await?,
664 PublicationChangedBeforeAttach
665 );
666 let missing = error
667 .downcast_ref::<std::io::Error>()
668 .filter(|cause| cause.kind() == std::io::ErrorKind::NotFound)
669 .map(|cause| match cause.raw_os_error() {
670 Some(code) => std::io::Error::from_raw_os_error(code),
671 None => std::io::Error::from(cause.kind()),
672 });
673 if let Some(cause) = missing {
674 return Ok(HostOwnerProbe::Unavailable(Arc::new(
675 UnavailablePublication { publication, cause },
676 )));
677 }
678 return Err(error);
679 }
680 };
681 let peer = AuthorizedPeer {
682 pid: process.pid(),
683 start: process.start().to_string(),
684 process,
685 };
686 (stream, Arc::new(peer))
687 };
688 let held_publication = publication.clone();
689 let check = peer.clone();
690 owner_work(move || {
691 check.check()?;
692 anyhow::ensure!(
693 held_publication.is_current()?,
694 PublicationChangedBeforeAttach
695 );
696 Ok(())
697 })
698 .await?;
699 anyhow::ensure!(
700 expected_owner
701 .as_ref()
702 .is_none_or(|expected| expected == &receipt),
703 "selected owner changed before frontend admission"
704 );
705 let (read, write) = tokio::io::split(stream);
706 let transport = crate::websocket::connect(read, write).await?;
707 let (read, mut write) = tokio::io::split(transport);
708 let mut replies = BoundedLines::new(BufReader::new(read));
709 let attach_id = uuid::Uuid::new_v4().to_string();
710 let desktop_browser_owner = listener
711 .as_ref()
712 .and_then(|selection| selection.desktop_browser_owner.clone());
713 let mut attach_params = json!({
714 "client":{"name":"codewhale-stdio","version":env!("CARGO_PKG_VERSION"),"pid":std::process::id()},
715 "mode":"attach","frontend":frontend,"native_runtime":native,"listener":listener,"scope":scope,"acp_model":acp_model,"expect_daemon_version":env!("CARGO_PKG_VERSION"),"expect_owner":receipt
716 });
717 if let Some(owner) = desktop_browser_owner {
718 attach_params["desktop_browser_owner"] = json!(owner);
719 }
720 let attach = json!(RpcCall {
721 id: Some(RequestId::String(attach_id.clone())),
722 method: "daemon/attach".into(),
723 params: attach_params,
724 trace: None
725 });
726 tokio::time::timeout(
727 Duration::from_secs(5),
728 write_stdio_line(&mut write, &attach),
729 )
730 .await
731 .context("owner attach write deadline expired; outcome uncertain")??;
732 let line = tokio::time::timeout(Duration::from_secs(5), replies.next_line())
733 .await
734 .context("owner attach response deadline expired")??
735 .context("owner closed before attach")?;
736 anyhow::ensure!(line.len() <= 16384, "oversized owner attach response");
737 let response: Value = serde_json::from_str(&line)?;
738 anyhow::ensure!(
739 response["id"] == attach_id
740 && response["error"].is_null()
741 && response["result"]["role"] == "attached",
742 "selected owner refused guest attachment"
743 );
744 let returned: RuntimeOwnerReceipt =
745 serde_json::from_value(response["result"]["owner_receipt"].clone())
746 .context("owner attach receipt unavailable")?;
747 anyhow::ensure!(
748 returned == receipt,
749 "connected owner did not confirm the exact captured generation/store"
750 );
751 if let Some(selection) = native.as_ref() {
752 anyhow::ensure!(
753 response["result"]["native_runtime"] == json!(selection),
754 "native capability or workspace acknowledgement mismatch"
755 );
756 }
757 let routing = response["result"]
758 .get("runtime_routing")
759 .filter(|value| !value.is_null())
760 .map(|value| serde_json::from_value(value.clone()))
761 .transpose()?;
762 Ok(HostOwnerProbe::Attached(Box::new(OwnerClient {
763 read: replies,
764 write,
765 peer,
766 receipt,
767 routing,
768 frontend,
769 output_failed: false,
770 native_initialized: false,
771 pending_initialize: None,
772 native,
773 publication,
774 #[cfg(all(test, unix))]
775 receive_test_hook: None,
776 })))
777 }
778
779 impl OwnerClient {
780 pub fn routing(&self) -> Option<&crate::RuntimeOwnerRouting> {
781 self.routing.as_ref()
782 }
783
784 pub fn receipt(&self) -> &RuntimeOwnerReceipt {
785 &self.receipt
786 }
787 pub async fn send(&mut self, id: Value, method: &str, params: Value) -> Result<()> {
788 anyhow::ensure!(
789 !self.output_failed,
790 "owner transport write previously failed; outcomes uncertain, not replayed"
791 );
792 if self.frontend == crate::daemon_socket::AttachFrontend::Acp {
793 return self
794 .send_frame(json!({"jsonrpc":"2.0","id":id,"method":method,"params":params}))
795 .await;
796 }
797 let id: RequestId = serde_json::from_value(id)?;
798 anyhow::ensure!(
799 self.pending_initialize.is_none(),
800 "receive the pending initialize acknowledgement before sending another request"
801 );
802 if self.frontend == crate::daemon_socket::AttachFrontend::Control
803 && !self.native_initialized
804 && method != "initialize"
805 {
806 let initialize_id = RequestId::String(format!(
807 "codewhale-native-initialize-{}",
808 uuid::Uuid::new_v4()
809 ));
810 self.send_call(RpcCall { id: Some(initialize_id.clone()), method: "initialize".into(), params: json!({"clientInfo":{"name":"codewhale-native-control","version":env!("CARGO_PKG_VERSION")}}), trace: None }).await?;
811 self.pending_initialize = Some(initialize_id.clone());
812 let acknowledged: Result<()> = async {
813 let response = tokio::time::timeout(Duration::from_secs(5), self.recv()).await.context("owner initialize response deadline expired; connection outcome uncertain")??.context("owner input closed before initialize acknowledgement")?;
814 anyhow::ensure!(response.get("id") == Some(&json!(initialize_id)) && response.get("error").is_none() && response.get("result").is_some(), "owner initialize acknowledgement mismatch or refusal");
815 Ok(())
816 }.await;
817 if let Err(error) = acknowledged {
818 self.output_failed = true;
819 return Err(error);
820 }
821 self.native_initialized = true;
822 }
823 let pending = (self.frontend == crate::daemon_socket::AttachFrontend::Control
824 && method == "initialize"
825 && !self.native_initialized)
826 .then(|| id.clone());
827 self.send_call(RpcCall {
828 id: Some(id),
829 method: method.to_string(),
830 params,
831 trace: None,
832 })
833 .await?;
834 self.pending_initialize = pending;
835 Ok(())
836 }
837 async fn send_call(&mut self, request: RpcCall) -> Result<()> {
838 let mut frame = json!(request);
839 if self.native.is_some() {
840 frame["jsonrpc"] = json!("2.0");
841 }
842 self.send_frame(frame).await
843 }
844 async fn check_native_publication(&self) -> Result<()> {
845 if self.native.is_some() {
846 let publication = self.publication.clone();
847 owner_work(move || {
848 anyhow::ensure!(
849 publication.is_current()?,
850 "selected owner publication changed"
851 );
852 Ok(())
853 })
854 .await?;
855 }
856 Ok(())
857 }
858 async fn send_frame(&mut self, frame: Value) -> Result<()> {
859 self.check_native_publication().await?;
860 anyhow::ensure!(
861 !self.output_failed,
862 "owner transport write previously failed; outcomes uncertain, not replayed"
863 );
864 let bytes = serialize_control_frame(&frame)?;
865 let check = self.peer.clone();
866 owner_work(move || check.check()).await?;
867 self.output_failed = true;
868 tokio::time::timeout(
869 Duration::from_secs(5),
870 write_control_line(&mut self.write, &bytes),
871 )
872 .await
873 .context("owner write deadline expired; outcome uncertain, not replayed")??;
874 self.output_failed = false;
875 Ok(())
876 }
877 pub async fn recv(&mut self) -> Result<Option<Value>> {
878 anyhow::ensure!(
879 !self.output_failed,
880 "owner transport write previously failed; outcomes uncertain, not replayed"
881 );
882 let Some(line) = self.read.next_line().await? else {
883 return Ok(None);
884 };
885 self.process_received_line(line).await.map(Some)
886 }
887
888 #[cfg(all(test, unix))]
889 pub(crate) fn set_receive_test_hook(
890 &mut self,
891 hook: tokio::sync::mpsc::UnboundedSender<tokio::sync::oneshot::Sender<()>>,
892 ) {
893 self.receive_test_hook = Some(hook);
894 }
895
896 async fn process_received_line(&mut self, line: String) -> Result<Value> {
897 #[cfg(all(test, unix))]
898 if let Some(hook) = self.receive_test_hook.as_ref() {
899 let (resume_tx, resume_rx) = tokio::sync::oneshot::channel();
900 if hook.send(resume_tx).is_ok() {
901 let _ = resume_rx.await;
902 }
903 }
904 let check = self.peer.clone();
905 owner_work(move || check.check()).await?;
906 self.check_native_publication().await?;
907 let value: Value = serde_json::from_str(&line)?;
908 if let Some(id) = self.pending_initialize.as_ref()
909 && value.get("id") == Some(&json!(id))
910 {
911 let response = serde_json::from_value::<RpcResponse>(value.clone());
912 let accepted = response
913 .ok()
914 .filter(|_| value.get("error").is_none())
915 .and_then(|response| {
916 serde_json::from_value::<InitializeResponse>(response.result).ok()
917 })
918 .is_some_and(|response| response.codex_home.is_absolute())
919 && (self.native.is_none()
920 || value["result"]["capabilities"]
921 == json!([
922 codewhale_app_server_protocol::runtime::NATIVE_RUNTIME_CAPABILITY
923 ]));
924 let rejected = serde_json::from_value::<RpcErrorResponse>(value.clone()).is_ok();
925 if !accepted && !rejected {
926 self.output_failed = true;
927 anyhow::bail!("initialize acknowledgement does not match its typed response");
928 }
929 self.native_initialized = accepted;
930 self.pending_initialize = None;
931 if accepted {
932 self.send_call(RpcCall {
933 id: None,
934 method: "initialized".into(),
935 params: Value::Null,
936 trace: None,
937 })
938 .await?;
939 }
940 }
941 Ok(value)
942 }
943 pub async fn forward_native<I, O>(mut self, input: I, mut output: O) -> Result<()>
944 where
945 I: tokio::io::AsyncRead + Unpin,
946 O: tokio::io::AsyncWrite + Unpin,
947 {
948 anyhow::ensure!(self.native.is_some(), "native capability was not selected");
949 anyhow::ensure!(
950 !self.output_failed,
951 "owner transport write previously failed; outcomes uncertain, not replayed"
952 );
953 let mut input = BoundedLines::new(BufReader::new(input));
954 let deadline = tokio::time::Instant::now() + Duration::from_secs(5);
955 loop {
956 let initialized = self.native_initialized;
957 tokio::select! {
958 _=tokio::time::sleep_until(deadline),if !initialized=>anyhow::bail!("native initialize deadline expired"),
959 line=input.next_line()=>{
960 let Some(line)=line? else{return Ok(())};
961 let frame=match crate::native_runtime::decode_envelope(&line) {
962 Ok(frame)=>frame,
963 Err(_)=>{tokio::time::timeout(Duration::from_secs(5),write_stdio_line(&mut output,&crate::native_runtime::error(Value::Null,-32600,"Invalid native request envelope",400,"not_started"))).await.context("native output deadline expired")??;continue;}
964 };
965 if frame.method=="initialized" {
966 anyhow::ensure!(self.native_initialized,"initialize acknowledgement required before initialized");
967 continue;
968 }
969 if frame.id.is_none() {
970 tokio::time::timeout(Duration::from_secs(5),write_stdio_line(&mut output,&crate::native_runtime::error(Value::Null,-32600,"Invalid native request envelope",400,"not_started"))).await.context("native output deadline expired")??;
971 continue;
972 }
973 if self.pending_initialize.is_some()
974 || (!self.native_initialized && frame.method!="initialize")
975 {
976 tokio::time::timeout(Duration::from_secs(5),write_stdio_line(&mut output,&crate::native_runtime::error(json!(frame.id),-32600,"Not initialized",400,"not_started"))).await.context("native output deadline expired")??;
977 continue;
978 }
979 self.send(json!(frame.id),&frame.method,frame.params).await?;
980 }
981 line=self.read.next_line()=>{
982 let line=line?.context("native owner connection closed; pending outcomes unknown")?;
983 anyhow::ensure!(
984 !self.output_failed,
985 "owner transport write previously failed; outcomes uncertain, not replayed"
986 );
987 let response=self.process_received_line(line).await?;
988 tokio::time::timeout(Duration::from_secs(5),write_stdio_line(&mut output,&response)).await.context("native output deadline expired")??;
989 }
990 }
991 }
992 }
993 pub async fn forward<I, O>(mut self, input: I, output: O) -> Result<()>
994 where
995 I: tokio::io::AsyncRead + Unpin,
996 O: tokio::io::AsyncWrite + Unpin,
997 {
998 anyhow::ensure!(
999 !self.output_failed,
1000 "owner transport write previously failed; outcomes uncertain, not replayed"
1001 );
1002 let mut input = BoundedLines::new(BufReader::new(input));
1003 let mut output = tokio::io::BufWriter::new(output);
1004 let mut input_open = true;
1005 loop {
1006 tokio::select! {
1007 line = input.next_line(), if input_open => match match line {
1008 Ok(line) => line,
1009 Err(error) if self.frontend == crate::daemon_socket::AttachFrontend::Acp && is_frame_refusal(&error) => {
1010 write_stdio_line(&mut output, &json!({"jsonrpc":"2.0","id":null,"error":{"code":-32700,"message":error.to_string()}})).await?;
1011 continue;
1012 }
1013 Err(error) => return Err(error.into()),
1014 } {
1015 None => {
1016 if self.native.is_some() {return Ok(());}
1017 input_open=false;
1018 tokio::time::timeout(Duration::from_secs(5), async {
1019 write_stdio_line(&mut self.write,&json!(RpcNotification { method:"daemon/input_closed".into(), params:Some(json!({})) })).await?;
1020 Ok::<(), anyhow::Error>(())
1021 }).await.context("owner input-close write outcome uncertain, not replayed")??;
1022 }
1023 Some(line) if self.frontend==crate::daemon_socket::AttachFrontend::Acp => {
1024 let check=self.peer.clone();
1025 owner_work(move || check.check()).await?;
1026 // Preserve response IDs/permission replies verbatim.
1027 // Actual ACP authority/parser stays in AcpServer.
1028 tokio::time::timeout(Duration::from_secs(5),write_control_line(&mut self.write,line.as_bytes())).await.context("ACP write outcome uncertain; not replayed")??;
1029 }
1030 Some(line) => match parse_stdio_line(&line) {
1031 ParsedStdioLine::Blank => {},
1032 ParsedStdioLine::Ignored => {},
1033 ParsedStdioLine::Response(response) => self.send_frame(response).await?,
1034 ParsedStdioLine::Request(request) => {
1035 self.send_call(request).await?;
1036 }
1037 }
1038 },
1039 line = self.read.next_line() => match line? {
1040 None if !input_open => return Ok(()),
1041 None if self.frontend==crate::daemon_socket::AttachFrontend::Acp => bail!("The Codewhale Runtime this ACP session attached to (pid {}) has exited, so the session has ended. Restart the agent to continue; pending operation outcomes may be uncertain.", self.receipt.pid),
1042 None => bail!("selected owner connection closed; pending operation outcomes may be uncertain"),
1043 Some(line) => {
1044 let _: Value = serde_json::from_str(&line).context("invalid owner response")?;
1045 self.check_native_publication().await?;
1046 tokio::time::timeout(Duration::from_secs(5), write_control_line(&mut output, line.as_bytes())).await.context("output write deadline expired")??;
1047 }
1048 }
1049 }
1050 }
1051 }
1052 }
1053
1054 #[cfg(all(test, unix))]
1055 mod tests {
1056 use super::*;
1057
1058 #[test]
1059 fn owner_receipt_reobserves_only_typed_unlinked_file_refusals() {
1060 let retired =
1061 anyhow::Error::new(codewhale_config::private_directory::UnlinkedPrivateFile)
1062 .context("bounded owner receipt read");
1063 assert!(owner_receipt_error(retired).is::<PublicationChangedBeforeAttach>());
1064 for refused in [
1065 anyhow::anyhow!("private file was unlinked before validation"),
1066 anyhow::anyhow!("xAI OAuth file must not have multiple filesystem links"),
1067 std::io::Error::from(std::io::ErrorKind::PermissionDenied).into(),
1068 anyhow::anyhow!("owner attach write deadline expired; outcome uncertain"),
1069 ] {
1070 assert!(!owner_receipt_error(refused).is::<PublicationChangedBeforeAttach>());
1071 }
1072 }
1073 }
1074 }
1075
1076 #[cfg(any(unix, windows))]
1077 pub use platform::{
1078 HostOwnerProbe, OwnerClient, PublicationChangedBeforeAttach, UnavailablePublication, connect,
1079 connect_acp_if_published, connect_if_published, connect_listener_if_published, connect_native,
1080 connect_scoped_control_if_published, connect_selected_acp_if_published,
1081 probe_owner_for_host_startup, publication_is_absent,
1082 };
1083
1083 lines RUST