1use std::collections::HashMap;
177use std::ops::Deref;
178use std::path::PathBuf;
179use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
180use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
181use std::time::Duration;
182
183use serde::ser::SerializeMap;
184use serde::{Deserialize, Serialize, Serializer};
185use serde_json::{Map, Value, json};
186use tokio::io::{AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader};
187use tokio::process::{Child, ChildStderr, ChildStdout, Command};
188use tokio::sync::{Notify, mpsc, oneshot};
189use tracing::{Instrument, debug, warn};
190
191use crate::Codex;
192use crate::error::{Error, OutputStream, Result};
193use crate::exec::{GroupKillGuard, SpanOutcome};
194use crate::types::{ApprovalPolicy, SandboxMode};
195
196const STDERR_TAIL_BYTES: usize = 16 * 1024;
198
199const STARTUP_EXIT_WAIT: Duration = Duration::from_secs(2);
202
203const STDERR_SETTLE: Duration = Duration::from_millis(500);
206
207#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
212#[serde(untagged)]
213pub enum RequestId {
214 Number(i64),
216 String(String),
218}
219
220impl std::fmt::Display for RequestId {
221 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
222 match self {
223 Self::Number(n) => write!(f, "{n}"),
224 Self::String(s) => f.write_str(s),
225 }
226 }
227}
228
229#[derive(Debug, Clone, PartialEq)]
233pub struct Notification {
234 pub method: String,
236 pub params: Value,
238}
239
240impl Notification {
241 #[must_use]
248 pub fn agent_message(&self) -> Option<AgentMessage> {
249 if self.method != "item/completed" {
250 return None;
251 }
252 let item = self.params.get("item")?;
253 if item.get("type")?.as_str()? != "agentMessage" {
254 return None;
255 }
256 Some(AgentMessage {
257 thread_id: self.params.get("threadId")?.as_str()?.to_string(),
258 turn_id: self.params.get("turnId")?.as_str()?.to_string(),
259 text: item.get("text")?.as_str()?.to_string(),
260 phase: item
261 .get("phase")
262 .and_then(Value::as_str)
263 .map(str::to_string),
264 })
265 }
266
267 #[must_use]
270 pub fn turn_completed(&self) -> Option<TurnCompleted> {
271 if self.method != "turn/completed" {
272 return None;
273 }
274 serde_json::from_value(self.params.clone()).ok()
275 }
276}
277
278#[derive(Debug, Clone, PartialEq, Eq)]
281pub struct AgentMessage {
282 pub thread_id: String,
284 pub turn_id: String,
286 pub text: String,
288 pub phase: Option<String>,
291}
292
293impl AgentMessage {
294 #[must_use]
296 pub fn is_final_answer(&self) -> bool {
297 self.phase.as_deref() == Some("final_answer")
298 }
299}
300
301#[derive(Debug, Clone, PartialEq)]
307pub struct ServerRequest {
308 pub id: RequestId,
310 pub method: String,
312 pub params: Value,
314}
315
316#[derive(Debug, Clone, PartialEq)]
318#[non_exhaustive]
319pub enum ServerMessage {
320 Notification(Notification),
322 Request(ServerRequest),
324}
325
326#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
331#[serde(rename_all = "camelCase")]
332#[non_exhaustive]
333pub enum TurnStatus {
334 InProgress,
336 Completed,
338 Interrupted,
340 Failed,
342 #[serde(other)]
344 Unknown,
345}
346
347#[derive(Debug, Clone, PartialEq, Deserialize)]
350#[serde(rename_all = "camelCase")]
351pub struct Turn {
352 pub id: String,
355 pub status: TurnStatus,
357 #[serde(default)]
359 pub items: Vec<Value>,
360 #[serde(default)]
363 pub error: Option<Value>,
364 #[serde(default)]
366 pub duration_ms: Option<i64>,
367}
368
369impl Turn {
370 #[must_use]
379 pub fn final_message(&self) -> Option<&str> {
380 self.items
381 .iter()
382 .rev()
383 .filter(|item| {
384 item.get("type").and_then(Value::as_str) == Some("agentMessage")
385 && item.get("phase").and_then(Value::as_str) == Some("final_answer")
386 })
387 .find_map(|item| item.get("text").and_then(Value::as_str))
388 }
389}
390
391#[derive(Debug, Clone, PartialEq, Deserialize)]
393#[serde(rename_all = "camelCase")]
394pub struct TurnCompleted {
395 pub thread_id: String,
397 pub turn: Turn,
399}
400
401#[derive(Debug, Clone, PartialEq)]
403pub struct Thread {
404 pub id: String,
406 pub model: Option<String>,
408 pub raw: Value,
410}
411
412#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
414#[serde(rename_all = "camelCase", default)]
415pub struct ServerInfo {
416 pub user_agent: String,
418 pub codex_home: Option<String>,
420 pub platform_family: Option<String>,
422 pub platform_os: Option<String>,
424}
425
426#[derive(Debug, Clone, PartialEq)]
428pub enum UserInput {
429 Text(String),
431 Raw(Value),
434}
435
436impl UserInput {
437 #[must_use]
439 pub fn text(text: impl Into<String>) -> Self {
440 Self::Text(text.into())
441 }
442}
443
444impl Serialize for UserInput {
445 fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
446 match self {
447 Self::Text(text) => {
448 let mut map = serializer.serialize_map(Some(3))?;
449 map.serialize_entry("type", "text")?;
450 map.serialize_entry("text", text)?;
451 map.serialize_entry("text_elements", &Vec::<Value>::new())?;
455 map.end()
456 }
457 Self::Raw(value) => value.serialize(serializer),
458 }
459 }
460}
461
462#[derive(Debug, Clone, Default, Serialize)]
467#[serde(rename_all = "camelCase")]
468pub struct ThreadStartParams {
469 #[serde(skip_serializing_if = "Option::is_none")]
470 cwd: Option<PathBuf>,
471 #[serde(skip_serializing_if = "Option::is_none")]
472 model: Option<String>,
473 #[serde(skip_serializing_if = "Option::is_none")]
474 approval_policy: Option<ApprovalPolicy>,
475 #[serde(skip_serializing_if = "Option::is_none")]
476 sandbox: Option<SandboxMode>,
477 #[serde(skip_serializing_if = "Option::is_none")]
478 ephemeral: Option<bool>,
479 #[serde(flatten)]
480 extra: Map<String, Value>,
481}
482
483impl ThreadStartParams {
484 #[must_use]
487 pub fn new() -> Self {
488 Self::default()
489 }
490
491 #[must_use]
493 pub fn cwd(mut self, dir: impl Into<PathBuf>) -> Self {
494 self.cwd = Some(dir.into());
495 self
496 }
497
498 #[must_use]
500 pub fn model(mut self, model: impl Into<String>) -> Self {
501 self.model = Some(model.into());
502 self
503 }
504
505 #[must_use]
507 pub fn approval_policy(mut self, policy: ApprovalPolicy) -> Self {
508 self.approval_policy = Some(policy);
509 self
510 }
511
512 #[must_use]
514 pub fn sandbox(mut self, mode: SandboxMode) -> Self {
515 self.sandbox = Some(mode);
516 self
517 }
518
519 #[must_use]
521 pub fn ephemeral(mut self, ephemeral: bool) -> Self {
522 self.ephemeral = Some(ephemeral);
523 self
524 }
525
526 #[must_use]
529 pub fn param(mut self, name: impl Into<String>, value: Value) -> Self {
530 self.extra.insert(name.into(), value);
531 self
532 }
533}
534
535#[derive(Debug, Clone, Serialize)]
541#[serde(rename_all = "camelCase")]
542pub struct TurnStartParams {
543 thread_id: String,
544 input: Vec<UserInput>,
545 #[serde(skip_serializing_if = "Option::is_none")]
546 model: Option<String>,
547 #[serde(skip_serializing_if = "Option::is_none")]
548 effort: Option<String>,
549 #[serde(skip_serializing_if = "Option::is_none")]
550 output_schema: Option<Value>,
551 #[serde(skip_serializing_if = "Option::is_none")]
552 cwd: Option<PathBuf>,
553 #[serde(skip_serializing_if = "Option::is_none")]
554 approval_policy: Option<ApprovalPolicy>,
555 #[serde(flatten)]
556 extra: Map<String, Value>,
557}
558
559impl TurnStartParams {
560 #[must_use]
562 pub fn new(thread_id: impl Into<String>, input: Vec<UserInput>) -> Self {
563 Self {
564 thread_id: thread_id.into(),
565 input,
566 model: None,
567 effort: None,
568 output_schema: None,
569 cwd: None,
570 approval_policy: None,
571 extra: Map::new(),
572 }
573 }
574
575 #[must_use]
577 pub fn text(thread_id: impl Into<String>, prompt: impl Into<String>) -> Self {
578 Self::new(thread_id, vec![UserInput::text(prompt)])
579 }
580
581 #[must_use]
583 pub fn model(mut self, model: impl Into<String>) -> Self {
584 self.model = Some(model.into());
585 self
586 }
587
588 #[must_use]
591 pub fn effort(mut self, effort: impl Into<String>) -> Self {
592 self.effort = Some(effort.into());
593 self
594 }
595
596 #[must_use]
598 pub fn output_schema(mut self, schema: Value) -> Self {
599 self.output_schema = Some(schema);
600 self
601 }
602
603 #[must_use]
605 pub fn cwd(mut self, dir: impl Into<PathBuf>) -> Self {
606 self.cwd = Some(dir.into());
607 self
608 }
609
610 #[must_use]
612 pub fn approval_policy(mut self, policy: ApprovalPolicy) -> Self {
613 self.approval_policy = Some(policy);
614 self
615 }
616
617 #[must_use]
620 pub fn param(mut self, name: impl Into<String>, value: Value) -> Self {
621 self.extra.insert(name.into(), value);
622 self
623 }
624}
625
626struct RpcFailure {
628 code: i64,
629 message: String,
630 data: Option<Value>,
631}
632
633#[derive(Debug, Clone)]
635enum Closed {
636 Eof,
638 OutputLimit { limit_bytes: usize },
640 Broken(String),
642 Terminated,
644}
645
646enum Reply {
648 Result(Value),
649 Rpc(RpcFailure),
650 Malformed,
652 Closed(Closed),
653}
654
655enum Event {
657 Message(ServerMessage),
658 Closed(Closed),
659}
660
661enum Outgoing {
663 Line(Vec<u8>),
664 Close,
666}
667
668struct State {
669 pending: HashMap<i64, oneshot::Sender<Reply>>,
670 closed: Option<Closed>,
671}
672
673struct Shared {
675 state: Mutex<State>,
676 next_id: AtomicI64,
677 stderr_tail: Mutex<Vec<u8>>,
678 stderr_done: AtomicBool,
681 stderr_finished: Notify,
682 kill: Mutex<Option<KillTarget>>,
686 events: mpsc::UnboundedSender<Event>,
687}
688
689fn locked<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
690 mutex.lock().unwrap_or_else(PoisonError::into_inner)
694}
695
696impl Shared {
697 fn fail(&self, reason: Closed) {
700 let pending = {
701 let mut state = locked(&self.state);
702 if state.closed.is_some() {
703 return;
704 }
705 state.closed = Some(reason.clone());
706 std::mem::take(&mut state.pending)
707 };
708 for (_, waiter) in pending {
709 let _ = waiter.send(Reply::Closed(reason.clone()));
710 }
711 let _ = self.events.send(Event::Closed(reason));
712 }
713
714 fn new(events: mpsc::UnboundedSender<Event>, kill: Option<KillTarget>) -> Self {
715 Self {
716 state: Mutex::new(State {
717 pending: HashMap::new(),
718 closed: None,
719 }),
720 next_id: AtomicI64::new(0),
721 stderr_tail: Mutex::new(Vec::new()),
722 stderr_done: AtomicBool::new(false),
723 stderr_finished: Notify::new(),
724 kill: Mutex::new(kill),
725 events,
726 }
727 }
728
729 fn fire_kill(&self) {
732 if let Some(target) = *locked(&self.kill) {
735 target.signal();
736 }
737 }
738
739 fn revoke_kill(&self) {
742 *locked(&self.kill) = None;
743 }
744
745 async fn stderr_settled(&self) {
750 let wait = async {
751 loop {
752 let notified = self.stderr_finished.notified();
753 if self.stderr_done.load(Ordering::Acquire) {
754 return;
755 }
756 notified.await;
757 }
758 };
759 let _ = tokio::time::timeout(STDERR_SETTLE, wait).await;
760 }
761
762 fn stderr_summary(&self) -> String {
764 let tail = locked(&self.stderr_tail);
765 let text = strip_ansi(&String::from_utf8_lossy(&tail));
766 let lines: Vec<&str> = text
767 .lines()
768 .map(str::trim)
769 .filter(|line| !line.is_empty())
770 .collect();
771 let start = lines.len().saturating_sub(5);
772 lines[start..].join("\n")
773 }
774
775 fn error_for(&self, reason: &Closed, method: Option<&str>) -> Error {
776 let protocol = |message: String| Error::AppServerProtocol { message };
777 match reason {
778 Closed::OutputLimit { limit_bytes } => Error::OutputLimitExceeded {
779 stream: OutputStream::Stdout,
780 limit_bytes: *limit_bytes,
781 },
782 Closed::Terminated => protocol("the app-server session was ended by the client".into()),
783 Closed::Broken(message) => protocol(message.clone()),
784 Closed::Eof => {
785 let stderr = self.stderr_summary();
786 let while_waiting =
787 method.map_or_else(String::new, |m| format!(" before answering `{m}`"));
788 if stderr.is_empty() {
789 protocol(format!("codex app-server closed its output{while_waiting}"))
790 } else {
791 protocol(format!(
792 "codex app-server closed its output{while_waiting}; stderr: {stderr}"
793 ))
794 }
795 }
796 }
797 }
798}
799
800fn strip_ansi(text: &str) -> String {
802 let mut out = String::with_capacity(text.len());
803 let mut chars = text.chars().peekable();
804 while let Some(c) = chars.next() {
805 if c == '\u{1b}' && chars.peek() == Some(&'[') {
806 chars.next();
807 for c in chars.by_ref() {
808 if c.is_ascii_alphabetic() {
809 break;
810 }
811 }
812 } else {
813 out.push(c);
814 }
815 }
816 out
817}
818
819struct PendingSlot<'a> {
822 shared: &'a Shared,
823 id: i64,
824}
825
826impl Drop for PendingSlot<'_> {
827 fn drop(&mut self) {
828 locked(&self.shared.state).pending.remove(&self.id);
829 }
830}
831
832fn json_error(context: &str, source: serde_json::Error) -> Error {
833 Error::Json {
834 message: format!("{context}: {source}"),
835 source,
836 }
837}
838
839fn request_line(id: i64, method: &str, params: &Value) -> Result<Vec<u8>> {
840 let method = serde_json::to_string(method).map_err(|e| json_error("method name", e))?;
841 let mut line = format!("{{\"id\":{id},\"method\":{method}");
842 if !params.is_null() {
843 let params = serde_json::to_string(params).map_err(|e| json_error("request params", e))?;
844 line.push_str(",\"params\":");
845 line.push_str(¶ms);
846 }
847 line.push_str("}\n");
848 Ok(line.into_bytes())
849}
850
851fn notification_line(method: &str, params: &Value) -> Result<Vec<u8>> {
852 let method = serde_json::to_string(method).map_err(|e| json_error("method name", e))?;
853 let mut line = format!("{{\"method\":{method}");
854 if !params.is_null() {
855 let params =
856 serde_json::to_string(params).map_err(|e| json_error("notification params", e))?;
857 line.push_str(",\"params\":");
858 line.push_str(¶ms);
859 }
860 line.push_str("}\n");
861 Ok(line.into_bytes())
862}
863
864fn reply_line(id: &RequestId, body_key: &str, body: &Value) -> Result<Vec<u8>> {
865 let id = serde_json::to_string(id).map_err(|e| json_error("request id", e))?;
866 let body = serde_json::to_string(body).map_err(|e| json_error("reply body", e))?;
867 Ok(format!("{{\"id\":{id},\"{body_key}\":{body}}}\n").into_bytes())
868}
869
870#[derive(Clone)]
877pub struct AppServerHandle {
878 shared: Arc<Shared>,
879 writer: mpsc::UnboundedSender<Outgoing>,
880 timeout: Option<Duration>,
881}
882
883impl std::fmt::Debug for AppServerHandle {
884 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
885 f.debug_struct("AppServerHandle")
886 .field("timeout", &self.timeout)
887 .finish_non_exhaustive()
888 }
889}
890
891impl AppServerHandle {
892 fn closed_error(&self, method: Option<&str>) -> Error {
893 let reason = locked(&self.shared.state).closed.clone();
894 match reason {
895 Some(reason) => self.shared.error_for(&reason, method),
896 None => Error::AppServerProtocol {
897 message: "codex app-server is no longer accepting messages (its stdin is closed)"
898 .into(),
899 },
900 }
901 }
902
903 fn enqueue(&self, line: Vec<u8>, method: Option<&str>) -> Result<()> {
904 if let Some(reason) = &locked(&self.shared.state).closed {
905 return Err(self.shared.error_for(reason, method));
906 }
907 self.writer
908 .send(Outgoing::Line(line))
909 .map_err(|_| self.closed_error(method))
910 }
911
912 pub async fn request(&self, method: &str, params: Value) -> Result<Value> {
924 let id = self.shared.next_id.fetch_add(1, Ordering::Relaxed);
925 let line = request_line(id, method, ¶ms)?;
926 let (waiter, answer) = oneshot::channel();
927 {
928 let mut state = locked(&self.shared.state);
929 if let Some(reason) = &state.closed {
930 return Err(self.shared.error_for(reason, Some(method)));
931 }
932 state.pending.insert(id, waiter);
933 }
934 let _slot = PendingSlot {
935 shared: &self.shared,
936 id,
937 };
938 self.writer
939 .send(Outgoing::Line(line))
940 .map_err(|_| self.closed_error(Some(method)))?;
941
942 let reply = match self.timeout {
943 Some(limit) => {
944 tokio::time::timeout(limit, answer)
945 .await
946 .map_err(|_| Error::Timeout {
947 timeout_seconds: limit.as_secs(),
948 })?
949 }
950 None => answer.await,
951 };
952 match reply {
953 Ok(Reply::Result(result)) => Ok(result),
954 Ok(Reply::Rpc(failure)) => Err(Error::AppServerRpc {
955 method: method.to_string(),
956 code: failure.code,
957 message: failure.message,
958 data: failure.data,
959 }),
960 Ok(Reply::Malformed) => Err(Error::AppServerProtocol {
961 message: format!(
962 "codex app-server answered `{method}` with neither result nor error"
963 ),
964 }),
965 Ok(Reply::Closed(reason)) => Err(self.shared.error_for(&reason, Some(method))),
966 Err(_) => Err(self.closed_error(Some(method))),
967 }
968 }
969
970 pub fn notify(&self, method: &str, params: Value) -> Result<()> {
977 self.enqueue(notification_line(method, ¶ms)?, Some(method))
978 }
979
980 pub fn respond(&self, id: RequestId, result: Value) -> Result<()> {
987 self.enqueue(reply_line(&id, "result", &result)?, None)
988 }
989
990 pub fn respond_error(
998 &self,
999 id: RequestId,
1000 code: i64,
1001 message: impl Into<String>,
1002 ) -> Result<()> {
1003 let body = json!({ "code": code, "message": message.into() });
1004 self.enqueue(reply_line(&id, "error", &body)?, None)
1005 }
1006
1007 pub async fn thread_start(&self, params: ThreadStartParams) -> Result<Thread> {
1014 let params =
1015 serde_json::to_value(params).map_err(|e| json_error("thread/start params", e))?;
1016 let raw = self.request("thread/start", params).await?;
1017 let id = raw
1018 .pointer("/thread/id")
1019 .and_then(Value::as_str)
1020 .ok_or_else(|| Error::AppServerProtocol {
1021 message: "thread/start returned no thread id".into(),
1022 })?
1023 .to_string();
1024 let model = raw.get("model").and_then(Value::as_str).map(str::to_string);
1025 Ok(Thread { id, model, raw })
1026 }
1027
1028 pub async fn turn_start(&self, params: TurnStartParams) -> Result<Turn> {
1036 let params =
1037 serde_json::to_value(params).map_err(|e| json_error("turn/start params", e))?;
1038 let result = self.request("turn/start", params).await?;
1039 let turn = result.get("turn").cloned().unwrap_or(Value::Null);
1040 serde_json::from_value(turn).map_err(|e| Error::AppServerProtocol {
1041 message: format!("turn/start returned no usable turn: {e}"),
1042 })
1043 }
1044
1045 pub async fn turn_steer(
1058 &self,
1059 thread_id: &str,
1060 expected_turn_id: &str,
1061 input: Vec<UserInput>,
1062 ) -> Result<String> {
1063 let params = json!({
1064 "threadId": thread_id,
1065 "expectedTurnId": expected_turn_id,
1066 "input": input,
1067 });
1068 let result = self.request("turn/steer", params).await?;
1069 result
1070 .get("turnId")
1071 .and_then(Value::as_str)
1072 .map(str::to_string)
1073 .ok_or_else(|| Error::AppServerProtocol {
1074 message: "turn/steer returned no turn id".into(),
1075 })
1076 }
1077
1078 pub async fn turn_interrupt(&self, thread_id: &str, turn_id: &str) -> Result<()> {
1090 let params = json!({ "threadId": thread_id, "turnId": turn_id });
1091 self.request("turn/interrupt", params).await.map(|_| ())
1092 }
1093}
1094
1095#[derive(Debug, Clone)]
1099pub struct AppServerBuilder<'a> {
1100 codex: &'a Codex,
1101 client_name: String,
1102 client_version: String,
1103 opt_out: Vec<String>,
1104}
1105
1106impl<'a> AppServerBuilder<'a> {
1107 #[must_use]
1111 pub fn client_info(mut self, name: impl Into<String>, version: impl Into<String>) -> Self {
1112 self.client_name = name.into();
1113 self.client_version = version.into();
1114 self
1115 }
1116
1117 #[must_use]
1121 pub fn opt_out_notification(mut self, method: impl Into<String>) -> Self {
1122 self.opt_out.push(method.into());
1123 self
1124 }
1125
1126 #[must_use]
1132 pub fn args(&self) -> Vec<String> {
1133 vec!["app-server".into(), "--listen".into(), "stdio://".into()]
1134 }
1135
1136 #[must_use]
1139 pub fn to_command_string(&self) -> String {
1140 crate::exec::command_string(self.codex, self.args())
1141 }
1142
1143 pub async fn start(self) -> Result<AppServer> {
1157 let codex = self.codex;
1158 let operation_args = self.args();
1159 let span = crate::exec::command_span("codex.app_server", codex, &operation_args);
1160 let args = crate::exec::assemble_args(codex, operation_args);
1161 let command_text = format!("{} {}", codex.binary.display(), args.join(" "));
1162 debug!(arg_count = args.len(), "starting codex app-server");
1163
1164 let mut outcome = SpanOutcome::start(span.clone());
1165 let mut command = Command::new(&codex.binary);
1166 command.args(&args);
1167 command.stdin(std::process::Stdio::piped());
1168 command.stdout(std::process::Stdio::piped());
1169 command.stderr(std::process::Stdio::piped());
1170 command.kill_on_drop(true);
1173 crate::exec::own_process_group(&mut command, codex.process_group);
1174 crate::exec::apply_die_with_parent(&mut command, codex.die_with_parent);
1175 if let Some(dir) = &codex.working_dir {
1176 command.current_dir(dir);
1177 }
1178 crate::exec::apply_child_environment(&mut command, codex.clear_env, &codex.env);
1179
1180 let mut child = match command.spawn() {
1181 Ok(child) => child,
1182 Err(e) => {
1183 outcome.settle("error", None);
1184 return Err(Error::Io {
1185 message: format!("failed to spawn codex app-server: {e}"),
1186 source: e,
1187 working_dir: codex.working_dir.clone(),
1188 });
1189 }
1190 };
1191 let group = crate::exec::arm_and_notify(
1192 codex.process_group,
1193 codex.termination_signal,
1194 child.id(),
1195 codex.on_spawn.as_ref(),
1196 );
1197 let pid = child.id();
1198
1199 let stdin = child.stdin.take().expect("stdin was configured as piped");
1200 let stdout = child.stdout.take().expect("stdout was configured as piped");
1201 let stderr = child.stderr.take().expect("stderr was configured as piped");
1202
1203 let (events_tx, events_rx) = mpsc::unbounded_channel();
1204 let (writer_tx, writer_rx) = mpsc::unbounded_channel();
1205 let shared = Arc::new(Shared::new(
1206 events_tx,
1207 Some(KillTarget {
1208 pid,
1209 group: codex.process_group,
1210 }),
1211 ));
1212
1213 tokio::spawn(read_stdout(
1214 stdout,
1215 Arc::clone(&shared),
1216 codex.output_limit,
1217 codex.working_dir.clone(),
1218 ));
1219 tokio::spawn(drain_stderr(stderr, Arc::clone(&shared)));
1220 tokio::spawn(write_stdin(stdin, writer_rx, Arc::clone(&shared)));
1221
1222 let handle = AppServerHandle {
1223 shared,
1224 writer: writer_tx,
1225 timeout: codex.timeout,
1226 };
1227 let mut server = AppServer {
1228 handle,
1229 events: events_rx,
1230 finished: false,
1231 child,
1232 group,
1233 outcome,
1234 termination_grace: codex.termination_grace,
1235 working_dir: codex.working_dir.clone(),
1236 command: command_text,
1237 info: ServerInfo::default(),
1238 };
1239
1240 let handshake = initialize(
1241 &server.handle,
1242 &self.client_name,
1243 &self.client_version,
1244 &self.opt_out,
1245 )
1246 .instrument(span)
1247 .await;
1248 match handshake {
1249 Ok(info) => {
1250 server.info = info;
1251 Ok(server)
1252 }
1253 Err(error) => Err(server.abandon(error).await),
1254 }
1255 }
1256}
1257
1258async fn initialize(
1259 handle: &AppServerHandle,
1260 name: &str,
1261 version: &str,
1262 opt_out: &[String],
1263) -> Result<ServerInfo> {
1264 let mut params = json!({ "clientInfo": { "name": name, "version": version } });
1265 if !opt_out.is_empty() {
1266 params["capabilities"] = json!({ "optOutNotificationMethods": opt_out });
1267 }
1268 let result = handle.request("initialize", params).await?;
1269 let info = serde_json::from_value(result).map_err(|e| Error::AppServerProtocol {
1270 message: format!("initialize returned an unexpected response: {e}"),
1271 })?;
1272 handle.notify("initialized", Value::Null)?;
1273 Ok(info)
1274}
1275
1276#[derive(Clone, Copy)]
1278struct KillTarget {
1279 pid: Option<u32>,
1280 group: bool,
1281}
1282
1283impl KillTarget {
1284 fn signal(self) {
1290 #[cfg(unix)]
1291 if let Some(pid) = self.pid {
1292 if self.group {
1293 crate::exec::signal_group(pid, libc::SIGKILL);
1294 } else if let Ok(pid) = i32::try_from(pid) {
1295 unsafe {
1299 libc::kill(pid, libc::SIGKILL);
1300 }
1301 }
1302 }
1303 #[cfg(not(unix))]
1306 let _ = (self.pid, self.group);
1307 }
1308}
1309
1310async fn read_stdout(
1313 stdout: ChildStdout,
1314 shared: Arc<Shared>,
1315 output_limit: Option<usize>,
1316 working_dir: Option<PathBuf>,
1317) {
1318 let mut reader = BufReader::new(stdout);
1319 let mut captured = 0usize;
1320 let reason = loop {
1321 let line = match crate::streaming::read_bounded_line(
1322 &mut reader,
1323 &mut captured,
1324 output_limit,
1325 OutputStream::Stdout,
1326 &working_dir,
1327 )
1328 .await
1329 {
1330 Ok(Some(line)) => line,
1331 Ok(None) => {
1332 shared.stderr_settled().await;
1333 break Closed::Eof;
1334 }
1335 Err(Error::OutputLimitExceeded { limit_bytes, .. }) => {
1336 shared.fire_kill();
1337 break Closed::OutputLimit { limit_bytes };
1338 }
1339 Err(error) => {
1340 shared.fire_kill();
1341 break Closed::Broken(error.to_string());
1342 }
1343 };
1344 if !line.trim_start().starts_with('{') {
1345 debug!(
1346 bytes = line.len(),
1347 "ignoring a non-JSON line from codex app-server"
1348 );
1349 continue;
1350 }
1351 if let Err(reason) = route(&line, &shared) {
1352 shared.fire_kill();
1353 break reason;
1354 }
1355 };
1356 shared.fail(reason);
1357}
1358
1359fn route(line: &str, shared: &Shared) -> std::result::Result<(), Closed> {
1361 let value: Value = serde_json::from_str(line).map_err(|e| {
1362 let head: String = line.chars().take(120).collect();
1363 Closed::Broken(format!("codex app-server sent invalid JSON ({e}): {head}"))
1364 })?;
1365 let method = value.get("method").and_then(Value::as_str);
1366 let id = value.get("id");
1367 match (method, id) {
1368 (Some(method), Some(id)) => {
1369 let Ok(id) = serde_json::from_value::<RequestId>(id.clone()) else {
1370 warn!(
1371 method_bytes = method.len(),
1372 "ignoring a server request with an unusable id"
1373 );
1374 return Ok(());
1375 };
1376 let request = ServerRequest {
1377 id,
1378 method: method.to_string(),
1379 params: value.get("params").cloned().unwrap_or(Value::Null),
1380 };
1381 let _ = shared
1382 .events
1383 .send(Event::Message(ServerMessage::Request(request)));
1384 }
1385 (Some(method), None) => {
1386 let notification = Notification {
1387 method: method.to_string(),
1388 params: value.get("params").cloned().unwrap_or(Value::Null),
1389 };
1390 let _ = shared
1391 .events
1392 .send(Event::Message(ServerMessage::Notification(notification)));
1393 }
1394 (None, Some(id)) if value.get("result").is_some() || value.get("error").is_some() => {
1395 deliver_answer(&value, id, shared);
1396 }
1397 (None, Some(id)) => {
1398 let waiter = id
1402 .as_i64()
1403 .and_then(|id| locked(&shared.state).pending.remove(&id));
1404 match waiter {
1405 Some(waiter) => {
1406 let _ = waiter.send(Reply::Malformed);
1407 }
1408 None => warn!("ignoring an answer with neither result nor error"),
1409 }
1410 }
1411 _ => warn!("ignoring a JSON object from codex app-server that is not a message"),
1412 }
1413 Ok(())
1414}
1415
1416fn deliver_answer(value: &Value, id: &Value, shared: &Shared) {
1417 let Some(id) = id.as_i64() else {
1418 debug!("ignoring an answer with no request id");
1420 return;
1421 };
1422 let waiter = locked(&shared.state).pending.remove(&id);
1423 let Some(waiter) = waiter else {
1424 debug!(id, "ignoring an answer nobody is waiting for");
1426 return;
1427 };
1428 let reply = match value.get("error") {
1429 Some(error) => Reply::Rpc(RpcFailure {
1430 code: error.get("code").and_then(Value::as_i64).unwrap_or(0),
1431 message: error
1432 .get("message")
1433 .and_then(Value::as_str)
1434 .unwrap_or_default()
1435 .to_string(),
1436 data: error.get("data").cloned(),
1437 }),
1438 None => Reply::Result(value.get("result").cloned().unwrap_or(Value::Null)),
1439 };
1440 let _ = waiter.send(reply);
1441}
1442
1443async fn drain_stderr(mut stderr: ChildStderr, shared: Arc<Shared>) {
1446 let mut buffer = [0u8; 4096];
1447 loop {
1448 match stderr.read(&mut buffer).await {
1449 Ok(0) | Err(_) => {
1450 shared.stderr_done.store(true, Ordering::Release);
1451 shared.stderr_finished.notify_waiters();
1452 break;
1453 }
1454 Ok(read) => {
1455 let mut tail = locked(&shared.stderr_tail);
1456 tail.extend_from_slice(&buffer[..read]);
1457 if tail.len() > STDERR_TAIL_BYTES {
1458 let excess = tail.len() - STDERR_TAIL_BYTES;
1459 tail.drain(..excess);
1460 }
1461 }
1462 }
1463 }
1464}
1465
1466async fn write_stdin<W: AsyncWrite + Unpin>(
1471 mut stdin: W,
1472 mut lines: mpsc::UnboundedReceiver<Outgoing>,
1473 shared: Arc<Shared>,
1474) {
1475 while let Some(outgoing) = lines.recv().await {
1476 match outgoing {
1477 Outgoing::Line(line) => {
1478 let written = async {
1479 stdin.write_all(&line).await?;
1480 stdin.flush().await
1481 }
1482 .await;
1483 if let Err(error) = written {
1484 if error.kind() == std::io::ErrorKind::BrokenPipe {
1485 debug!("codex app-server closed its stdin");
1492 } else {
1493 shared.fail(Closed::Broken(format!(
1494 "failed to write to codex app-server stdin: {error}"
1495 )));
1496 }
1497 break;
1498 }
1499 }
1500 Outgoing::Close => break,
1501 }
1502 }
1503 }
1506
1507pub struct AppServer {
1518 handle: AppServerHandle,
1519 events: mpsc::UnboundedReceiver<Event>,
1520 finished: bool,
1521 child: Child,
1522 group: GroupKillGuard,
1523 outcome: SpanOutcome,
1524 termination_grace: Duration,
1525 working_dir: Option<PathBuf>,
1526 command: String,
1527 info: ServerInfo,
1528}
1529
1530impl std::fmt::Debug for AppServer {
1531 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1532 f.debug_struct("AppServer")
1533 .field("pid", &self.child.id())
1534 .field("info", &self.info)
1535 .finish_non_exhaustive()
1536 }
1537}
1538
1539impl Deref for AppServer {
1540 type Target = AppServerHandle;
1541
1542 fn deref(&self) -> &AppServerHandle {
1543 &self.handle
1544 }
1545}
1546
1547impl AppServer {
1548 #[must_use]
1550 pub fn builder(codex: &Codex) -> AppServerBuilder<'_> {
1551 AppServerBuilder {
1552 codex,
1553 client_name: "codex-wrapper".to_string(),
1554 client_version: env!("CARGO_PKG_VERSION").to_string(),
1555 opt_out: Vec::new(),
1556 }
1557 }
1558
1559 #[must_use]
1561 pub fn server_info(&self) -> &ServerInfo {
1562 &self.info
1563 }
1564
1565 #[must_use]
1567 pub fn pid(&self) -> Option<u32> {
1568 self.child.id()
1569 }
1570
1571 #[must_use]
1573 pub fn handle(&self) -> AppServerHandle {
1574 self.handle.clone()
1575 }
1576
1577 pub async fn next_message(&mut self) -> Result<Option<ServerMessage>> {
1591 if self.finished {
1592 return Ok(None);
1593 }
1594 match self.events.recv().await {
1595 Some(Event::Message(message)) => Ok(Some(message)),
1596 Some(Event::Closed(reason)) => {
1597 self.finished = true;
1598 match reason {
1599 Closed::Eof | Closed::Terminated => Ok(None),
1600 reason => {
1601 let _ = self.child.start_kill();
1605 Err(self.handle.shared.error_for(&reason, None))
1606 }
1607 }
1608 }
1609 None => {
1610 self.finished = true;
1611 Ok(None)
1612 }
1613 }
1614 }
1615
1616 pub async fn shutdown(mut self) -> Result<()> {
1629 self.handle.shared.revoke_kill();
1632 let _ = self.handle.writer.send(Outgoing::Close);
1633 match tokio::time::timeout(self.termination_grace, self.child.wait()).await {
1634 Ok(Ok(status)) => {
1635 self.group.disarm();
1636 self.handle.shared.stderr_settled().await;
1637 self.handle.shared.fail(Closed::Terminated);
1638 let code = status.code().unwrap_or(-1);
1639 if status.success() {
1640 self.outcome.settle("ok", Some(code));
1641 return Ok(());
1642 }
1643 self.outcome.settle("failed", Some(code));
1644 Err(Error::from_command_failure(
1645 self.command.clone(),
1646 code,
1647 String::new(),
1648 self.handle.shared.stderr_summary(),
1649 self.working_dir.clone(),
1650 ))
1651 }
1652 Ok(Err(error)) => Err(Error::Io {
1653 message: format!("failed to wait on codex app-server: {error}"),
1654 source: error,
1655 working_dir: self.working_dir.clone(),
1656 }),
1657 Err(_) => self.terminate().await,
1658 }
1659 }
1660
1661 pub async fn terminate(mut self) -> Result<()> {
1676 self.handle.shared.revoke_kill();
1677 self.handle.shared.fail(Closed::Terminated);
1678 let result = crate::exec::terminate_and_reap(
1679 &mut self.child,
1680 &mut self.group,
1681 self.termination_grace,
1682 self.working_dir.as_deref(),
1683 )
1684 .await;
1685 self.outcome.settle("cancelled", None);
1686 result
1687 }
1688
1689 async fn abandon(mut self, error: Error) -> Error {
1691 self.handle.shared.revoke_kill();
1692 let outcome = if matches!(error, Error::Timeout { .. }) {
1693 "timeout"
1694 } else {
1695 "failed"
1696 };
1697 let by_server = matches!(locked(&self.handle.shared.state).closed, Some(Closed::Eof));
1701
1702 let ended = if by_server {
1706 tokio::time::timeout(STARTUP_EXIT_WAIT, self.child.wait())
1707 .await
1708 .ok()
1709 } else {
1710 self.child.try_wait().transpose()
1711 };
1712 if let Some(Ok(status)) = ended {
1713 self.group.disarm();
1716 self.handle.shared.stderr_settled().await;
1717 let code = status.code().unwrap_or(-1);
1718 self.outcome.settle(outcome, Some(code));
1719 if by_server && !status.success() {
1720 return Error::from_command_failure(
1724 self.command.clone(),
1725 code,
1726 String::new(),
1727 self.handle.shared.stderr_summary(),
1728 self.working_dir.clone(),
1729 );
1730 }
1731 return error;
1732 }
1733
1734 self.handle.shared.fail(Closed::Terminated);
1735 let _ = crate::exec::terminate_and_reap(
1736 &mut self.child,
1737 &mut self.group,
1738 self.termination_grace,
1739 self.working_dir.as_deref(),
1740 )
1741 .await;
1742 self.outcome.settle(outcome, None);
1743 error
1744 }
1745}
1746
1747impl Drop for AppServer {
1748 fn drop(&mut self) {
1749 self.handle.shared.revoke_kill();
1752 }
1753}
1754
1755#[cfg(all(test, unix))]
1756mod tests {
1757 use super::*;
1758 use crate::CodexBuilder;
1759 use crate::test_support::{PidFile, is_running_for_test, wait_until_gone};
1760
1761 fn fake(mode: &str) -> CodexBuilder {
1762 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1763 .join("tests")
1764 .join("fake-app-server.sh");
1765 Codex::builder()
1766 .binary("/bin/bash")
1767 .arg(script.to_str().expect("fixture path is utf-8"))
1768 .env("FAKE_APP_SERVER_MODE", mode)
1769 .termination_grace(Duration::from_millis(100))
1771 .timeout(Duration::from_secs(20))
1773 }
1774
1775 async fn started(mode: &str) -> AppServer {
1776 let codex = fake(mode).build().expect("bash must exist");
1777 AppServer::builder(&codex)
1778 .start()
1779 .await
1780 .expect("the fake server starts")
1781 }
1782
1783 async fn until_turn_completed(server: &mut AppServer) -> (TurnCompleted, Vec<ServerMessage>) {
1785 let mut seen = Vec::new();
1786 loop {
1787 let message = tokio::time::timeout(Duration::from_secs(10), server.next_message())
1788 .await
1789 .expect("the turn should finish")
1790 .expect("no stream error")
1791 .expect("the server should not close first");
1792 let done = match &message {
1793 ServerMessage::Notification(n) => n.turn_completed(),
1794 _ => None,
1795 };
1796 seen.push(message);
1797 if let Some(done) = done {
1798 return (done, seen);
1799 }
1800 }
1801 }
1802
1803 fn methods(seen: &[ServerMessage]) -> Vec<&str> {
1804 seen.iter()
1805 .map(|message| match message {
1806 ServerMessage::Notification(n) => n.method.as_str(),
1807 ServerMessage::Request(r) => r.method.as_str(),
1808 })
1809 .collect()
1810 }
1811
1812 #[tokio::test]
1813 async fn the_handshake_reports_the_server_and_delivers_unsolicited_notifications() {
1814 let mut server = started("turn").await;
1815 assert!(server.server_info().user_agent.contains("0.149.0"));
1816 assert_eq!(
1817 server.server_info().codex_home.as_deref(),
1818 Some("/home/user/.codex")
1819 );
1820
1821 let first = server.next_message().await.unwrap().unwrap();
1823 let ServerMessage::Notification(notification) = first else {
1824 panic!("expected a notification, got {first:?}");
1825 };
1826 assert_eq!(notification.method, "remoteControl/status/changed");
1827 assert_eq!(notification.params["status"], "disabled");
1828 server.shutdown().await.unwrap();
1829 }
1830
1831 #[tokio::test]
1832 async fn a_turn_runs_to_completion_and_yields_its_final_message() {
1833 let mut server = started("turn").await;
1834 let thread = server
1835 .thread_start(
1836 ThreadStartParams::new()
1837 .cwd("/tmp/fixture")
1838 .ephemeral(true)
1839 .approval_policy(ApprovalPolicy::Never)
1840 .sandbox(SandboxMode::ReadOnly),
1841 )
1842 .await
1843 .unwrap();
1844 assert_eq!(thread.id, "01a0d1a2-5f2e-7263-a97b-cabf3e78caff");
1845 assert_eq!(thread.model.as_deref(), Some("gpt-5.6-sol"));
1846
1847 let turn = server
1848 .turn_start(TurnStartParams::text(&thread.id, "say ok"))
1849 .await
1850 .unwrap();
1851 assert_eq!(turn.status, TurnStatus::InProgress);
1852 assert_eq!(turn.id, "01a0d1a2-5f9f-75c1-9305-fa382e7b37bc");
1853
1854 let (done, seen) = until_turn_completed(&mut server).await;
1855 assert_eq!(done.thread_id, thread.id);
1856 assert_eq!(done.turn.id, turn.id);
1857 assert_eq!(done.turn.status, TurnStatus::Completed);
1858 assert_eq!(done.turn.final_message(), Some("ok"));
1859 let methods = methods(&seen);
1860 assert!(methods.contains(&"thread/started"));
1861 assert!(methods.contains(&"turn/started"));
1862 assert!(methods.contains(&"item/agentMessage/delta"));
1863 server.shutdown().await.unwrap();
1864 }
1865
1866 #[tokio::test]
1867 async fn steering_adds_input_to_the_running_turn() {
1868 let mut server = started("held").await;
1869 let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
1870 let turn = server
1871 .turn_start(TurnStartParams::text(&thread.id, "sleep, then say DONE"))
1872 .await
1873 .unwrap();
1874
1875 let steered = server
1876 .turn_steer(
1877 &thread.id,
1878 &turn.id,
1879 vec![UserInput::text("Also append STEERED")],
1880 )
1881 .await
1882 .unwrap();
1883 assert_eq!(steered, turn.id);
1884
1885 let (done, seen) = until_turn_completed(&mut server).await;
1886 assert_eq!(done.turn.final_message(), Some("DONE STEERED"));
1887 let echoed = seen.iter().any(|message| match message {
1890 ServerMessage::Notification(n) => {
1891 n.method == "item/completed"
1892 && n.params.pointer("/item/content/0/text")
1893 == Some(&json!("Also append STEERED"))
1894 }
1895 _ => false,
1896 });
1897 assert!(echoed, "the server never saw the steered text: {seen:?}");
1898 server.shutdown().await.unwrap();
1899 }
1900
1901 #[tokio::test]
1902 async fn steering_from_another_task_while_events_are_read() {
1903 let mut server = started("held").await;
1904 let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
1905 let turn = server
1906 .turn_start(TurnStartParams::text(&thread.id, "go"))
1907 .await
1908 .unwrap();
1909
1910 let handle = server.handle();
1911 let (thread_id, turn_id) = (thread.id.clone(), turn.id.clone());
1912 let steer = tokio::spawn(async move {
1913 handle
1914 .turn_steer(&thread_id, &turn_id, vec![UserInput::text("more")])
1915 .await
1916 });
1917
1918 let (done, _) = until_turn_completed(&mut server).await;
1919 assert_eq!(done.turn.status, TurnStatus::Completed);
1920 assert_eq!(steer.await.unwrap().unwrap(), turn.id);
1921 server.shutdown().await.unwrap();
1922 }
1923
1924 #[tokio::test]
1925 async fn steering_the_wrong_turn_is_an_rpc_error_that_names_both_ids() {
1926 let server = started("held").await;
1927 let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
1928 let turn = server
1929 .turn_start(TurnStartParams::text(&thread.id, "go"))
1930 .await
1931 .unwrap();
1932
1933 let error = server
1934 .turn_steer(&thread.id, "not-the-turn", vec![UserInput::text("x")])
1935 .await
1936 .unwrap_err();
1937 match error {
1938 Error::AppServerRpc {
1939 method,
1940 code,
1941 message,
1942 ..
1943 } => {
1944 assert_eq!(method, "turn/steer");
1945 assert_eq!(code, -32600);
1946 assert_eq!(
1947 message,
1948 format!(
1949 "expected active turn id `not-the-turn` but found `{}`",
1950 turn.id
1951 )
1952 );
1953 }
1954 other => panic!("expected an rpc error, got {other:?}"),
1955 }
1956
1957 let error = server
1958 .turn_interrupt(&thread.id, "not-the-turn")
1959 .await
1960 .unwrap_err();
1961 assert!(
1962 matches!(&error, Error::AppServerRpc { message, .. }
1963 if message == &format!("expected active turn id not-the-turn but found {}", turn.id)),
1964 "{error:?}"
1965 );
1966 server.shutdown().await.unwrap();
1967 }
1968
1969 #[tokio::test]
1970 async fn steering_or_interrupting_with_no_active_turn_is_an_rpc_error() {
1971 let server = started("held").await;
1972 let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
1973
1974 let error = server
1975 .turn_steer(&thread.id, "any", vec![UserInput::text("x")])
1976 .await
1977 .unwrap_err();
1978 assert!(
1979 matches!(&error, Error::AppServerRpc { message, .. } if message == "no active turn to steer"),
1980 "{error:?}"
1981 );
1982 let error = server.turn_interrupt(&thread.id, "any").await.unwrap_err();
1983 assert!(
1984 matches!(&error, Error::AppServerRpc { message, .. } if message == "no active turn to interrupt"),
1985 "{error:?}"
1986 );
1987 server.shutdown().await.unwrap();
1988 }
1989
1990 #[tokio::test]
1994 async fn the_final_answer_is_available_when_turn_completed_carries_no_items() {
1995 let codex = fake("turn")
1996 .env("FAKE_APP_SERVER_ITEMS", "legacy")
1997 .build()
1998 .unwrap();
1999 let mut server = AppServer::builder(&codex).start().await.unwrap();
2000 let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2001 server
2002 .turn_start(TurnStartParams::text(&thread.id, "say ok"))
2003 .await
2004 .unwrap();
2005
2006 let (done, seen) = until_turn_completed(&mut server).await;
2007 assert_eq!(done.turn.status, TurnStatus::Completed);
2008 assert!(done.turn.items.is_empty());
2009 assert_eq!(done.turn.final_message(), None);
2010 let answer = seen
2011 .iter()
2012 .filter_map(|message| match message {
2013 ServerMessage::Notification(n) => n.agent_message(),
2014 _ => None,
2015 })
2016 .rfind(AgentMessage::is_final_answer)
2017 .expect("the item stream carries the answer");
2018 assert_eq!(answer.text, "ok");
2019 server.shutdown().await.unwrap();
2020 }
2021
2022 #[tokio::test]
2023 async fn interrupting_ends_the_turn_as_interrupted_with_no_final_message() {
2024 let mut server = started("held").await;
2025 let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2026 let turn = server
2027 .turn_start(TurnStartParams::text(&thread.id, "go"))
2028 .await
2029 .unwrap();
2030
2031 server.turn_interrupt(&thread.id, &turn.id).await.unwrap();
2032
2033 let (done, _) = until_turn_completed(&mut server).await;
2034 assert_eq!(done.turn.status, TurnStatus::Interrupted);
2035 assert!(done.turn.items.is_empty());
2036 assert_eq!(done.turn.final_message(), None);
2037 server.shutdown().await.unwrap();
2038 }
2039
2040 #[tokio::test]
2041 async fn a_server_request_is_delivered_and_the_reply_reaches_the_server() {
2042 let mut server = started("approval").await;
2043 let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2044 server
2045 .turn_start(TurnStartParams::text(&thread.id, "touch a file"))
2046 .await
2047 .unwrap();
2048
2049 let mut seen = Vec::new();
2050 let request = loop {
2051 let message = tokio::time::timeout(Duration::from_secs(10), server.next_message())
2052 .await
2053 .unwrap()
2054 .unwrap()
2055 .unwrap();
2056 if let ServerMessage::Request(request) = message {
2057 break request;
2058 }
2059 seen.push(message);
2060 };
2061 assert_eq!(request.method, "item/commandExecution/requestApproval");
2062 assert_eq!(request.id, RequestId::Number(0));
2063 assert_eq!(
2064 request.params["command"],
2065 "/bin/zsh -lc 'touch created.txt'"
2066 );
2067
2068 server
2069 .respond(request.id, json!({ "decision": "decline" }))
2070 .unwrap();
2071
2072 let (done, after) = until_turn_completed(&mut server).await;
2073 assert_eq!(done.turn.final_message(), Some("decision: decline"));
2075 assert!(methods(&after).contains(&"serverRequest/resolved"));
2076 server.shutdown().await.unwrap();
2077 }
2078
2079 #[tokio::test]
2080 async fn concurrent_requests_are_matched_to_their_answers_by_id() {
2081 let server = started("turn").await;
2082 let (first, second, unknown) = tokio::join!(
2083 server.thread_start(ThreadStartParams::new()),
2084 server.request("thread/start", json!({})),
2085 server.request("no/such/method", json!({})),
2086 );
2087 assert!(first.is_ok());
2088 assert!(second.unwrap().pointer("/thread/id").is_some());
2089 match unknown.unwrap_err() {
2090 Error::AppServerRpc { message, .. } => {
2091 assert!(
2092 message.contains("unknown variant `no/such/method`"),
2093 "{message}"
2094 );
2095 }
2096 other => panic!("expected an rpc error, got {other:?}"),
2097 }
2098 server.shutdown().await.unwrap();
2099 }
2100
2101 #[tokio::test]
2102 async fn a_second_initialize_is_rejected_by_the_server() {
2103 let server = started("turn").await;
2104 let error = server
2105 .request(
2106 "initialize",
2107 json!({ "clientInfo": { "name": "x", "version": "0" } }),
2108 )
2109 .await
2110 .unwrap_err();
2111 assert!(
2112 matches!(&error, Error::AppServerRpc { message, .. } if message == "Already initialized"),
2113 "{error:?}"
2114 );
2115 server.shutdown().await.unwrap();
2116 }
2117
2118 #[tokio::test]
2120 async fn requests_are_written_as_the_server_expects_them() {
2121 let log = std::env::temp_dir().join(format!(
2122 "codex-wrapper-{}-app-server-wire.log",
2123 std::process::id()
2124 ));
2125 let _ = std::fs::remove_file(&log);
2126 let codex = fake("held")
2127 .env("FAKE_APP_SERVER_LOG", log.to_str().unwrap())
2128 .build()
2129 .unwrap();
2130 let mut server = AppServer::builder(&codex)
2131 .client_info("probe", "1.2.3")
2132 .opt_out_notification("item/agentMessage/delta")
2133 .opt_out_notification("mcpServer/startupStatus/updated")
2134 .start()
2135 .await
2136 .unwrap();
2137 let thread = server
2138 .thread_start(
2139 ThreadStartParams::new()
2140 .cwd("/tmp/fixture")
2141 .model("gpt-5.6-sol")
2142 .approval_policy(ApprovalPolicy::Never)
2143 .sandbox(SandboxMode::ReadOnly)
2144 .ephemeral(true),
2145 )
2146 .await
2147 .unwrap();
2148 let schema = json!({ "type": "object", "required": ["answer"] });
2149 let turn = server
2150 .turn_start(
2151 TurnStartParams::text(&thread.id, "hi")
2152 .model("gpt-5.6-sol")
2153 .effort("low")
2154 .output_schema(schema.clone())
2155 .cwd("/tmp/fixture")
2156 .approval_policy(ApprovalPolicy::Never)
2157 .param("summary", json!("none")),
2158 )
2159 .await
2160 .unwrap();
2161 server
2162 .turn_steer(&thread.id, &turn.id, vec![UserInput::text("more")])
2163 .await
2164 .unwrap();
2165 let _ = until_turn_completed(&mut server).await;
2166 server.shutdown().await.unwrap();
2167
2168 let lines: Vec<Value> = std::fs::read_to_string(&log)
2169 .unwrap()
2170 .lines()
2171 .map(|line| serde_json::from_str(line).expect("every client line is JSON"))
2172 .collect();
2173 let _ = std::fs::remove_file(&log);
2174
2175 assert_eq!(
2176 lines[0],
2177 json!({
2178 "id": 0,
2179 "method": "initialize",
2180 "params": {
2181 "clientInfo": { "name": "probe", "version": "1.2.3" },
2182 "capabilities": {
2183 "optOutNotificationMethods": [
2184 "item/agentMessage/delta",
2185 "mcpServer/startupStatus/updated"
2186 ]
2187 }
2188 }
2189 })
2190 );
2191 assert_eq!(lines[1], json!({ "method": "initialized" }));
2192 assert_eq!(
2193 lines[2],
2194 json!({
2195 "id": 1,
2196 "method": "thread/start",
2197 "params": {
2198 "cwd": "/tmp/fixture",
2199 "model": "gpt-5.6-sol",
2200 "approvalPolicy": "never",
2201 "sandbox": "read-only",
2202 "ephemeral": true
2203 }
2204 })
2205 );
2206 assert_eq!(
2207 lines[3],
2208 json!({
2209 "id": 2,
2210 "method": "turn/start",
2211 "params": {
2212 "threadId": thread.id,
2213 "input": [{ "type": "text", "text": "hi", "text_elements": [] }],
2214 "model": "gpt-5.6-sol",
2215 "effort": "low",
2216 "outputSchema": schema,
2217 "cwd": "/tmp/fixture",
2218 "approvalPolicy": "never",
2219 "summary": "none"
2220 }
2221 })
2222 );
2223 assert_eq!(
2224 lines[4],
2225 json!({
2226 "id": 3,
2227 "method": "turn/steer",
2228 "params": {
2229 "threadId": thread.id,
2230 "expectedTurnId": turn.id,
2231 "input": [{ "type": "text", "text": "more", "text_elements": [] }]
2232 }
2233 })
2234 );
2235 }
2236
2237 #[tokio::test]
2242 async fn a_server_that_exits_cleanly_before_answering_fails_the_start_without_waiting() {
2243 let codex = fake("exit-clean")
2244 .termination_grace(Duration::from_secs(4))
2245 .build()
2246 .unwrap();
2247 let started_at = std::time::Instant::now();
2248 let error = AppServer::builder(&codex).start().await.unwrap_err();
2249 assert!(
2250 matches!(error, Error::AppServerProtocol { .. }),
2251 "{error:?}"
2252 );
2253 assert!(
2254 started_at.elapsed() < Duration::from_secs(3),
2255 "start waited out the grace period for a server that had already exited"
2256 );
2257 }
2258
2259 #[tokio::test]
2263 async fn invalid_json_during_the_handshake_is_reported_as_invalid_json() {
2264 let codex = fake("bad-init").build().unwrap();
2265 let error = AppServer::builder(&codex).start().await.unwrap_err();
2266 assert!(
2267 matches!(&error, Error::AppServerProtocol { message } if message.contains("invalid JSON")),
2268 "{error:?}"
2269 );
2270 assert_eq!(error.exit_code(), None);
2271 }
2272
2273 #[tokio::test]
2277 async fn a_response_with_neither_result_nor_error_fails_the_request_it_names() {
2278 let server = started("no-result").await;
2279 let error = server
2280 .thread_start(ThreadStartParams::new())
2281 .await
2282 .unwrap_err();
2283 assert!(
2284 matches!(&error, Error::AppServerProtocol { message }
2285 if message.contains("neither result nor error") && message.contains("thread/start")),
2286 "{error:?}"
2287 );
2288 assert!(server.notify("initialized", Value::Null).is_ok());
2290 server.shutdown().await.unwrap();
2291 }
2292
2293 #[tokio::test]
2297 async fn the_readers_kill_switch_is_revoked_when_the_client_is_done_with_the_child() {
2298 let sleeper = |seconds: &str| {
2300 std::process::Command::new("sleep")
2301 .arg(seconds)
2302 .spawn()
2303 .unwrap()
2304 };
2305 let (events, _received) = mpsc::unbounded_channel();
2306
2307 let mut live = sleeper("60");
2308 let shared = Shared::new(
2309 events.clone(),
2310 Some(KillTarget {
2311 pid: Some(live.id()),
2312 group: false,
2313 }),
2314 );
2315 shared.fire_kill();
2316 assert!(
2317 live.wait().unwrap().code().is_none(),
2318 "the switch should have killed the process it was armed with"
2319 );
2320
2321 let mut revoked = sleeper("60");
2322 let shared = Shared::new(
2323 events,
2324 Some(KillTarget {
2325 pid: Some(revoked.id()),
2326 group: false,
2327 }),
2328 );
2329 shared.revoke_kill();
2330 shared.fire_kill();
2331 std::thread::sleep(Duration::from_millis(200));
2332 assert!(
2333 revoked.try_wait().unwrap().is_none(),
2334 "a revoked switch still killed the process"
2335 );
2336 revoked.kill().unwrap();
2337 revoked.wait().unwrap();
2338 }
2339
2340 #[tokio::test]
2341 async fn every_way_of_ending_the_session_revokes_the_kill_switch() {
2342 let armed = |shared: &Shared| locked(&shared.kill).is_some();
2343
2344 let server = started("turn").await;
2345 let shared = Arc::clone(&server.handle.shared);
2346 assert!(armed(&shared));
2347 server.shutdown().await.unwrap();
2348 assert!(!armed(&shared), "shutdown left the switch armed");
2349
2350 let server = started("turn").await;
2351 let shared = Arc::clone(&server.handle.shared);
2352 server.terminate().await.unwrap();
2353 assert!(!armed(&shared), "terminate left the switch armed");
2354
2355 let server = started("turn").await;
2356 let shared = Arc::clone(&server.handle.shared);
2357 drop(server);
2358 assert!(!armed(&shared), "dropping left the switch armed");
2359 }
2360
2361 #[test]
2362 fn the_previewed_command_includes_the_clients_global_args() {
2363 let codex = Codex::builder()
2364 .binary("/bin/echo")
2365 .config("model=\"o3\"")
2366 .build()
2367 .unwrap();
2368 let builder = AppServer::builder(&codex);
2369 assert_eq!(builder.args(), ["app-server", "--listen", "stdio://"]);
2370 assert_eq!(
2371 builder.to_command_string(),
2372 "/bin/echo -c 'model=\"o3\"' app-server --listen stdio://"
2373 );
2374 }
2375
2376 #[tokio::test]
2377 async fn a_silent_server_times_out_the_handshake_and_is_stopped() {
2378 let pid = Arc::new(Mutex::new(None));
2379 let observed = Arc::clone(&pid);
2380 let codex = fake("silent")
2381 .timeout(Duration::from_millis(300))
2382 .on_spawn(Arc::new(move |info| {
2383 *observed.lock().unwrap() = Some(info.pid);
2384 }))
2385 .build()
2386 .unwrap();
2387
2388 let error = AppServer::builder(&codex).start().await.unwrap_err();
2389 assert!(matches!(error, Error::Timeout { .. }), "{error:?}");
2390
2391 let pid = pid.lock().unwrap().expect("the server was spawned");
2392 assert!(
2393 wait_until_gone(pid).await,
2394 "the silent server ({pid}) survived a failed start"
2395 );
2396 }
2397
2398 #[tokio::test]
2399 async fn a_server_that_exits_at_startup_is_reported_with_its_stderr() {
2400 let codex = fake("exit-on-start").build().unwrap();
2401 let error = AppServer::builder(&codex).start().await.unwrap_err();
2402 assert_eq!(error.exit_code(), Some(1), "{error:?}");
2403 assert_eq!(
2404 error.failure_kind(),
2405 Some(crate::FailureKind::Config),
2406 "{error:?}"
2407 );
2408 assert!(error.to_string().contains("bogus_key"), "{error}");
2409 }
2410
2411 #[tokio::test]
2423 async fn a_broken_stdin_pipe_leaves_the_verdict_to_the_reader() {
2424 let (stdin, server_end) = tokio::io::duplex(64);
2425 drop(server_end);
2426
2427 let (events, _received) = mpsc::unbounded_channel();
2428 let shared = Arc::new(Shared::new(events, None));
2429 let (lines, receiver) = mpsc::unbounded_channel();
2430 lines.send(Outgoing::Line(b"{}\n".to_vec())).unwrap();
2431
2432 tokio::time::timeout(
2435 Duration::from_secs(10),
2436 write_stdin(stdin, receiver, Arc::clone(&shared)),
2437 )
2438 .await
2439 .expect("the write to a closed pipe did not fail");
2440
2441 assert!(
2442 locked(&shared.state).closed.is_none(),
2443 "a write to a closed pipe was recorded as the session's failure"
2444 );
2445 drop(lines);
2446 }
2447
2448 #[tokio::test]
2452 async fn a_server_that_closes_its_input_and_then_fails_is_reported_by_its_exit_status() {
2453 let codex = fake("close-stdin").build().unwrap();
2454 let error = AppServer::builder(&codex).start().await.unwrap_err();
2455 assert_eq!(error.exit_code(), Some(1), "{error:?}");
2456 assert_eq!(
2457 error.failure_kind(),
2458 Some(crate::FailureKind::Config),
2459 "{error:?}"
2460 );
2461 assert!(error.to_string().contains("bogus_key"), "{error}");
2462 }
2463
2464 #[tokio::test]
2467 async fn heavy_stderr_does_not_stall_the_session() {
2468 let codex = fake("noisy-stderr").build().unwrap();
2469 let server =
2470 tokio::time::timeout(Duration::from_secs(20), AppServer::builder(&codex).start())
2471 .await
2472 .expect("the handshake stalled behind an undrained stderr pipe")
2473 .unwrap();
2474 server.shutdown().await.unwrap();
2475 }
2476
2477 #[tokio::test]
2478 async fn a_server_that_exits_mid_request_fails_it_with_the_stderr() {
2479 let mut server = started("exit-on-turn").await;
2480 let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2481 let error = server
2482 .turn_start(TurnStartParams::text(&thread.id, "go"))
2483 .await
2484 .unwrap_err();
2485 let text = error.to_string();
2486 assert!(text.contains("turn/start"), "{text}");
2487 assert!(
2488 text.contains("connection to the model provider was lost"),
2489 "{text}"
2490 );
2491
2492 while server.next_message().await.unwrap().is_some() {}
2494 assert!(server.next_message().await.unwrap().is_none());
2495
2496 let again = server.request("thread/start", json!({})).await.unwrap_err();
2498 assert!(
2499 matches!(again, Error::AppServerProtocol { .. }),
2500 "{again:?}"
2501 );
2502
2503 let error = server.shutdown().await.unwrap_err();
2505 assert_eq!(error.exit_code(), Some(5), "{error:?}");
2506 }
2507
2508 #[tokio::test]
2509 async fn the_output_limit_ends_the_session_and_kills_the_server() {
2510 let pid = Arc::new(Mutex::new(None));
2511 let observed = Arc::clone(&pid);
2512 let codex = fake("flood")
2513 .output_limit(2048)
2514 .on_spawn(Arc::new(move |info| {
2515 *observed.lock().unwrap() = Some(info.pid);
2516 }))
2517 .build()
2518 .unwrap();
2519 let mut server = AppServer::builder(&codex).start().await.unwrap();
2520
2521 let error = loop {
2522 match server.next_message().await {
2523 Ok(Some(_)) => {}
2524 Ok(None) => panic!("the limit error was swallowed"),
2525 Err(error) => break error,
2526 }
2527 };
2528 assert!(
2529 matches!(
2530 error,
2531 Error::OutputLimitExceeded {
2532 stream: OutputStream::Stdout,
2533 limit_bytes: 2048
2534 }
2535 ),
2536 "{error:?}"
2537 );
2538 assert!(server.next_message().await.unwrap().is_none());
2539
2540 let pid = pid.lock().unwrap().expect("the server was spawned");
2541 assert!(
2542 wait_until_gone(pid).await,
2543 "the server ({pid}) kept running after the output limit"
2544 );
2545 }
2546
2547 #[tokio::test]
2548 async fn invalid_json_ends_the_session() {
2549 let mut server = started("bad-json").await;
2550 let error = loop {
2551 match server.next_message().await {
2552 Ok(Some(_)) => {}
2553 Ok(None) => panic!("the malformed line was swallowed"),
2554 Err(error) => break error,
2555 }
2556 };
2557 assert!(
2558 matches!(&error, Error::AppServerProtocol { message } if message.contains("invalid JSON")),
2559 "{error:?}"
2560 );
2561 }
2562
2563 #[tokio::test]
2564 async fn terminate_stops_the_whole_process_group() {
2565 let pid_file = PidFile::new("app-server-terminate");
2566 let codex = fake("spawns-child")
2567 .env(
2568 "CODEX_WRAPPER_TEST_PIDFILE",
2569 pid_file.path().to_str().unwrap(),
2570 )
2571 .termination_grace(Duration::from_secs(1))
2574 .build()
2575 .unwrap();
2576 let server = AppServer::builder(&codex).start().await.unwrap();
2577 let (parent, child) = read_pids(&pid_file).await;
2578 assert!(is_running_for_test(parent) && is_running_for_test(child));
2579
2580 server.terminate().await.unwrap();
2581
2582 assert!(
2585 wait_until_gone(parent).await,
2586 "the server ({parent}) survived"
2587 );
2588 assert!(
2589 wait_until_gone(child).await,
2590 "the server's subprocess ({child}) survived terminate"
2591 );
2592 let marker = term_marker(&pid_file);
2595 assert!(
2596 marker.exists(),
2597 "terminate killed the server without asking it to stop first"
2598 );
2599 let _ = std::fs::remove_file(marker);
2600 }
2601
2602 #[tokio::test]
2603 async fn dropping_during_app_server_termination_grace_kills_the_group() {
2604 let fixture = crate::test_support::GracePeriodFixture::new("app-server-grace-drop");
2605 let codex = fixture.configure(fake("ignores-eof")).build().unwrap();
2606 let server = AppServer::builder(&codex).start().await.unwrap();
2607 fixture.assert_drop_during_grace(server.terminate()).await;
2608 }
2609
2610 #[tokio::test]
2611 async fn dropping_the_client_kills_the_process_group() {
2612 let pid_file = PidFile::new("app-server-drop");
2613 let codex = fake("spawns-child")
2614 .env(
2615 "CODEX_WRAPPER_TEST_PIDFILE",
2616 pid_file.path().to_str().unwrap(),
2617 )
2618 .build()
2619 .unwrap();
2620 let server = AppServer::builder(&codex).start().await.unwrap();
2621 let (parent, child) = read_pids(&pid_file).await;
2622
2623 drop(server);
2624
2625 assert!(
2626 wait_until_gone(parent).await,
2627 "the server ({parent}) survived"
2628 );
2629 assert!(
2630 wait_until_gone(child).await,
2631 "the server's subprocess ({child}) survived the drop"
2632 );
2633 assert!(!term_marker(&pid_file).exists());
2635 }
2636
2637 #[tokio::test]
2638 async fn shutdown_lets_a_server_that_exits_on_eof_finish_by_itself() {
2639 let codex = fake("turn")
2642 .termination_grace(Duration::from_secs(4))
2643 .build()
2644 .unwrap();
2645 let server = AppServer::builder(&codex).start().await.unwrap();
2646 let pid = server.pid().expect("running");
2647 let started_at = std::time::Instant::now();
2648 server.shutdown().await.unwrap();
2649 assert!(
2650 started_at.elapsed() < Duration::from_secs(3),
2651 "shutdown waited out the grace instead of seeing the exit"
2652 );
2653 assert!(wait_until_gone(pid).await);
2654 }
2655
2656 #[tokio::test]
2657 async fn shutdown_falls_back_to_termination_when_the_server_ignores_eof() {
2658 let pid_file = PidFile::new("app-server-ignores-eof");
2659 let codex = fake("ignores-eof")
2660 .env(
2661 "CODEX_WRAPPER_TEST_PIDFILE",
2662 pid_file.path().to_str().unwrap(),
2663 )
2664 .termination_grace(Duration::from_secs(1))
2667 .build()
2668 .unwrap();
2669 let server = AppServer::builder(&codex).start().await.unwrap();
2670 let (parent, child) = read_pids(&pid_file).await;
2671
2672 server.shutdown().await.unwrap();
2673
2674 let marker = term_marker(&pid_file);
2676 assert!(
2677 marker.exists(),
2678 "shutdown killed the server without asking it to stop"
2679 );
2680 let _ = std::fs::remove_file(marker);
2681
2682 assert!(
2683 wait_until_gone(parent).await,
2684 "the server ({parent}) survived"
2685 );
2686 assert!(
2687 wait_until_gone(child).await,
2688 "the server's subprocess ({child}) survived shutdown"
2689 );
2690 }
2691
2692 #[tokio::test]
2693 async fn requests_after_shutdown_fail_on_a_surviving_handle() {
2694 let server = started("turn").await;
2695 let handle = server.handle();
2696 server.shutdown().await.unwrap();
2697 let error = handle.request("thread/start", json!({})).await.unwrap_err();
2698 assert!(
2699 matches!(error, Error::AppServerProtocol { .. }),
2700 "{error:?}"
2701 );
2702 assert!(handle.notify("initialized", Value::Null).is_err());
2703 }
2704
2705 fn term_marker(pid_file: &PidFile) -> std::path::PathBuf {
2706 let mut path = pid_file.path().as_os_str().to_owned();
2707 path.push(".term");
2708 std::path::PathBuf::from(path)
2709 }
2710
2711 async fn read_pids(pid_file: &PidFile) -> (u32, u32) {
2712 for _ in 0..1000 {
2714 if let Ok(contents) = std::fs::read_to_string(pid_file.path()) {
2715 let field = |key: &str| {
2716 contents
2717 .lines()
2718 .find_map(|line| line.strip_prefix(key))
2719 .and_then(|value| value.trim().parse::<u32>().ok())
2720 };
2721 if let (Some(parent), Some(child)) = (field("parent="), field("child=")) {
2722 return (parent, child);
2723 }
2724 }
2725 tokio::time::sleep(Duration::from_millis(10)).await;
2726 }
2727 panic!("the fake server never recorded its pids");
2728 }
2729
2730 #[tokio::test]
2731 async fn a_request_that_times_out_leaves_the_session_usable_and_no_entry_behind() {
2732 let server = started("mute-after-init").await;
2735 let mut handle = server.handle();
2736 handle.timeout = Some(Duration::from_millis(150));
2737
2738 for _ in 0..2 {
2739 let error = handle.request("thread/start", json!({})).await.unwrap_err();
2740 assert!(matches!(error, Error::Timeout { .. }), "{error:?}");
2741 }
2742 assert!(
2743 locked(&handle.shared.state).pending.is_empty(),
2744 "a timed-out request left its slot behind"
2745 );
2746 assert!(handle.notify("initialized", Value::Null).is_ok());
2748 server.terminate().await.unwrap();
2749 }
2750
2751 #[tokio::test]
2755 async fn dropping_a_request_future_does_not_corrupt_the_wire() {
2756 let log = std::env::temp_dir().join(format!(
2757 "codex-wrapper-{}-app-server-dropped.log",
2758 std::process::id()
2759 ));
2760 let _ = std::fs::remove_file(&log);
2761 let codex = fake("turn")
2762 .env("FAKE_APP_SERVER_LOG", log.to_str().unwrap())
2763 .build()
2764 .unwrap();
2765 let server = AppServer::builder(&codex).start().await.unwrap();
2766
2767 for _ in 0..20 {
2768 let request = server.request("thread/start", json!({ "ephemeral": true }));
2771 let mut request = std::pin::pin!(request);
2772 let mut context = std::task::Context::from_waker(std::task::Waker::noop());
2773 assert!(request.as_mut().poll(&mut context).is_pending());
2774 }
2775 let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2776 assert!(!thread.id.is_empty());
2777 server.shutdown().await.unwrap();
2778
2779 let text = std::fs::read_to_string(&log).unwrap();
2780 let _ = std::fs::remove_file(&log);
2781 let mut count = 0;
2782 for line in text.lines() {
2783 serde_json::from_str::<Value>(line).expect("the server received a partial line");
2784 count += 1;
2785 }
2786 assert_eq!(count, 23, "{text}");
2788 }
2789
2790 #[tokio::test]
2791 async fn next_message_loses_nothing_when_its_future_is_dropped() {
2792 let mut server = started("turn").await;
2793 let thread = server.thread_start(ThreadStartParams::new()).await.unwrap();
2794 server
2795 .turn_start(TurnStartParams::text(&thread.id, "go"))
2796 .await
2797 .unwrap();
2798
2799 let mut seen = Vec::new();
2803 let mut finished = false;
2804 let deadline = std::time::Instant::now() + Duration::from_secs(20);
2805 while std::time::Instant::now() < deadline {
2806 if let Ok(next) =
2807 tokio::time::timeout(Duration::from_micros(200), server.next_message()).await
2808 {
2809 let message = next.unwrap().expect("the stream ended early");
2810 if let ServerMessage::Notification(n) = &message {
2811 finished |= n.turn_completed().is_some();
2812 }
2813 seen.push(message);
2814 }
2815 if finished {
2816 break;
2817 }
2818 }
2819 assert!(
2820 finished,
2821 "never saw the turn complete: {:?}",
2822 methods(&seen)
2823 );
2824 let methods = methods(&seen);
2825 let expected = [
2827 "remoteControl/status/changed",
2828 "thread/started",
2829 "thread/status/changed",
2830 "turn/started",
2831 "item/started",
2832 "item/agentMessage/delta",
2833 "item/completed",
2834 "thread/tokenUsage/updated",
2835 "thread/status/changed",
2836 "turn/completed",
2837 ];
2838 assert_eq!(methods, expected);
2839 server.shutdown().await.unwrap();
2840 }
2841
2842 #[test]
2843 fn turn_final_message_takes_the_last_final_answer_and_ignores_commentary() {
2844 let turn: Turn = serde_json::from_value(json!({
2845 "id": "t",
2846 "status": "completed",
2847 "items": [
2848 { "type": "agentMessage", "text": "working", "phase": "commentary" },
2849 { "type": "commandExecution", "text": "not a message", "phase": "final_answer" },
2850 { "type": "agentMessage", "text": "first", "phase": "final_answer" },
2851 { "type": "agentMessage", "text": "last", "phase": "final_answer" }
2852 ]
2853 }))
2854 .unwrap();
2855 assert_eq!(turn.final_message(), Some("last"));
2856 }
2857
2858 #[test]
2859 fn agent_messages_are_decoded_from_item_completed_only() {
2860 let message = |phase: Option<&str>| Notification {
2861 method: "item/completed".into(),
2862 params: json!({
2863 "item": {
2864 "type": "agentMessage",
2865 "id": "m",
2866 "text": "DONE STEERED",
2867 "phase": phase,
2868 },
2869 "threadId": "th",
2870 "turnId": "tu",
2871 }),
2872 };
2873 let answer = message(Some("final_answer")).agent_message().unwrap();
2874 assert_eq!(answer.text, "DONE STEERED");
2875 assert_eq!(
2876 (answer.thread_id.as_str(), answer.turn_id.as_str()),
2877 ("th", "tu")
2878 );
2879 assert!(answer.is_final_answer());
2880 assert!(
2881 !message(Some("commentary"))
2882 .agent_message()
2883 .unwrap()
2884 .is_final_answer()
2885 );
2886 assert!(!message(None).agent_message().unwrap().is_final_answer());
2887
2888 let mut command = message(None);
2890 command.params["item"]["type"] = json!("commandExecution");
2891 assert!(command.agent_message().is_none());
2892 let mut delta = message(None);
2893 delta.method = "item/agentMessage/delta".into();
2894 assert!(delta.agent_message().is_none());
2895 }
2896
2897 #[test]
2898 fn an_unknown_turn_status_is_kept_apart_from_the_known_ones() {
2899 let turn: Turn =
2900 serde_json::from_value(json!({ "id": "t", "status": "someFutureStatus" })).unwrap();
2901 assert_eq!(turn.status, TurnStatus::Unknown);
2902 }
2903
2904 #[test]
2905 fn only_a_well_formed_turn_completed_notification_decodes() {
2906 let other = Notification {
2907 method: "turn/started".into(),
2908 params: json!({}),
2909 };
2910 assert!(other.turn_completed().is_none());
2911 let malformed = Notification {
2912 method: "turn/completed".into(),
2913 params: json!({ "threadId": "x" }),
2914 };
2915 assert!(malformed.turn_completed().is_none());
2916 }
2917
2918 #[test]
2919 fn request_ids_round_trip_as_numbers_and_strings() {
2920 assert_eq!(serde_json::to_string(&RequestId::Number(7)).unwrap(), "7");
2921 assert_eq!(
2922 serde_json::to_string(&RequestId::String("a".into())).unwrap(),
2923 "\"a\""
2924 );
2925 assert_eq!(
2926 serde_json::from_str::<RequestId>("0").unwrap(),
2927 RequestId::Number(0)
2928 );
2929 assert_eq!(
2930 serde_json::from_str::<RequestId>("\"x\"").unwrap(),
2931 RequestId::String("x".into())
2932 );
2933 }
2934
2935 #[test]
2936 fn reply_lines_echo_the_servers_id() {
2937 let line = reply_line(
2938 &RequestId::Number(0),
2939 "result",
2940 &json!({ "decision": "decline" }),
2941 )
2942 .unwrap();
2943 assert_eq!(
2944 String::from_utf8(line).unwrap(),
2945 "{\"id\":0,\"result\":{\"decision\":\"decline\"}}\n"
2946 );
2947 let line = reply_line(
2948 &RequestId::String("r-1".into()),
2949 "error",
2950 &json!({ "code": -32601, "message": "no" }),
2951 )
2952 .unwrap();
2953 assert_eq!(
2954 String::from_utf8(line).unwrap(),
2955 "{\"id\":\"r-1\",\"error\":{\"code\":-32601,\"message\":\"no\"}}\n"
2956 );
2957 }
2958
2959 #[test]
2960 fn colour_codes_are_removed_from_server_logs() {
2961 let raw = "\u{1b}[2m2026-09-24T04:17:33Z\u{1b}[0m \u{1b}[31mERROR\u{1b}[0m worker quit";
2962 assert_eq!(strip_ansi(raw), "2026-09-24T04:17:33Z ERROR worker quit");
2963 }
2964
2965 #[test]
2966 fn a_line_that_is_not_a_message_is_ignored_and_bad_json_is_fatal() {
2967 let (events, mut received) = mpsc::unbounded_channel();
2968 let shared = Shared::new(events, None);
2969 assert!(route(r#"{"unrelated":true}"#, &shared).is_ok());
2970 assert!(
2971 route(
2972 r#"{"id":null,"error":{"code":-32600,"message":"x"}}"#,
2973 &shared
2974 )
2975 .is_ok()
2976 );
2977 assert!(route(r#"{"id":99,"result":{}}"#, &shared).is_ok());
2978 assert!(received.try_recv().is_err(), "nothing should be delivered");
2979
2980 assert!(route(r#"{"method":"a/b","params":{"k":1}}"#, &shared).is_ok());
2981 assert!(matches!(
2982 received.try_recv(),
2983 Ok(Event::Message(ServerMessage::Notification(n))) if n.method == "a/b"
2984 ));
2985 assert!(route(r#"{"method":"a/b","id":"s"}"#, &shared).is_ok());
2986 assert!(matches!(
2987 received.try_recv(),
2988 Ok(Event::Message(ServerMessage::Request(r))) if r.id == RequestId::String("s".into())
2989 ));
2990 assert!(matches!(
2991 route(r#"{"method": oops"#, &shared),
2992 Err(Closed::Broken(_))
2993 ));
2994 }
2995}