返回 CodeWhale
stdio.rs
根目录 / crates / app-server / src / stdio.rs
1 use crate::config_rpc::process_app_request;
2 use crate::turns::{NativeTurn, handle_prompt_request, handle_thread_request, run_native_turn_for};
3 use crate::{
4 AppState, AppTransport, ConfigGetParams, ConfigSetParams, DispatchError, InFlightTurn, RpcCall,
5 RuntimeOwnerRequest, RuntimeThreadHint, ShutdownAuthority, StdioDispatchResult, StdioLoopExit,
6 StdioLoopPolicy, ThreadIdParams, ThreadInterruptParams, ThreadMessageParams,
7 TurnExecutionOwner, TurnRegistry, daemon_socket, jsonrpc_error, jsonrpc_result,
8 legacy_deepseek_compat, params_or_object, parse_params, thread_control,
9 };
10 use anyhow::Context as _;
11 use anyhow::Result;
12 use codewhale_app_server_protocol::runtime::MAX_RUNTIME_IMAGE_BODY_BYTES;
13 use codewhale_protocol::{
14 AppRequest, PromptRequest, ThreadGoalClearParams, ThreadGoalGetParams, ThreadGoalSetParams,
15 ThreadRequest, ThreadResponse,
16 };
17 use serde::Deserialize;
18 use serde_json::{Value, json};
19 use std::collections::VecDeque;
20 use std::time::Duration;
21 use tokio::io::AsyncWriteExt as _;
22 use tokio::io::{AsyncBufRead, AsyncWrite};
23 use tokio_util::sync::CancellationToken;
24
25 pub use codewhale_util::bounded_lines::{BoundedLines, FrameRefusal, is_frame_refusal};
26
27 const _: () =
28 assert!(codewhale_util::bounded_lines::MAX_FRAME_BYTES == MAX_RUNTIME_IMAGE_BODY_BYTES);
29
30 /// The stdio JSON-RPC loop, generic over its transport so it can be driven by
31 /// a duplex pipe in tests rather than the process's real stdin/stdout.
32 pub(crate) async fn run_stdio_loop<R, W, C>(
33 state: &AppState,
34 mut reader: BoundedLines<R>,
35 mut writer: W,
36 policy: StdioLoopPolicy,
37 // Dropped the moment input closes, not when the in-flight turn ends. The
38 // socket transport passes its owner claim here: a `thread/message` can run
39 // for minutes, and an owner who disconnects mid-turn must not keep the
40 // daemon claimed for the rest of it, or a relaunched client is locked out
41 // with `daemon_already_claimed` and cannot even shut the daemon down.
42 // Process stdio has no claim and passes `None`.
43 mut input_claim: Option<C>,
44 ) -> Result<StdioLoopExit>
45 where
46 R: AsyncBufRead + Unpin,
47 W: AsyncWrite + Unpin,
48 C: Send,
49 {
50 // Work that arrived while a turn was streaming. The turn owns the writer
51 // for its whole duration, so these wait for it rather than interleaving
52 // into the middle of a response.
53 let mut pending: VecDeque<(PendingStdioWork, usize)> = VecDeque::new();
54 let mut pending_bytes = 0usize;
55 let mut stdin_open = true;
56 let mut connection = crate::connection::ConnectionSession::default();
57
58 loop {
59 let next = pending.pop_front().map(|(work, bytes)| {
60 pending_bytes -= bytes;
61 work
62 });
63 let request = match next {
64 Some(PendingStdioWork::Response(response)) => {
65 write_stdio_line(&mut writer, &response).await?;
66 continue;
67 }
68 Some(PendingStdioWork::Request(request)) => request,
69 None => {
70 if !stdin_open {
71 return Ok(StdioLoopExit::InputClosed);
72 }
73 let Some(line) = reader.next_line().await? else {
74 return Ok(StdioLoopExit::InputClosed);
75 };
76 match parse_stdio_line(&line) {
77 ParsedStdioLine::Blank => continue,
78 ParsedStdioLine::Ignored | ParsedStdioLine::Response(_) => continue,
79 ParsedStdioLine::Request(request) => request,
80 }
81 }
82 };
83
84 if is_control_detach(&request) {
85 drop(input_claim.take());
86 return Ok(StdioLoopExit::InputClosed);
87 }
88 let Some(id) = request.id.clone() else {
89 if request.method == "initialized" {
90 tracing::debug!("control initialized notification received");
91 }
92 continue;
93 };
94 if request.method == "initialize" {
95 let response = match connection.initialize(request.params) {
96 Ok(result) => {
97 tracing::debug!(connection = %connection.id(), "control connection initialized");
98 jsonrpc_result(id, result)
99 }
100 Err(error) => jsonrpc_error(id, error),
101 };
102 write_stdio_line(&mut writer, &response).await?;
103 continue;
104 }
105 if !connection.initialized() {
106 write_stdio_line(
107 &mut writer,
108 &jsonrpc_error(id, DispatchError::invalid_request("Not initialized")),
109 )
110 .await?;
111 continue;
112 }
113 if request.method == "shutdown" && policy.shutdown == ShutdownAuthority::Denied {
114 write_stdio_line(
115 &mut writer,
116 &jsonrpc_error(id, DispatchError::not_daemon_owner()),
117 )
118 .await?;
119 continue;
120 }
121 let mut input_error: Option<anyhow::Error> = None;
122 let native_request = matches!(
123 request.method.as_str(),
124 "thread/message" | "prompt/request" | "prompt/run"
125 ) || (request.method == "thread/request"
126 && request.params.get("kind").and_then(Value::as_str) == Some("message"));
127 let dispatched = if native_request {
128 // A turn can run for minutes. Keep reading stdin while it streams
129 // so an interrupt (or a shutdown) can actually reach it — with a
130 // plain `await` here, nothing could be read until it finished.
131 let cancellation = CancellationToken::new();
132 let _cancel_on_drop = cancellation.clone().drop_guard();
133 let dispatch = dispatch_stdio_request_with_writer(
134 state,
135 &mut writer,
136 &request.method,
137 request.params,
138 policy.transport,
139 Some(cancellation.clone()),
140 Some(connection.id()),
141 );
142 tokio::pin!(dispatch);
143 loop {
144 tokio::select! {
145 outcome = &mut dispatch => break outcome,
146 line = reader.next_line(), if stdin_open => {
147 match line {
148 Err(error) => {
149 stdin_open = false;
150 drop(input_claim.take());
151 cancellation.cancel();
152 input_error = Some(error.into());
153 }
154 Ok(None) => {
155 stdin_open = false;
156 // Release the claim here, not after `dispatch`
157 // resolves.
158 drop(input_claim.take());
159 if policy.transport == AppTransport::Socket {
160 cancellation.cancel();
161 }
162 }
163 Ok(Some(line)) => {
164 if matches!(parse_stdio_line(&line), ParsedStdioLine::Request(ref request) if is_control_detach(request)) {
165 stdin_open=false; drop(input_claim.take());
166 } else if let Err(error) = handle_line_during_turn(state, &line, &mut pending, &mut pending_bytes, policy, Some(connection.id())).await {
167 stdin_open = false;
168 drop(input_claim.take());
169 cancellation.cancel();
170 input_error = Some(error);
171 }
172 }
173 }
174 }
175 }
176 }
177 } else {
178 dispatch_stdio_request_with_writer(
179 state,
180 &mut writer,
181 &request.method,
182 request.params,
183 policy.transport,
184 None,
185 Some(connection.id()),
186 )
187 .await
188 };
189
190 if let Some(error) = input_error {
191 if let Err(dispatch_error) = &dispatched {
192 let diagnostic = error.to_string();
193 return Err(error.context(format!(
194 "control input failed: {diagnostic}; native request cleanup: {}",
195 dispatch_error.wire.message
196 )));
197 }
198 return Err(error);
199 }
200 match dispatched {
201 Ok(dispatch) => {
202 write_stdio_line(&mut writer, &jsonrpc_result(id, dispatch.result)).await?;
203 if dispatch.should_exit {
204 return Ok(StdioLoopExit::Shutdown);
205 }
206 }
207 Err(mut err) => {
208 if let Some(error) = err.transport_error.take() {
209 return Err(error);
210 }
211 write_stdio_line(&mut writer, &jsonrpc_error(id, err)).await?;
212 }
213 }
214 }
215 }
216
217 /// Work deferred until a streaming turn releases the writer.
218 pub(crate) enum PendingStdioWork {
219 /// Already answered (an interrupt acted immediately); just needs writing.
220 Response(Value),
221 /// Not started yet; runs normally once the turn is done.
222 Request(RpcCall),
223 }
224
225 /// Fixed retained queue limits; exhaustion is a visible connection refusal
226 /// before deferred work is admitted. Already-running effects are never replayed.
227 pub(crate) fn queue_stdio_work(
228 pending: &mut VecDeque<(PendingStdioWork, usize)>,
229 bytes: &mut usize,
230 work: PendingStdioWork,
231 input_bytes: usize,
232 ) -> Result<()> {
233 let retained = input_bytes
234 .checked_add(1024)
235 .context("control queue size overflow")?;
236 anyhow::ensure!(
237 pending.len() < 64 && retained <= MAX_RUNTIME_IMAGE_BODY_BYTES.saturating_sub(*bytes),
238 "control queue limit exceeded; deferred request not admitted, in-flight outcomes may be uncertain"
239 );
240 *bytes += retained;
241 pending.push_back((work, retained));
242 Ok(())
243 }
244
245 pub(crate) enum ParsedStdioLine {
246 Blank,
247 Request(RpcCall),
248 Ignored,
249 Response(Value),
250 }
251
252 pub(crate) fn parse_stdio_line(line: &str) -> ParsedStdioLine {
253 if line.len() > MAX_RUNTIME_IMAGE_BODY_BYTES {
254 return ParsedStdioLine::Ignored;
255 }
256 if line.trim().is_empty() {
257 return ParsedStdioLine::Blank;
258 }
259 let message: codewhale_app_server_protocol::rpc::RpcMessage = match serde_json::from_str(line) {
260 Ok(message) => message,
261 Err(error) => {
262 tracing::debug!(%error, "discarding malformed control RPC message");
263 return ParsedStdioLine::Ignored;
264 }
265 };
266 match message {
267 codewhale_app_server_protocol::rpc::RpcMessage::Response(response) => {
268 ParsedStdioLine::Response(json!(response))
269 }
270 codewhale_app_server_protocol::rpc::RpcMessage::Error(response) => {
271 ParsedStdioLine::Response(json!(response))
272 }
273 message => ParsedStdioLine::Request(message.into_call().expect("call variant")),
274 }
275 }
276
277 /// Triage a request that arrived mid-turn.
278 ///
279 /// Cancellation is the whole point of reading here, so `thread/interrupt`
280 /// runs immediately and only its reply waits for the writer. `shutdown` also
281 /// interrupts immediately — otherwise it would block on the bridge mutex the
282 /// turn is holding — and then queues so the turn can unwind first. Everything
283 /// else simply queues: it was never urgent, and running it now would race the
284 /// turn for the writer.
285 pub(crate) async fn handle_line_during_turn(
286 state: &AppState,
287 line: &str,
288 pending: &mut VecDeque<(PendingStdioWork, usize)>,
289 pending_bytes: &mut usize,
290 policy: StdioLoopPolicy,
291 connection: Option<crate::connection::ConnectionId>,
292 ) -> Result<()> {
293 let request = match parse_stdio_line(line) {
294 ParsedStdioLine::Blank => return Ok(()),
295 ParsedStdioLine::Ignored | ParsedStdioLine::Response(_) => return Ok(()),
296 ParsedStdioLine::Request(request) => request,
297 };
298
299 let Some(id) = request.id.clone() else {
300 return Ok(());
301 };
302
303 match request.method.as_str() {
304 "thread/interrupt" => {
305 let response = match parse_params::<ThreadInterruptParams>(params_or_object(
306 request.params.clone(),
307 )) {
308 Ok(parsed) => {
309 match interrupt_stdio_turn(state, &parsed.thread_id, connection).await {
310 Ok(interrupted) => jsonrpc_result(
311 id,
312 json!({ "thread_id": parsed.thread_id, "interrupted": interrupted }),
313 ),
314 Err(err) => jsonrpc_error(id, err),
315 }
316 }
317 Err(err) => jsonrpc_error(id, err),
318 };
319 queue_stdio_work(
320 pending,
321 pending_bytes,
322 PendingStdioWork::Response(response),
323 line.len(),
324 )?;
325 }
326 "shutdown" if policy.shutdown == ShutdownAuthority::Denied => {
327 // A non-owner may not even interrupt the live turns: that is the
328 // first half of what shutdown does.
329 queue_stdio_work(
330 pending,
331 pending_bytes,
332 PendingStdioWork::Response(jsonrpc_error(id, DispatchError::not_daemon_owner())),
333 line.len(),
334 )?;
335 }
336 "shutdown" => {
337 let _ = interrupt_all_stdio_turns(state).await;
338 queue_stdio_work(
339 pending,
340 pending_bytes,
341 PendingStdioWork::Request(request),
342 line.len(),
343 )?;
344 }
345 _ => queue_stdio_work(
346 pending,
347 pending_bytes,
348 PendingStdioWork::Request(request),
349 line.len(),
350 )?,
351 }
352 Ok(())
353 }
354
355 pub(crate) fn is_control_detach(request: &RpcCall) -> bool {
356 request.id.is_none()
357 && request.method == "daemon/input_closed"
358 && request
359 .params
360 .as_object()
361 .is_some_and(serde_json::Map::is_empty)
362 }
363
364 #[derive(Default)]
365 struct ControlFrameBuffer {
366 bytes: Vec<u8>,
367 exceeded: bool,
368 }
369
370 impl std::io::Write for ControlFrameBuffer {
371 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
372 if bytes.len() > MAX_RUNTIME_IMAGE_BODY_BYTES.saturating_sub(self.bytes.len()) {
373 self.exceeded = true;
374 return Err(std::io::Error::new(
375 std::io::ErrorKind::InvalidData,
376 FrameRefusal::TooLarge,
377 ));
378 }
379 let needed = self.bytes.len() + bytes.len();
380 if needed > self.bytes.capacity() {
381 let capacity = self
382 .bytes
383 .capacity()
384 .saturating_mul(2)
385 .max(needed)
386 .min(MAX_RUNTIME_IMAGE_BODY_BYTES);
387 self.bytes.reserve_exact(capacity - self.bytes.len());
388 }
389 self.bytes.extend_from_slice(bytes);
390 Ok(bytes.len())
391 }
392
393 fn flush(&mut self) -> std::io::Result<()> {
394 Ok(())
395 }
396 }
397
398 pub fn serialize_control_frame(value: &Value) -> std::io::Result<Vec<u8>> {
399 let mut output = ControlFrameBuffer::default();
400 if let Err(error) = serde_json::to_writer(&mut output, value) {
401 return Err(if output.exceeded {
402 std::io::Error::new(std::io::ErrorKind::InvalidData, FrameRefusal::TooLarge)
403 } else {
404 std::io::Error::new(std::io::ErrorKind::InvalidData, error)
405 });
406 }
407 Ok(output.bytes)
408 }
409
410 #[derive(Debug, thiserror::Error)]
411 #[error("control transport write failed; pending outcomes may be uncertain: {0}")]
412 struct ControlWriteFailure(#[source] std::io::Error);
413
414 pub fn is_control_write_failure(error: &anyhow::Error) -> bool {
415 error
416 .chain()
417 .any(|source| source.is::<ControlWriteFailure>())
418 }
419
420 pub async fn write_control_line<W: AsyncWrite + Unpin + ?Sized>(
421 writer: &mut W,
422 body: &[u8],
423 ) -> Result<()> {
424 if body.len() > MAX_RUNTIME_IMAGE_BODY_BYTES {
425 return Err(
426 std::io::Error::new(std::io::ErrorKind::InvalidData, FrameRefusal::TooLarge).into(),
427 );
428 }
429 let result = tokio::time::timeout(Duration::from_secs(30), async {
430 writer.write_all(body).await?;
431 writer.write_all(b"\n").await?;
432 writer.flush().await
433 })
434 .await
435 .unwrap_or_else(|_| {
436 Err(std::io::Error::new(
437 std::io::ErrorKind::TimedOut,
438 "control transport write did not settle within 30 seconds",
439 ))
440 });
441 result.map_err(|error| ControlWriteFailure(error).into())
442 }
443
444 pub(crate) async fn write_stdio_line<W: AsyncWrite + Unpin>(
445 writer: &mut W,
446 response: &Value,
447 ) -> Result<()> {
448 let frame = serialize_control_frame(response)?;
449 write_control_line(writer, &frame).await
450 }
451
452 pub(crate) async fn handle_stdio_thread_message<W: AsyncWrite + Unpin>(
453 state: &AppState,
454 writer: &mut W,
455 parsed: ThreadMessageParams,
456 cancellation: Option<CancellationToken>,
457 connection: Option<crate::connection::ConnectionId>,
458 ) -> std::result::Result<Value, DispatchError> {
459 let mut result = run_native_turn_for(
460 state,
461 writer,
462 NativeTurn {
463 allowed_tools: parsed.allowed_tools.as_deref(),
464 max_output_tokens: parsed.max_output_tokens,
465 thread_key: &parsed.thread_id,
466 input: &parsed.input,
467 images: &parsed.images,
468 model_override: None,
469 interruptible: true,
470 ephemeral: false,
471 cancellation,
472 },
473 None,
474 connection,
475 )
476 .await?;
477 if let Some(object) = result.as_object_mut() {
478 object.insert("thread_id".to_string(), Value::String(parsed.thread_id));
479 }
480 Ok(result)
481 }
482
483 /// Resuming, forking, archiving or unarchiving a thread the runtime reports
484 /// as `missing` must fail with a named not-found error. Recording the null model/workspace of that
485 /// response as a stdio hint would clobber any previously cached hint for
486 /// the same thread id (#5171).
487 pub(crate) fn ensure_thread_found(
488 response: &ThreadResponse,
489 ) -> std::result::Result<(), DispatchError> {
490 if response.status == "missing" {
491 return Err(DispatchError::thread_not_found(&response.thread_id));
492 }
493 Ok(())
494 }
495
496 pub(crate) async fn record_stdio_thread_hint(state: &AppState, response: &ThreadResponse) {
497 let mut hints = state.stdio_thread_hints.lock().await;
498 hints.insert(
499 response.thread_id.clone(),
500 RuntimeThreadHint {
501 model: response.model.clone(),
502 workspace: response.cwd.clone(),
503 },
504 );
505 }
506
507 ///
508 /// Split from [`interrupt_stdio_turn`] so teardown paths can run many
509 /// concurrently (#6211 R8b) — each future owns its snapshot and never holds
510 /// the turn registry across the request.
511 pub(crate) async fn interrupt_turn_request(
512 turn: &InFlightTurn,
513 ) -> std::result::Result<bool, DispatchError> {
514 match &turn.owner {
515 TurnExecutionOwner::Native(owner) => {
516 let interrupted = match tokio::time::timeout(
517 Duration::from_secs(10),
518 owner.execute(RuntimeOwnerRequest::InterruptTurn {
519 thread_id: turn.runtime_thread_id.clone(),
520 turn_id: turn.turn_id.clone(),
521 }),
522 )
523 .await
524 {
525 Ok(result) => result
526 .map_err(|error| DispatchError::internal(format!("interrupt failed: {error}"))),
527 Err(error) => Err(DispatchError::internal(format!(
528 "interrupt outcome uncertain: {error}"
529 ))),
530 };
531 match interrupted {
532 Ok(_) => Ok(true),
533 Err(error) => {
534 let detail = crate::owner_calls::execute(
535 owner,
536 RuntimeOwnerRequest::GetThread {
537 thread_id: turn.runtime_thread_id.clone(),
538 },
539 )
540 .await;
541 let terminal = detail.as_ref().ok().is_some_and(|detail| {
542 detail.pointer("/thread/id").and_then(Value::as_str)
543 == Some(turn.runtime_thread_id.as_str())
544 && detail
545 .get("turns")
546 .and_then(Value::as_array)
547 .is_some_and(|turns| {
548 turns.iter().any(|record| {
549 record.get("id").and_then(Value::as_str)
550 == Some(turn.turn_id.as_str())
551 && record.get("thread_id").and_then(Value::as_str)
552 == Some(turn.runtime_thread_id.as_str())
553 && matches!(
554 record.get("status").and_then(Value::as_str),
555 Some(
556 "completed"
557 | "failed"
558 | "interrupted"
559 | "canceled"
560 )
561 )
562 })
563 })
564 });
565 if terminal {
566 Ok(false)
567 } else {
568 Err(DispatchError::internal(format!(
569 "{}; exact native terminal is unconfirmed for thread {}, turn {}",
570 error.wire.message, turn.runtime_thread_id, turn.turn_id
571 )))
572 }
573 }
574 }
575 }
576 #[cfg(test)]
577 TurnExecutionOwner::HistoricalHttp {
578 base_url,
579 auth_token,
580 } => {
581 let mut request = codewhale_release::platform_http_client_builder()
582 .redirect(reqwest::redirect::Policy::none())
583 .timeout(Duration::from_secs(10))
584 .build()
585 .map_err(|err| DispatchError::internal(err.to_string()))?
586 .post(format!(
587 "{}/v1/threads/{}/turns/{}/interrupt",
588 base_url, turn.runtime_thread_id, turn.turn_id
589 ));
590 if let Some(token) = auth_token.as_deref() {
591 request = request.bearer_auth(token);
592 }
593 request
594 .send()
595 .await
596 .and_then(reqwest::Response::error_for_status)
597 .map_err(|err| DispatchError::internal(format!("interrupt failed: {err}")))?;
598 Ok(true)
599 }
600 }
601 }
602
603 pub(crate) async fn interrupt_stdio_turn(
604 state: &AppState,
605 thread_id: &str,
606 requester: Option<crate::connection::ConnectionId>,
607 ) -> std::result::Result<bool, DispatchError> {
608 let Some(turn) = state.in_flight_turns.lock().await.get(thread_id).cloned() else {
609 return Ok(false);
610 };
611 if let (Some(owner), Some(requester)) = (turn.connection, requester)
612 && owner != requester
613 {
614 return Err(DispatchError::not_turn_owner());
615 }
616 let interrupted = interrupt_turn_request(&turn).await?;
617 retire_turn_registration(&state.in_flight_turns, thread_id, &turn).await;
618 Ok(interrupted)
619 }
620
621 pub(crate) async fn retire_turn_registration(
622 registry: &TurnRegistry,
623 key: &str,
624 expected: &InFlightTurn,
625 ) {
626 let mut registered = registry.lock().await;
627 if registered.get(key).is_some_and(|current| {
628 current.runtime_thread_id == expected.runtime_thread_id
629 && current.turn_id == expected.turn_id
630 && match (&current.owner, &expected.owner) {
631 (TurnExecutionOwner::Native(current), TurnExecutionOwner::Native(expected)) => {
632 std::sync::Arc::ptr_eq(current, expected)
633 }
634 #[cfg(test)]
635 (
636 TurnExecutionOwner::HistoricalHttp {
637 base_url: current,
638 auth_token: current_auth,
639 },
640 TurnExecutionOwner::HistoricalHttp {
641 base_url: expected,
642 auth_token: expected_auth,
643 },
644 ) => current == expected && current_auth == expected_auth,
645 #[cfg(test)]
646 _ => false,
647 }
648 }) {
649 registered.remove(key);
650 }
651 }
652
653 /// Interrupt every in-flight turn concurrently, reporting how many were
654 /// reached (#6211 R8b).
655 ///
656 /// The teardown paths used to await each turn's interrupt in sequence, so
657 /// their latency grew with the number of live turns, including each
658 /// interrupt deadline and bounded readback after uncertain outcomes. Each interrupt now owns its snapshot and runs
659 /// as an independent task; individual failures are ignored exactly as the
660 /// sequential loop ignored them, and the registry lock is never held across
661 /// the requests.
662 pub(crate) async fn interrupt_all_stdio_turns(state: &AppState) -> usize {
663 let turns: Vec<(String, InFlightTurn)> = {
664 let map = state.in_flight_turns.lock().await;
665 map.iter()
666 .map(|(key, turn)| (key.clone(), turn.clone()))
667 .collect()
668 };
669 let mut set = tokio::task::JoinSet::new();
670 for (key, turn) in turns {
671 let registry = state.in_flight_turns.clone();
672 set.spawn(async move {
673 let interrupted = interrupt_turn_request(&turn).await?;
674 retire_turn_registration(&registry, &key, &turn).await;
675 Ok::<_, DispatchError>(interrupted)
676 });
677 }
678 let mut interrupted = 0usize;
679 while let Some(joined) = set.join_next().await {
680 if matches!(joined, Ok(Ok(true))) {
681 interrupted += 1;
682 }
683 }
684 interrupted
685 }
686
687 pub(crate) async fn emit_stdio_event<W: AsyncWrite + Unpin>(
688 writer: &mut W,
689 event: Value,
690 ) -> Result<()> {
691 write_stdio_line(writer, &event).await
692 }
693
694 #[cfg(test)]
695 pub(crate) async fn dispatch_stdio_request(
696 state: &AppState,
697 method: &str,
698 params: Value,
699 ) -> std::result::Result<StdioDispatchResult, DispatchError> {
700 let mut sink = tokio::io::sink();
701 dispatch_stdio_request_with_writer(
702 state,
703 &mut sink,
704 method,
705 params,
706 AppTransport::Stdio,
707 None,
708 None,
709 )
710 .await
711 }
712
713 pub(crate) async fn dispatch_stdio_app_request(
714 state: &AppState,
715 request: AppRequest,
716 transport: AppTransport,
717 ) -> std::result::Result<StdioDispatchResult, DispatchError> {
718 let response = Box::pin(process_app_request(state, request, transport)).await;
719 Ok(StdioDispatchResult {
720 result: serde_json::to_value(response)
721 .map_err(|err| DispatchError::internal(err.to_string()))?,
722 should_exit: false,
723 })
724 }
725
726 pub(crate) async fn dispatch_stdio_request_with_writer<W: AsyncWrite + Unpin>(
727 state: &AppState,
728 writer: &mut W,
729 method: &str,
730 params: Value,
731 transport: AppTransport,
732 cancellation: Option<CancellationToken>,
733 connection: Option<crate::connection::ConnectionId>,
734 ) -> std::result::Result<StdioDispatchResult, DispatchError> {
735 let outcome = match method {
736 "healthz" | "app/healthz" => StdioDispatchResult {
737 result: json!({
738 "status": "ok",
739 "service": legacy_deepseek_compat::SERVICE_NAME,
740 "transport": transport.label()
741 }),
742 should_exit: false,
743 },
744 "capabilities" => {
745 let mut methods = vec![
746 "healthz",
747 "thread/capabilities",
748 "thread/request",
749 "thread/create",
750 "thread/start",
751 "thread/resume",
752 "thread/fork",
753 "thread/list",
754 "thread/loaded/list",
755 "thread/read",
756 "thread/name/set",
757 "thread/set_name",
758 "thread/goal/get",
759 "thread/goal/clear",
760 "thread/archive",
761 "thread/unarchive",
762 "thread/message",
763 "thread/interrupt",
764 "app/capabilities",
765 "app/request",
766 "app/config/get",
767 "app/config/set",
768 "app/config/unset",
769 "app/config/list",
770 "app/config/reload",
771 "app/models",
772 "app/thread_loaded_list",
773 "prompt/capabilities",
774 "prompt/request",
775 "prompt/run",
776 "shutdown",
777 ];
778 if transport == AppTransport::Socket {
779 // The daemon handshake exists only on the socket transport;
780 // stdio/HTTP clients never see it, so the stdio pin is unchanged.
781 methods.insert(1, daemon_socket::ATTACH_METHOD);
782 }
783 StdioDispatchResult {
784 result: json!({
785 "transport": transport.label(),
786 "framing": match transport {
787 AppTransport::Stdio => "jsonl",
788 AppTransport::Socket => "websocket-text",
789 AppTransport::Http => "http",
790 },
791 "families": ["thread/*", "app/*", "prompt/*"],
792 "initialization": {"required": true, "method": "initialize", "notification": "initialized"},
793 "turn_image_inputs": true,
794 "interactive_execution": false,
795 "goal_execution": false,
796 "tool_free_turns": true,
797 "full_api_entrypoint": "codewhale app-server --http",
798 "methods": methods,
799 }),
800 should_exit: false,
801 }
802 }
803 "thread/capabilities" => StdioDispatchResult {
804 result: json!({
805 "turn_image_inputs": true,
806 "interactive_execution": false,
807 "goal_execution": false,
808 "tool_free_turns": true,
809 "full_api_entrypoint": "codewhale app-server --http",
810 "methods": [
811 "thread/request",
812 "thread/create",
813 "thread/start",
814 "thread/resume",
815 "thread/fork",
816 "thread/list",
817 "thread/loaded/list",
818 "thread/read",
819 "thread/name/set",
820 "thread/set_name",
821 "thread/goal/get",
822 "thread/goal/clear",
823 "thread/archive",
824 "thread/unarchive",
825 "thread/message",
826 "thread/interrupt"
827 ]
828 }),
829 should_exit: false,
830 },
831 "thread/request" => {
832 let request: ThreadRequest = parse_params(params)?;
833 if let ThreadRequest::Message {
834 thread_id,
835 input,
836 allowed_tools,
837 images,
838 max_output_tokens,
839 } = request
840 {
841 let response = handle_stdio_thread_message(
842 state,
843 writer,
844 ThreadMessageParams {
845 thread_id,
846 input,
847 allowed_tools,
848 images,
849 max_output_tokens,
850 },
851 cancellation.clone(),
852 connection,
853 )
854 .await?;
855 return Ok(StdioDispatchResult {
856 result: response,
857 should_exit: false,
858 });
859 }
860 let should_record_hint = matches!(
861 &request,
862 ThreadRequest::Create { .. }
863 | ThreadRequest::Start(_)
864 | ThreadRequest::Resume(_)
865 | ThreadRequest::Fork(_)
866 );
867 let response = handle_thread_request(state, request).await?;
868 if should_record_hint {
869 record_stdio_thread_hint(state, &response).await;
870 }
871 StdioDispatchResult {
872 result: serde_json::to_value(response)
873 .map_err(|err| DispatchError::internal(err.to_string()))?,
874 should_exit: false,
875 }
876 }
877 "thread/create" => {
878 #[derive(Debug, Deserialize)]
879 struct CreateParams {
880 #[serde(default)]
881 metadata: Value,
882 }
883 let parsed: CreateParams = parse_params(params_or_object(params))?;
884 let response = handle_thread_request(
885 state,
886 ThreadRequest::Create {
887 metadata: parsed.metadata,
888 },
889 )
890 .await?;
891 record_stdio_thread_hint(state, &response).await;
892 StdioDispatchResult {
893 result: serde_json::to_value(response)
894 .map_err(|err| DispatchError::internal(err.to_string()))?,
895 should_exit: false,
896 }
897 }
898 "thread/start" => {
899 let params: codewhale_app_server_protocol::rpc::ThreadStartParams =
900 parse_params(params_or_object(params))?;
901 let request = ThreadRequest::Start(thread_control::start_params(params)?);
902 let response = handle_thread_request(state, request).await?;
903 record_stdio_thread_hint(state, &response).await;
904 let wire = thread_control::start_wire(response)
905 .map_err(|err| DispatchError::internal(format!("{err:#}")))?;
906 StdioDispatchResult {
907 result: serde_json::to_value(wire)
908 .map_err(|err| DispatchError::internal(err.to_string()))?,
909 should_exit: false,
910 }
911 }
912 "thread/resume" => {
913 let request = ThreadRequest::Resume(parse_params(params_or_object(params))?);
914 let response = handle_thread_request(state, request).await?;
915 ensure_thread_found(&response)?;
916 record_stdio_thread_hint(state, &response).await;
917 StdioDispatchResult {
918 result: serde_json::to_value(response)
919 .map_err(|err| DispatchError::internal(err.to_string()))?,
920 should_exit: false,
921 }
922 }
923 "thread/fork" => {
924 let request = ThreadRequest::Fork(parse_params(params_or_object(params))?);
925 let response = handle_thread_request(state, request).await?;
926 ensure_thread_found(&response)?;
927 record_stdio_thread_hint(state, &response).await;
928 StdioDispatchResult {
929 result: serde_json::to_value(response)
930 .map_err(|err| DispatchError::internal(err.to_string()))?,
931 should_exit: false,
932 }
933 }
934 "thread/list" => {
935 let request = ThreadRequest::List(parse_params(params_or_object(params))?);
936 let response = handle_thread_request(state, request).await?;
937 StdioDispatchResult {
938 result: serde_json::to_value(thread_control::list_wire(response))
939 .map_err(|err| DispatchError::internal(err.to_string()))?,
940 should_exit: false,
941 }
942 }
943 "thread/loaded/list" => {
944 let params: codewhale_app_server_protocol::rpc::ThreadLoadedListParams =
945 parse_params(params_or_object(params))?;
946 let limit = params.limit.map(usize::try_from).transpose().map_err(|_| {
947 DispatchError::invalid_params("loaded thread limit exceeds platform size")
948 })?;
949 let cursor = params
950 .cursor
951 .as_deref()
952 .map(|cursor| {
953 cursor
954 .strip_prefix("loaded-v1:")
955 .filter(|id| id.len() <= 1024 && !id.chars().any(char::is_control))
956 .ok_or_else(|| {
957 DispatchError::invalid_params("invalid loaded thread cursor")
958 })
959 })
960 .transpose()?;
961 let loaded = thread_control::loaded(state)
962 .await
963 .map_err(|error| thread_control::rpc_error(error, None))?;
964 let start = cursor.filter(|id| !id.is_empty()).map_or(0, |cursor| {
965 loaded
966 .threads
967 .partition_point(|thread| thread.id.as_str() <= cursor)
968 });
969 let remaining = &loaded.threads[start..];
970 let count = limit.unwrap_or(remaining.len()).max(1).min(remaining.len());
971 let data = remaining[..count]
972 .iter()
973 .map(|thread| thread.id.clone())
974 .collect::<Vec<_>>();
975 let next_cursor = if count < remaining.len() {
976 Some(data.last().map_or_else(
977 || {
978 params
979 .cursor
980 .clone()
981 .unwrap_or_else(|| "loaded-v1:".to_owned())
982 },
983 |id| format!("loaded-v1:{id}"),
984 ))
985 } else {
986 None
987 };
988 StdioDispatchResult {
989 result: serde_json::to_value(
990 codewhale_app_server_protocol::rpc::ThreadLoadedListResponse {
991 data,
992 next_cursor,
993 },
994 )
995 .map_err(|error| DispatchError::internal(error.to_string()))?,
996 should_exit: false,
997 }
998 }
999 "thread/read" => {
1000 let params: codewhale_app_server_protocol::rpc::ThreadReadParams =
1001 parse_params(params_or_object(params))?;
1002 let include_turns = params.include_turns;
1003 let request = ThreadRequest::Read(codewhale_protocol::ThreadReadParams {
1004 thread_id: params.thread_id,
1005 });
1006 let response = handle_thread_request(state, request).await?;
1007 let wire = thread_control::read_wire(response, include_turns)
1008 .map_err(|err| DispatchError::internal(format!("{err:#}")))?;
1009 StdioDispatchResult {
1010 result: serde_json::to_value(wire)
1011 .map_err(|err| DispatchError::internal(err.to_string()))?,
1012 should_exit: false,
1013 }
1014 }
1015 "thread/name/set" => {
1016 let params: codewhale_app_server_protocol::rpc::ThreadSetNameParams =
1017 parse_params(params_or_object(params))?;
1018 handle_thread_request(
1019 state,
1020 ThreadRequest::SetName(codewhale_protocol::ThreadSetNameParams {
1021 thread_id: params.thread_id,
1022 name: params.name,
1023 }),
1024 )
1025 .await?;
1026 StdioDispatchResult {
1027 result: serde_json::to_value(
1028 codewhale_app_server_protocol::rpc::ThreadSetNameResponse::default(),
1029 )
1030 .map_err(|error| DispatchError::internal(error.to_string()))?,
1031 should_exit: false,
1032 }
1033 }
1034 "thread/set_name" | "thread/set-name" => {
1035 let request = ThreadRequest::SetName(parse_params(params_or_object(params))?);
1036 let response = handle_thread_request(state, request).await?;
1037 StdioDispatchResult {
1038 result: serde_json::to_value(response)
1039 .map_err(|err| DispatchError::internal(err.to_string()))?,
1040 should_exit: false,
1041 }
1042 }
1043 "thread/goal/set" | "thread/goal_set" | "thread/goal-set" => {
1044 let request = ThreadRequest::GoalSet(parse_params::<ThreadGoalSetParams>(
1045 params_or_object(params),
1046 )?);
1047 let response = handle_thread_request(state, request).await?;
1048 StdioDispatchResult {
1049 result: serde_json::to_value(response)
1050 .map_err(|err| DispatchError::internal(err.to_string()))?,
1051 should_exit: false,
1052 }
1053 }
1054 "thread/goal/get" | "thread/goal_get" | "thread/goal-get" => {
1055 let request = ThreadRequest::GoalGet(parse_params::<ThreadGoalGetParams>(
1056 params_or_object(params),
1057 )?);
1058 let response = handle_thread_request(state, request).await?;
1059 StdioDispatchResult {
1060 result: serde_json::to_value(response)
1061 .map_err(|err| DispatchError::internal(err.to_string()))?,
1062 should_exit: false,
1063 }
1064 }
1065 "thread/goal/clear" | "thread/goal_clear" | "thread/goal-clear" => {
1066 let request = ThreadRequest::GoalClear(parse_params::<ThreadGoalClearParams>(
1067 params_or_object(params),
1068 )?);
1069 let response = handle_thread_request(state, request).await?;
1070 StdioDispatchResult {
1071 result: serde_json::to_value(response)
1072 .map_err(|err| DispatchError::internal(err.to_string()))?,
1073 should_exit: false,
1074 }
1075 }
1076 "thread/archive" => {
1077 let parsed: ThreadIdParams = parse_params(params_or_object(params))?;
1078 let response = handle_thread_request(
1079 state,
1080 ThreadRequest::Archive {
1081 thread_id: parsed.thread_id,
1082 },
1083 )
1084 .await?;
1085 ensure_thread_found(&response)?;
1086 StdioDispatchResult {
1087 result: serde_json::to_value(response)
1088 .map_err(|err| DispatchError::internal(err.to_string()))?,
1089 should_exit: false,
1090 }
1091 }
1092 "thread/unarchive" => {
1093 let parsed: ThreadIdParams = parse_params(params_or_object(params))?;
1094 let response = handle_thread_request(
1095 state,
1096 ThreadRequest::Unarchive {
1097 thread_id: parsed.thread_id,
1098 },
1099 )
1100 .await?;
1101 ensure_thread_found(&response)?;
1102 StdioDispatchResult {
1103 result: serde_json::to_value(response)
1104 .map_err(|err| DispatchError::internal(err.to_string()))?,
1105 should_exit: false,
1106 }
1107 }
1108 "thread/message" => {
1109 let parsed: ThreadMessageParams = parse_params(params_or_object(params))?;
1110 let response = handle_stdio_thread_message(
1111 state,
1112 writer,
1113 parsed,
1114 cancellation.clone(),
1115 connection,
1116 )
1117 .await?;
1118 StdioDispatchResult {
1119 result: response,
1120 should_exit: false,
1121 }
1122 }
1123 "app/capabilities" => {
1124 dispatch_stdio_app_request(state, AppRequest::Capabilities, transport).await?
1125 }
1126 "app/request" => {
1127 let request: AppRequest = parse_params(params)?;
1128 dispatch_stdio_app_request(state, request, transport).await?
1129 }
1130 "app/config/get" => {
1131 let parsed: ConfigGetParams = parse_params(params_or_object(params))?;
1132 dispatch_stdio_app_request(state, AppRequest::ConfigGet { key: parsed.key }, transport)
1133 .await?
1134 }
1135 "app/config/set" => {
1136 let parsed: ConfigSetParams = parse_params(params_or_object(params))?;
1137 dispatch_stdio_app_request(
1138 state,
1139 AppRequest::ConfigSet {
1140 key: parsed.key,
1141 value: parsed.value,
1142 },
1143 transport,
1144 )
1145 .await?
1146 }
1147 "app/config/unset" => {
1148 let parsed: ConfigGetParams = parse_params(params_or_object(params))?;
1149 dispatch_stdio_app_request(
1150 state,
1151 AppRequest::ConfigUnset { key: parsed.key },
1152 transport,
1153 )
1154 .await?
1155 }
1156 "app/config/list" => {
1157 dispatch_stdio_app_request(state, AppRequest::ConfigList, transport).await?
1158 }
1159 "app/config/reload" => {
1160 dispatch_stdio_app_request(state, AppRequest::ConfigReload, transport).await?
1161 }
1162 "app/models" => dispatch_stdio_app_request(state, AppRequest::Models, transport).await?,
1163 "app/thread_loaded_list" | "app/thread-loaded-list" => {
1164 dispatch_stdio_app_request(state, AppRequest::ThreadLoadedList, transport).await?
1165 }
1166 "prompt/capabilities" => StdioDispatchResult {
1167 result: json!({
1168 "interactive_execution": false,
1169 "goal_execution": false,
1170 "tool_free_turns": true,
1171 "full_api_entrypoint": "codewhale app-server --http",
1172 "methods": ["prompt/request", "prompt/run"]
1173 }),
1174 should_exit: false,
1175 },
1176 "prompt/request" | "prompt/run" => {
1177 let request: PromptRequest = parse_params(params)?;
1178 let response =
1179 handle_prompt_request(state, writer, request, cancellation.clone()).await?;
1180 StdioDispatchResult {
1181 result: serde_json::to_value(response)
1182 .map_err(|err| DispatchError::internal(err.to_string()))?,
1183 should_exit: false,
1184 }
1185 }
1186 "thread/interrupt" => {
1187 let parsed: ThreadInterruptParams = parse_params(params_or_object(params))?;
1188 let interrupted = interrupt_stdio_turn(state, &parsed.thread_id, connection).await?;
1189 StdioDispatchResult {
1190 result: json!({
1191 "thread_id": parsed.thread_id,
1192 "interrupted": interrupted,
1193 }),
1194 should_exit: false,
1195 }
1196 }
1197 "shutdown" => {
1198 // The transport checks shutdown authority before dispatch.
1199 // Interrupt live turns before returning the flushed shutdown
1200 // result to its captured host. Keep the shared bridge bound while
1201 // that owner drains its manager and listeners.
1202 let _ = interrupt_all_stdio_turns(state).await;
1203 StdioDispatchResult {
1204 result: json!({"ok": true, "status": "stopped"}),
1205 should_exit: true,
1206 }
1207 }
1208 daemon_socket::ATTACH_METHOD if transport == AppTransport::Socket => {
1209 return Err(DispatchError::already_attached());
1210 }
1211 _ => return Err(DispatchError::method_not_found(method)),
1212 };
1213 Ok(outcome)
1214 }
1215
1215 lines RUST