返回 CodeWhale
lib.rs
根目录 / crates / app-server / src / lib.rs
1 #![allow(clippy::too_many_arguments)]
2
3 pub mod acp_server;
4 pub mod eval;
5 pub mod exec_agent;
6 pub mod mcp_server;
7 pub mod remote_control;
8 pub mod remote_setup;
9 pub mod runtime_api;
10 pub mod runtime_chat_relay;
11
12 use crate::http::{app_router, resolve_auth_token};
13 use crate::stdio::{BoundedLines, run_stdio_loop};
14 use anyhow::Context as _;
15 use anyhow::{Result, anyhow};
16 use axum::http::{Method, StatusCode};
17 use codewhale_app_server_protocol::rpc::{
18 RequestId, RpcCall, RpcErrorDetails, RpcErrorResponse, RpcResponse,
19 };
20 #[cfg(test)]
21 use codewhale_app_server_protocol::runtime::MAX_RUNTIME_IMAGE_BODY_BYTES;
22 use codewhale_app_server_protocol::runtime::RuntimeImageInput;
23 use codewhale_config::ConfigStore;
24 use codewhale_core::Runtime;
25 use codewhale_protocol::EventFrame;
26 use codewhale_state::StateStore;
27 use serde::Deserialize;
28 use serde::de::DeserializeOwned;
29 use serde_json::{Value, json};
30 use std::collections::HashMap;
31 use std::net::SocketAddr;
32 use std::path::{Path, PathBuf};
33 #[cfg(test)]
34 use std::process::Child;
35 #[cfg(all(test, unix))]
36 use std::process::Command;
37 use std::sync::Arc;
38 use std::time::Duration;
39 use tokio::io::{AsyncBufRead, AsyncWrite, BufReader};
40 use tokio::sync::{Mutex, RwLock};
41 use uuid::Uuid;
42 mod chat_completions;
43 mod connection;
44 pub mod native_runtime;
45 mod thread_control;
46 mod websocket;
47 pub use codewhale_protocol::{
48 ThreadListParams, ThreadReadParams, ThreadRequest, ThreadResponse, ThreadSetNameParams,
49 };
50 pub use thread_control::{ThreadControlSelection, request_thread_control};
51 #[cfg(test)]
52 mod bridge;
53 mod config_rpc;
54 pub mod http;
55 mod owner_calls;
56 pub mod stdio;
57 mod turns;
58
59 /// Capture once in a client before sending a durable control. Servers require
60 /// the caller's retained key and never manufacture a replacement on retry.
61 pub fn capture_thread_operation_key() -> String {
62 Uuid::new_v4().to_string()
63 }
64
65 pub mod daemon_client;
66 pub mod daemon_socket;
67 #[cfg(windows)]
68 mod daemon_windows;
69
70 /// Legacy DeepSeek-era naming kept for external compatibility.
71 ///
72 /// CodeWhale began life as DeepSeek-TUI; existing health probes, SDK
73 /// harnesses, and on-disk layouts still key off these names. Every remaining
74 /// legacy reference in this crate routes through this shim so a future
75 /// coordinated migration touches exactly one place (repo policy: preserve
76 /// legacy migration care).
77 mod legacy_deepseek_compat {
78 /// Service name advertised by the HTTP and stdio health probes.
79 pub(crate) const SERVICE_NAME: &str = "deepseek-app-server";
80 }
81
82 /// Upper bound on JSON request bodies accepted by the HTTP app-server.
83 const MAX_HTTP_BODY_BYTES: usize = 16 * 1024 * 1024;
84
85 #[cfg(test)]
86 const MAX_SSE_FRAME_BYTES: usize = 16 * 1024 * 1024;
87
88 const DEFAULT_CORS_ORIGINS: &[&str] = &[
89 "http://localhost",
90 "http://localhost:1420",
91 "http://localhost:3000",
92 "http://localhost:5173",
93 "http://127.0.0.1",
94 "http://127.0.0.1:1420",
95 ];
96
97 #[derive(Clone)]
98 pub struct AppServerOptions {
99 pub listen: SocketAddr,
100 pub config_path: Option<PathBuf>,
101 pub auth_token: Option<String>,
102 pub insecure_no_auth: bool,
103 pub cors_origins: Vec<String>,
104 }
105
106 impl std::fmt::Debug for AppServerOptions {
107 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 f.debug_struct("AppServerOptions")
109 .field("listen", &self.listen)
110 .field("config_path", &self.config_path)
111 .field(
112 "auth_token",
113 &self.auth_token.as_ref().map(|_| "<redacted>"),
114 )
115 .field("insecure_no_auth", &self.insecure_no_auth)
116 .field("cors_origins", &self.cors_origins)
117 .finish()
118 }
119 }
120
121 pub use codewhale_runtime::runtime_control::RuntimeControlFrontend;
122
123 /// A bounded listener request admitted only over the authenticated owner channel.
124 /// The bearer is explicit operator input, never discovery or response data.
125 #[derive(Clone, serde::Serialize, serde::Deserialize)]
126 #[serde(deny_unknown_fields)]
127 pub struct RuntimeListenerSelection {
128 pub workers: usize,
129 pub workspace: PathBuf,
130 pub config_profile: Option<String>,
131 #[serde(default)]
132 pub config_source: Option<PathBuf>,
133 pub host: String,
134 pub port: u16,
135 pub cors_origins: Vec<String>,
136 pub auth_token: Option<String>,
137 pub insecure_no_auth: bool,
138 pub mobile: bool,
139 pub web: bool,
140 #[serde(default, skip_serializing)]
141 pub desktop_browser_owner: Option<String>,
142 }
143
144 pub fn is_valid_desktop_browser_owner_key(key: &str) -> bool {
145 use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
146 key.len() == 43
147 && URL_SAFE_NO_PAD
148 .decode(key)
149 .is_ok_and(|bytes| bytes.len() == 32 && URL_SAFE_NO_PAD.encode(&bytes) == key)
150 }
151
152 impl std::fmt::Debug for RuntimeListenerSelection {
153 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154 f.debug_struct("RuntimeListenerSelection")
155 .field("host", &self.host)
156 .field("port", &self.port)
157 .field(
158 "auth_token",
159 &self.auth_token.as_ref().map(|_| "<redacted>"),
160 )
161 .field("mobile", &self.mobile)
162 .field("web", &self.web)
163 .field(
164 "desktop_browser_owner",
165 &self.desktop_browser_owner.as_ref().map(|_| "<present>"),
166 )
167 .finish_non_exhaustive()
168 }
169 }
170
171 impl RuntimeListenerSelection {
172 pub fn validate_bounds(&self) -> Result<()> {
173 anyhow::ensure!(
174 self.workspace.as_os_str().len() <= 32768
175 && self
176 .config_source
177 .as_ref()
178 .is_none_or(|path| path.as_os_str().len() <= 32768)
179 && self
180 .config_profile
181 .as_ref()
182 .is_none_or(|profile| profile.len() <= 1024)
183 && self.host.len() <= 128
184 && self.cors_origins.len() <= 64
185 && self.cors_origins.iter().map(String::len).sum::<usize>() <= 32768
186 && self
187 .auth_token
188 .as_ref()
189 .is_none_or(|token| token.len() <= 8192)
190 && self
191 .desktop_browser_owner
192 .as_deref()
193 .is_none_or(is_valid_desktop_browser_owner_key),
194 "selected frontend input exceeds its bounds"
195 );
196 Ok(())
197 }
198 }
199
200 #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
201 #[serde(deny_unknown_fields)]
202 pub struct RuntimeFrontendScope {
203 pub workers: usize,
204 pub workspace: PathBuf,
205 pub config_profile: Option<String>,
206 #[serde(default)]
207 pub config_source: Option<PathBuf>,
208 }
209
210 impl RuntimeFrontendScope {
211 pub fn validate_bounds(&self) -> Result<()> {
212 anyhow::ensure!(
213 self.workspace.as_os_str().len() <= 32768
214 && self
215 .config_source
216 .as_ref()
217 .is_none_or(|path| path.as_os_str().len() <= 32768)
218 && self
219 .config_profile
220 .as_ref()
221 .is_none_or(|profile| profile.len() <= 1024),
222 "selected frontend scope exceeds its bounds"
223 );
224 Ok(())
225 }
226 }
227
228 #[derive(Clone)]
229 pub enum RuntimeOwnerFrontendSelection {
230 Control(RuntimeFrontendScope),
231 Acp {
232 scope: Option<RuntimeFrontendScope>,
233 model: Option<String>,
234 },
235 Listener(RuntimeListenerSelection),
236 }
237
238 pub type RuntimeOwnerEventStream =
239 std::pin::Pin<Box<dyn futures_util::Stream<Item = RuntimeOwnerEventFrame> + Send>>;
240
241 pub struct RuntimeOwnerEventFrame {
242 pub event: String,
243 pub data: Value,
244 pub sequence: Option<u64>,
245 }
246
247 #[derive(Debug, Clone)]
248 pub enum RuntimeOwnerRequest {
249 Native {
250 workspace: PathBuf,
251 request: codewhale_app_server_protocol::runtime::NativeRuntimeRequest,
252 },
253 Capabilities,
254 Providers,
255 ProviderModels {
256 provider: String,
257 provider_id: Option<String>,
258 cursor: Option<String>,
259 },
260 ReloadConfig,
261 CreateThread(Value),
262 ListThreads {
263 include_archived: bool,
264 limit: usize,
265 },
266 RunningThreads,
267 LoadedThreads,
268 GetThread {
269 thread_id: String,
270 },
271 UpdateThread {
272 thread_id: String,
273 body: Value,
274 },
275 GetGoal {
276 thread_id: String,
277 },
278 ClearGoal {
279 thread_id: String,
280 },
281 HistorySnapshot {
282 thread_id: String,
283 },
284 HistoryImport(codewhale_protocol::CanonicalHistoryImportRequest),
285 HistoryMutate(codewhale_protocol::CanonicalThreadMutationRequest),
286 HistoryLookup(codewhale_protocol::CanonicalThreadOperationLookup),
287 HistoryRecover(codewhale_protocol::CanonicalThreadOperationRecovery),
288 LookupTurnOperation {
289 thread_id: String,
290 operation_key: String,
291 },
292 StartTurn {
293 thread_id: String,
294 body: Value,
295 },
296 InterruptTurn {
297 thread_id: String,
298 turn_id: String,
299 },
300 DecideApproval {
301 approval_id: String,
302 binding: Option<codewhale_engine::runtime_threads::manager::ExternalApprovalBinding>,
303 decision: codewhale_engine::runtime_threads::manager::ExternalApprovalDecision,
304 },
305 SubmitUserInput {
306 thread_id: String,
307 input_id: String,
308 turn_id: Option<String>,
309 response: codewhale_engine::tools::user_input::UserInputResponse,
310 },
311 CancelUserInput {
312 thread_id: String,
313 input_id: String,
314 turn_id: Option<String>,
315 },
316 DeliverDynamicToolResult {
317 thread_id: String,
318 turn_id: String,
319 call_id: String,
320 result: codewhale_app_server_protocol::runtime::DynamicToolCallResult,
321 },
322 }
323
324 #[derive(Debug, thiserror::Error)]
325 #[error("Runtime owner returned {status}: {message}")]
326 pub struct RuntimeOwnerFailure {
327 pub status: u16,
328 pub message: String,
329 pub code: Option<String>,
330 }
331
332 /// Captured Runtime-owned IO projection. Implementations use the held manager
333 /// and existing routers; this port owns neither a store nor a turn controller.
334 pub trait RuntimeOwnerFrontend: Send + Sync {
335 fn execute(
336 &self,
337 request: RuntimeOwnerRequest,
338 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Value>> + Send + '_>>;
339 fn events(
340 &self,
341 thread_id: String,
342 since_seq: u64,
343 ) -> std::pin::Pin<
344 Box<dyn std::future::Future<Output = Result<RuntimeOwnerEventStream>> + Send + '_>,
345 >;
346 fn events_in_workspace(
347 &self,
348 workspace: PathBuf,
349 thread_id: String,
350 since_seq: u64,
351 ) -> std::pin::Pin<
352 Box<dyn std::future::Future<Output = Result<RuntimeOwnerEventStream>> + Send + '_>,
353 > {
354 let _ = workspace;
355 self.events(thread_id, since_seq)
356 }
357 fn validate_selection<'a>(
358 &'a self,
359 selection: &'a RuntimeOwnerFrontendSelection,
360 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>>;
361 fn serve<'a>(
362 &'a self,
363 selection: RuntimeOwnerFrontendSelection,
364 compatibility: AppState,
365 input: Box<dyn tokio::io::AsyncBufRead + Send + Unpin>,
366 output: Box<dyn AsyncWrite + Send + Unpin + 'a>,
367 ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>>;
368 }
369
370 #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
371 #[serde(deny_unknown_fields)]
372 pub struct RuntimeOwnerRouting {
373 pub endpoint: SocketAddr,
374 /// The owning manager's acknowledged workspace. A legacy cold wrapper
375 /// without one cannot supply a default mutation scope.
376 #[serde(default, skip_serializing_if = "Option::is_none")]
377 pub workspace: Option<PathBuf>,
378 /// Actual held scheduler setting; absent on historical cold wrappers.
379 #[serde(default, skip_serializing_if = "Option::is_none")]
380 pub workers: Option<usize>,
381 pub mobile: bool,
382 pub web: bool,
383 pub acp: bool,
384 #[serde(default)]
385 pub acp_only: bool,
386 }
387
388 #[cfg(test)]
389 type SharedRuntimeBridge = Arc<Mutex<RuntimeBridge>>;
390
391 #[derive(Clone)]
392 pub struct AppState {
393 captured_owner: Option<codewhale_protocol::RuntimeOwnerReceipt>,
394 captured_routing: Option<RuntimeOwnerRouting>,
395 frontend_workspace: Option<PathBuf>,
396 owner_frontend: Option<Arc<dyn RuntimeOwnerFrontend>>,
397 config_path: Option<PathBuf>,
398 config: Arc<RwLock<codewhale_config::ConfigToml>>,
399 /// Bookkeeping config and read-only historical archive access.
400 /// Actual turns and transcript writes belong to the captured owner.
401 runtime: Arc<RwLock<Runtime>>,
402 auth_token: Option<String>,
403 #[cfg(test)]
404 runtime_bridge: Arc<Mutex<Option<SharedRuntimeBridge>>>,
405 #[cfg(test)]
406 runtime_thread_map: Arc<Mutex<HashMap<String, String>>>,
407 stdio_thread_hints: Arc<Mutex<HashMap<String, RuntimeThreadHint>>>,
408 in_flight_turns: Arc<Mutex<HashMap<String, InFlightTurn>>>,
409 }
410
411 #[derive(Clone)]
412 enum TurnExecutionOwner {
413 Native(Arc<dyn RuntimeOwnerFrontend>),
414 #[cfg(test)]
415 HistoricalHttp {
416 base_url: String,
417 auth_token: Option<String>,
418 },
419 }
420
421 #[derive(Clone)]
422 struct InFlightTurn {
423 owner: TurnExecutionOwner,
424 /// Thread id as the *runtime* knows it, not the stdio-facing id.
425 runtime_thread_id: String,
426 turn_id: String,
427 connection: Option<connection::ConnectionId>,
428 }
429
430 type TurnRegistry = Arc<Mutex<HashMap<String, InFlightTurn>>>;
431
432 /// Server error: the app-server could not reach the runtime that executes
433 /// turns. Kept in the JSON-RPC implementation-defined server range
434 /// (-32000..-32099) alongside `thread_not_found` (-32004).
435 const RUNTIME_UNAVAILABLE_CODE: i64 = -32005;
436
437 /// Server error: the named thread does not exist.
438 const THREAD_NOT_FOUND_CODE: i64 = -32004;
439
440 /// Server error: a daemon-socket client tried to act before `daemon/attach`.
441 /// Only the unix listener raises it; gated so the Windows build (where the
442 /// listener is a typed-unsupported stub) does not fail `warnings = "deny"`
443 /// on dead code.
444 #[cfg(any(unix, windows))]
445 const ATTACH_REQUIRED_CODE: i64 = -32010;
446
447 /// Server error: a `daemon/attach` claim lost to a live owner.
448 #[cfg(any(unix, windows))]
449 const DAEMON_ALREADY_CLAIMED_CODE: i64 = -32011;
450
451 /// Server error: only the owning client may `shutdown` the daemon.
452 const NOT_DAEMON_OWNER_CODE: i64 = -32012;
453
454 /// Server error: the client refused the daemon's version at attach time.
455 #[cfg(any(unix, windows))]
456 const DAEMON_VERSION_SKEW_CODE: i64 = -32013;
457
458 /// Server error: `daemon/attach` sent twice on one connection.
459 const ALREADY_ATTACHED_CODE: i64 = -32014;
460
461 #[derive(Debug)]
462 struct DispatchError {
463 wire: RpcErrorDetails,
464 transport_error: Option<anyhow::Error>,
465 }
466
467 #[derive(Debug)]
468 struct StdioDispatchResult {
469 result: Value,
470 should_exit: bool,
471 }
472
473 #[cfg(test)]
474 struct RuntimeBridge {
475 base_url: String,
476 client: reqwest::Client,
477 auth_token: Option<String>,
478 #[cfg(test)]
479 child: Option<Child>,
480 #[cfg(test)]
481 last_seq_by_thread: HashMap<String, u64>,
482 }
483
484 #[cfg(test)]
485 impl std::fmt::Debug for RuntimeBridge {
486 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
487 formatter
488 .debug_struct("RuntimeBridge")
489 .field("base_url", &self.base_url)
490 .field("authenticated", &self.auth_token.is_some())
491 .finish_non_exhaustive()
492 }
493 }
494
495 #[derive(Debug, Clone, Default)]
496 struct RuntimeThreadHint {
497 model: Option<String>,
498 workspace: Option<PathBuf>,
499 }
500
501 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
502 enum TurnTerminalStatus {
503 Completed,
504 Failed,
505 Interrupted,
506 Canceled,
507 }
508
509 /// Structured capture of one bridged turn, for callers that must *return*
510 /// the turn instead of streaming it (HTTP `/prompt`, HTTP `/thread` messages).
511 ///
512 /// The stdio path streams the same events to its writer and needs none of
513 /// this, so it passes `None` and pays nothing.
514 #[derive(Debug, Default)]
515 struct TurnTranscript {
516 /// Concatenated `agent_message` deltas — the model's actual output.
517 text: String,
518 /// The model the runtime reports for the thread that ran the turn.
519 model: Option<String>,
520 /// The same frames the stdio path writes, in order.
521 events: Vec<EventFrame>,
522 }
523
524 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
525 enum AppTransport {
526 Http,
527 Stdio,
528 /// Unix-domain-socket daemon transport (`daemon_socket`). Speaks the
529 /// same RPC objects as stdio inside WebSocket text messages after attach.
530 Socket,
531 }
532
533 impl AppTransport {
534 /// Wire label reported by `healthz` / `capabilities`.
535 fn label(self) -> &'static str {
536 match self {
537 Self::Http => "http",
538 Self::Stdio => "stdio",
539 Self::Socket => {
540 #[cfg(windows)]
541 {
542 "named-pipe"
543 }
544 #[cfg(not(windows))]
545 {
546 "unix-socket"
547 }
548 }
549 }
550 }
551 }
552
553 /// Whether the peer driving a JSON-RPC loop may stop the whole server.
554 ///
555 /// The process-owned stdio loop always may (its peer *is* the supervisor).
556 /// On the daemon socket only the client that claimed the daemon may; every
557 /// other attached client is refused with `not_daemon_owner` — the brief's
558 /// "never terminate a daemon the app did not spawn", enforced server-side.
559 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
560 enum ShutdownAuthority {
561 Granted,
562 Denied,
563 }
564
565 /// Per-connection policy for [`run_stdio_loop`].
566 #[derive(Debug, Clone, Copy)]
567 struct StdioLoopPolicy {
568 transport: AppTransport,
569 shutdown: ShutdownAuthority,
570 }
571
572 impl StdioLoopPolicy {
573 /// Legacy stdio qualification comparator; production stdio attaches its owner.
574 const fn process_stdio() -> Self {
575 Self {
576 transport: AppTransport::Stdio,
577 shutdown: ShutdownAuthority::Granted,
578 }
579 }
580 }
581
582 /// Why [`run_stdio_loop`] returned.
583 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
584 enum StdioLoopExit {
585 /// The peer closed its write side; nothing asked the server to stop.
586 InputClosed,
587 /// The peer sent an honoured `shutdown`.
588 Shutdown,
589 }
590
591 #[derive(Debug, Deserialize)]
592 struct ConfigGetParams {
593 key: String,
594 }
595
596 #[derive(Debug, Deserialize)]
597 struct ConfigSetParams {
598 key: String,
599 value: String,
600 }
601
602 #[derive(Debug, Deserialize)]
603 struct ThreadIdParams {
604 thread_id: String,
605 }
606
607 #[derive(Debug, Deserialize)]
608 struct ThreadMessageParams {
609 #[serde(default)]
610 allowed_tools: Option<Vec<String>>,
611 #[serde(default, rename = "maxOutputTokens", alias = "max_output_tokens")]
612 max_output_tokens: Option<std::num::NonZeroU32>,
613 thread_id: String,
614 input: String,
615 #[serde(default)]
616 images: Vec<RuntimeImageInput>,
617 }
618
619 #[derive(Debug, Deserialize)]
620 struct ThreadInterruptParams {
621 thread_id: String,
622 }
623
624 pub async fn run(options: AppServerOptions) -> Result<()> {
625 let auth_token = resolve_auth_token(&options)?;
626 let state =
627 build_state_off_runtime(options.config_path.clone(), auth_token, AppTransport::Http)
628 .await?;
629 let app = app_router(state, &options.cors_origins);
630
631 let listener = tokio::net::TcpListener::bind(options.listen).await?;
632 axum::serve(listener, app)
633 .with_graceful_shutdown(shutdown_signal())
634 .await?;
635 Ok(())
636 }
637
638 async fn shutdown_signal() {
639 let ctrl_c = async {
640 let _ = tokio::signal::ctrl_c().await;
641 };
642
643 #[cfg(unix)]
644 let terminate = async {
645 match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
646 Ok(mut signal) => {
647 signal.recv().await;
648 }
649 Err(_) => std::future::pending::<()>().await,
650 }
651 };
652
653 #[cfg(not(unix))]
654 let terminate = std::future::pending::<()>();
655
656 tokio::select! {
657 _ = ctrl_c => {}
658 _ = terminate => {}
659 }
660 }
661
662 /// Attach the existing compatibility dispatcher to the actual held Runtime.
663 /// Auth remains process-private; it is never part of the owner receipt or IPC.
664 #[cfg(any(unix, windows))]
665 pub async fn bind_runtime_owner(
666 config_path: Option<PathBuf>,
667 endpoint: SocketAddr,
668 auth_token: Option<String>,
669 owner: codewhale_protocol::RuntimeOwnerReceipt,
670 ) -> Result<daemon_socket::DaemonSocket> {
671 let (daemon, _) = bind_runtime_frontends(
672 config_path,
673 auth_token,
674 owner,
675 RuntimeOwnerRouting {
676 endpoint,
677 workspace: None,
678 workers: None,
679 mobile: false,
680 web: false,
681 acp: false,
682 acp_only: false,
683 },
684 None,
685 None,
686 )
687 .await?;
688 // A caller of this entry point has no HTTP frontend to fall back on: it
689 // exists to hand back a socket. `bind_runtime_frontends` only degrades to
690 // `None` when the filesystem cannot hold a private endpoint directory, and
691 // there is nothing to serve if that happens here.
692 daemon.ok_or_else(|| {
693 anyhow::anyhow!(
694 "this filesystem cannot hold the private directory a runtime owner endpoint needs"
695 )
696 })
697 }
698
699 /// Build the actual compatibility state once for all owner frontends.
700 #[cfg(any(unix, windows))]
701 pub async fn bind_runtime_frontends(
702 config_path: Option<PathBuf>,
703 auth_token: Option<String>,
704 owner: codewhale_protocol::RuntimeOwnerReceipt,
705 routing: RuntimeOwnerRouting,
706 owner_frontend: Option<Arc<dyn RuntimeOwnerFrontend>>,
707 recovery: Option<Arc<daemon_client::UnavailablePublication>>,
708 ) -> Result<(Option<daemon_socket::DaemonSocket>, AppState)> {
709 anyhow::ensure!(
710 owner.version == 1 && owner.pid == std::process::id() && !owner.lease_generation.is_empty(),
711 "invalid captured Runtime owner"
712 );
713 let mut state =
714 build_state_off_runtime(config_path, auth_token.clone(), AppTransport::Socket).await?;
715 state.captured_owner = Some(owner.clone());
716 anyhow::ensure!(
717 routing.acp == owner_frontend.is_some() && (!routing.acp_only || routing.acp),
718 "ACP projection must belong to its actual captured owner"
719 );
720 state.frontend_workspace = routing.workspace.clone();
721 state.captured_routing = Some(routing);
722 state.owner_frontend = owner_frontend;
723 let daemon = daemon_socket::bind_captured_owner(state.clone(), owner, recovery).await?;
724 Ok((daemon, state))
725 }
726
727 pub async fn run_owned_acp(state: AppState) -> Result<()> {
728 anyhow::ensure!(
729 state
730 .captured_owner
731 .as_ref()
732 .is_some_and(|owner| owner.pid == std::process::id()),
733 "ACP stdio must belong to its actual captured host"
734 );
735 state
736 .owner_frontend
737 .as_ref()
738 .context("captured owner has no ACP projection")?
739 .serve(
740 RuntimeOwnerFrontendSelection::Acp {
741 scope: None,
742 model: None,
743 },
744 state.clone(),
745 Box::new(BufReader::new(tokio::io::stdin())),
746 Box::new(tokio::io::BufWriter::new(tokio::io::stdout())),
747 )
748 .await
749 }
750
751 /// The existing charged socket connection invokes the same priority-aware
752 /// dispatcher after its captured Runtime has admitted the selected scope.
753 pub async fn run_guest_control<'a>(
754 mut state: AppState,
755 workspace: PathBuf,
756 input: Box<dyn AsyncBufRead + Send + Unpin>,
757 output: Box<dyn AsyncWrite + Send + Unpin + 'a>,
758 ) -> Result<()> {
759 anyhow::ensure!(
760 state
761 .captured_owner
762 .as_ref()
763 .is_some_and(|owner| owner.pid == std::process::id()),
764 "control projection requires its actual captured host"
765 );
766 state.frontend_workspace = Some(workspace);
767 let policy = StdioLoopPolicy {
768 transport: AppTransport::Socket,
769 shutdown: ShutdownAuthority::Denied,
770 };
771 run_stdio_loop(&state, BoundedLines::new(input), output, policy, None::<()>).await?;
772 Ok(())
773 }
774
775 /// Logical write EOF for duplex transports. This is only a per-connection
776 /// lifecycle notification; it carries no tool, turn or host-shutdown authority.
777 pub fn is_control_input_closed(message: &Value) -> bool {
778 message
779 .get("jsonrpc")
780 .is_none_or(|version| version == "2.0")
781 && message.get("id").is_none()
782 && message["method"] == "daemon/input_closed"
783 && message["params"]
784 .as_object()
785 .is_some_and(|params| params.is_empty())
786 }
787
788 pub async fn run_owned_stdio(state: AppState) -> Result<()> {
789 anyhow::ensure!(
790 state
791 .captured_owner
792 .as_ref()
793 .is_some_and(|owner| owner.pid == std::process::id()),
794 "stdio must belong to its actual captured Runtime host"
795 );
796 let lines = BoundedLines::new(BufReader::new(tokio::io::stdin()));
797 let writer = tokio::io::BufWriter::new(tokio::io::stdout());
798 run_stdio_loop(
799 &state,
800 lines,
801 writer,
802 StdioLoopPolicy::process_stdio(),
803 None::<()>,
804 )
805 .await?;
806 Ok(())
807 }
808
809 #[cfg(test)]
810 fn build_state(config_path: Option<PathBuf>, auth_token: Option<String>) -> Result<AppState> {
811 build_state_with_transport(config_path, auth_token, AppTransport::Http)
812 }
813
814 /// [`build_state_with_transport`] on the blocking pool. Server startup is
815 /// async, but building state is not: it reads and parses the config file,
816 /// creates directories, and opens SQLite (a schema migration that may wait
817 /// out the 5s busy timeout behind another process). Run inline, that parked
818 /// a Tokio worker.
819 async fn build_state_off_runtime(
820 config_path: Option<PathBuf>,
821 auth_token: Option<String>,
822 transport: AppTransport,
823 ) -> Result<AppState> {
824 codewhale_runtime::runtime_control::owner_work(move || {
825 build_state_with_transport(config_path, auth_token, transport)
826 })
827 .await
828 .context("app-server state setup task failed")
829 }
830
831 fn build_state_with_transport(
832 config_path: Option<PathBuf>,
833 auth_token: Option<String>,
834 _transport: AppTransport,
835 ) -> Result<AppState> {
836 let has_explicit_config_path = config_path.is_some();
837 let store = ConfigStore::load(config_path)?;
838 store.config.validate_configured_model()?;
839 let config_path = has_explicit_config_path.then(|| store.path().to_path_buf());
840 let config = store.config.clone();
841
842 let state_db_path = config_path
843 .as_ref()
844 .and_then(|p| p.parent().map(|parent| parent.join("state.db")));
845 let state_store = StateStore::open(state_db_path)?;
846
847 let runtime = Runtime::new(config.clone(), state_store);
848
849 Ok(AppState {
850 captured_owner: None,
851 captured_routing: None,
852 frontend_workspace: None,
853 owner_frontend: None,
854 config_path,
855 config: Arc::new(RwLock::new(config)),
856 runtime: Arc::new(RwLock::new(runtime)),
857 auth_token,
858 #[cfg(test)]
859 runtime_bridge: Arc::new(Mutex::new(None)),
860 #[cfg(test)]
861 runtime_thread_map: Arc::new(Mutex::new(HashMap::new())),
862 stdio_thread_hints: Arc::new(Mutex::new(HashMap::new())),
863 in_flight_turns: Arc::new(Mutex::new(HashMap::new())),
864 })
865 }
866
867 fn params_or_object(params: Value) -> Value {
868 if params.is_null() { json!({}) } else { params }
869 }
870
871 fn parse_params<T: DeserializeOwned>(params: Value) -> std::result::Result<T, DispatchError> {
872 serde_json::from_value(params).map_err(|err| DispatchError::invalid_params(err.to_string()))
873 }
874
875 fn jsonrpc_result(id: RequestId, result: Value) -> Value {
876 json!(RpcResponse { id, result })
877 }
878
879 fn jsonrpc_error(id: RequestId, err: DispatchError) -> Value {
880 json!(RpcErrorResponse {
881 id,
882 error: err.wire
883 })
884 }
885
886 impl DispatchError {
887 fn invalid_request(message: impl Into<String>) -> Self {
888 Self {
889 wire: RpcErrorDetails {
890 code: -32600,
891 message: message.into(),
892 data: None,
893 },
894 transport_error: None,
895 }
896 }
897
898 fn method_not_found(method: &str) -> Self {
899 Self {
900 wire: RpcErrorDetails {
901 code: -32601,
902 message: format!("unsupported method: {method}"),
903 data: None,
904 },
905 transport_error: None,
906 }
907 }
908
909 fn invalid_params(message: impl Into<String>) -> Self {
910 Self {
911 wire: RpcErrorDetails {
912 code: -32602,
913 message: message.into(),
914 data: None,
915 },
916 transport_error: None,
917 }
918 }
919
920 fn unsupported_interactive_execution() -> Self {
921 Self {
922 wire: RpcErrorDetails {
923 code: -32602,
924 message: "Compatibility transports cannot answer approvals or clarification requests. Use codewhale app-server --http and /v1/* for interactive turns and goal execution; tool-free turn requests require explicit allowed_tools: [].".to_string(),
925 data: Some(json!({
926 "error": "interactive_execution_unsupported",
927 "entrypoint": "codewhale app-server --http",
928 "allowed_tools_required": [],
929 "goal_execution": false,
930 })),
931 },
932 transport_error: None,
933 }
934 }
935
936 /// Server error (-32000..-32099): the turn engine could not be reached,
937 /// or refused to start the turn — either way nothing ran. Distinct from
938 /// `internal` because the caller can retry this one once a runtime is up.
939 fn runtime_unavailable(message: impl Into<String>) -> Self {
940 let message = message.into();
941 Self {
942 wire: RpcErrorDetails {
943 code: RUNTIME_UNAVAILABLE_CODE,
944 message: message.clone(),
945 data: Some(json!({
946 "error": "runtime_unavailable",
947 "detail": message,
948 })),
949 },
950 transport_error: None,
951 }
952 }
953
954 /// Server error (-32000..-32099): the named thread does not exist.
955 fn thread_not_found(thread_id: &str) -> Self {
956 Self {
957 wire: RpcErrorDetails {
958 code: THREAD_NOT_FOUND_CODE,
959 message: format!("thread not found: {thread_id}"),
960 data: Some(json!({
961 "error": "thread_not_found",
962 "thread_id": thread_id,
963 })),
964 },
965 transport_error: None,
966 }
967 }
968
969 fn internal(message: impl Into<String>) -> Self {
970 Self {
971 wire: RpcErrorDetails {
972 code: -32603,
973 message: message.into(),
974 data: None,
975 },
976 transport_error: None,
977 }
978 }
979
980 /// Server error (-32000..-32099): the daemon-socket connection has not
981 /// completed `daemon/attach`, so nothing but `healthz` is allowed yet.
982 #[cfg(any(unix, windows))]
983 fn attach_required(method: &str) -> Self {
984 Self {
985 wire: RpcErrorDetails {
986 code: ATTACH_REQUIRED_CODE,
987 message: format!("send daemon/attach before `{method}`"),
988 data: Some(json!({
989 "error": "attach_required",
990 "method": method,
991 "attach_method": daemon_socket::ATTACH_METHOD,
992 })),
993 },
994 transport_error: None,
995 }
996 }
997
998 /// Server error (-32000..-32099): a `claim` attach lost to a live owner.
999 #[cfg(any(unix, windows))]
1000 fn daemon_already_claimed(owner: &Value) -> Self {
1001 Self {
1002 wire: RpcErrorDetails {
1003 code: DAEMON_ALREADY_CLAIMED_CODE,
1004 message: "daemon already claimed by another client; attach with mode=attach"
1005 .to_string(),
1006 data: Some(json!({
1007 "error": "daemon_already_claimed",
1008 "owner": owner,
1009 })),
1010 },
1011 transport_error: None,
1012 }
1013 }
1014
1015 /// Server error (-32000..-32099): only the owner may stop the daemon.
1016 fn not_daemon_owner() -> Self {
1017 Self {
1018 wire: RpcErrorDetails {
1019 code: NOT_DAEMON_OWNER_CODE,
1020 message: "only the client that claimed this daemon may shut it down".to_string(),
1021 data: Some(json!({ "error": "not_daemon_owner" })),
1022 },
1023 transport_error: None,
1024 }
1025 }
1026
1027 /// Server error (-32000..-32099): only the connection that started a
1028 /// turn may interrupt it.
1029 fn not_turn_owner() -> Self {
1030 Self {
1031 wire: RpcErrorDetails {
1032 code: NOT_DAEMON_OWNER_CODE,
1033 message: "only the connection that started this turn may interrupt it".to_string(),
1034 data: Some(json!({ "error": "not_turn_owner" })),
1035 },
1036 transport_error: None,
1037 }
1038 }
1039
1040 /// Server error (-32000..-32099): the client's expected daemon version
1041 /// does not match the running binary (bundle skew).
1042 #[cfg(any(unix, windows))]
1043 fn daemon_version_skew(expected: &str, actual: &str) -> Self {
1044 Self {
1045 wire: RpcErrorDetails {
1046 code: DAEMON_VERSION_SKEW_CODE,
1047 message: format!(
1048 "daemon version {actual} does not match the client's expected {expected}"
1049 ),
1050 data: Some(json!({
1051 "error": "daemon_version_skew",
1052 "expected": expected,
1053 "actual": actual,
1054 })),
1055 },
1056 transport_error: None,
1057 }
1058 }
1059
1060 /// Server error (-32000..-32099): `daemon/attach` after attaching.
1061 fn already_attached() -> Self {
1062 Self {
1063 wire: RpcErrorDetails {
1064 code: ALREADY_ATTACHED_CODE,
1065 message: "this connection is already attached".to_string(),
1066 data: Some(json!({ "error": "already_attached" })),
1067 },
1068 transport_error: None,
1069 }
1070 }
1071 }
1072
1073 /// Install the process-wide rustls crypto provider once for tests that build
1074 /// an HTTP client. Production installs it at startup; each test must do the
1075 /// same instead of relying on another test in the process having run first
1076 /// (nextest runs every test in its own process).
1077 #[cfg(test)]
1078 pub(crate) fn install_test_crypto_provider() {
1079 static INIT: std::sync::OnceLock<()> = std::sync::OnceLock::new();
1080 INIT.get_or_init(|| {
1081 let _ = rustls::crypto::ring::default_provider().install_default();
1082 });
1083 }
1084
1085 #[cfg(test)]
1086 mod tests;
1087
1087 lines RUST