返回 CodeWhale
turns.rs
根目录 / crates / app-server / src / turns.rs
1 use crate::stdio::{emit_stdio_event, interrupt_turn_request, retire_turn_registration};
2 use crate::{
3 AppState, DispatchError, InFlightTurn, RuntimeOwnerFrontend, RuntimeOwnerRequest,
4 RuntimeThreadHint, TurnExecutionOwner, TurnRegistry, TurnTerminalStatus, TurnTranscript,
5 owner_calls, thread_control,
6 };
7 use anyhow::{Context as _, Result, anyhow};
8 use codewhale_app_server_protocol::runtime::RuntimeImageInput;
9 use codewhale_protocol::{
10 EventFrame, PromptRequest, PromptResponse, ResponseChannel, ThreadRequest, ThreadResponse,
11 };
12 use futures_util::StreamExt;
13 use serde_json::{Value, json};
14 use std::path::Path;
15 use std::sync::Arc;
16 use std::time::Duration;
17 use tokio::io::AsyncWrite;
18 use tokio_util::sync::CancellationToken;
19 use uuid::Uuid;
20
21 pub(crate) async fn handle_thread_request(
22 state: &AppState,
23 req: ThreadRequest,
24 ) -> std::result::Result<ThreadResponse, DispatchError> {
25 if matches!(&req, ThreadRequest::GoalSet(_)) {
26 return Err(DispatchError::unsupported_interactive_execution());
27 }
28 thread_control::handle(state, req).await
29 }
30
31 pub(crate) struct RuntimeTurnInput<'a> {
32 pub(crate) input: &'a str,
33 pub(crate) images: &'a [RuntimeImageInput],
34 pub(crate) max_output_tokens: Option<std::num::NonZeroU32>,
35 pub(crate) expected_workspace: Option<&'a Path>,
36 pub(crate) cancellation: Option<&'a CancellationToken>,
37 }
38
39 pub(crate) struct NativeTurn<'a> {
40 pub(crate) allowed_tools: Option<&'a [String]>,
41 pub(crate) max_output_tokens: Option<std::num::NonZeroU32>,
42 pub(crate) thread_key: &'a str,
43 pub(crate) input: &'a str,
44 pub(crate) images: &'a [RuntimeImageInput],
45 /// Model for the runtime thread when this call is the one that creates
46 /// it. An existing thread keeps the model it was created with.
47 pub(crate) model_override: Option<String>,
48 /// Publish the live turn so a concurrent `thread/interrupt` can cancel
49 /// it. Only stdio has a mid-turn channel, so only stdio sets this.
50 pub(crate) interruptible: bool,
51 pub(crate) ephemeral: bool,
52 pub(crate) cancellation: Option<CancellationToken>,
53 }
54
55 /// Execute exactly one turn on the real runtime.
56 ///
57 pub(crate) async fn run_native_turn<W: AsyncWrite + Unpin>(
58 state: &AppState,
59 writer: &mut W,
60 turn: NativeTurn<'_>,
61 transcript: Option<&mut TurnTranscript>,
62 ) -> std::result::Result<Value, DispatchError> {
63 run_native_turn_for(state, writer, turn, transcript, None).await
64 }
65
66 pub(crate) async fn run_native_turn_for<W: AsyncWrite + Unpin>(
67 state: &AppState,
68 writer: &mut W,
69 turn: NativeTurn<'_>,
70 transcript: Option<&mut TurnTranscript>,
71 connection: Option<crate::connection::ConnectionId>,
72 ) -> std::result::Result<Value, DispatchError> {
73 if !matches!(turn.allowed_tools, Some([])) {
74 return Err(DispatchError::unsupported_interactive_execution());
75 }
76 let mut hint = {
77 let hints = state.stdio_thread_hints.lock().await;
78 hints.get(turn.thread_key).cloned()
79 };
80 if let Some(model) = turn.model_override {
81 hint.get_or_insert_with(RuntimeThreadHint::default).model = Some(model);
82 }
83 // Durable compatibility IDs resolve through full canonical history and
84 // exact owner receipts before the existing turn transport can begin.
85 let resolved = if turn.ephemeral {
86 None
87 } else {
88 Some(
89 thread_control::resolve(state, turn.thread_key, true)
90 .await
91 .map_err(|error| thread_control::rpc_error(error, Some(turn.thread_key)))?,
92 )
93 };
94 if let Some((_, workspace)) = resolved.as_ref() {
95 hint.get_or_insert_with(RuntimeThreadHint::default)
96 .workspace = Some(workspace.clone());
97 } else if let Some(workspace) = state.frontend_workspace.as_ref() {
98 hint.get_or_insert_with(RuntimeThreadHint::default)
99 .workspace
100 .get_or_insert_with(|| workspace.clone());
101 }
102 // Retain the acknowledged/observed scope across all transport awaits.
103 // The owning Runtime rechecks this assertion at its final turn admission.
104 let expected_workspace = hint.as_ref().and_then(|hint| hint.workspace.clone());
105 let owner = owner_calls::captured(state)
106 .map_err(|error| DispatchError::runtime_unavailable(error.to_string()))?;
107 if turn.max_output_tokens.is_some() {
108 let info = owner_calls::execute(&owner, RuntimeOwnerRequest::Capabilities)
109 .await
110 .map_err(|error| DispatchError::runtime_unavailable(error.to_string()))?;
111 if info
112 .pointer("/capabilities/turn_output_token_limit")
113 .and_then(Value::as_bool)
114 != Some(true)
115 {
116 return Err(DispatchError::invalid_params(
117 "Runtime does not support maxOutputTokens",
118 ));
119 }
120 }
121 if turn.max_output_tokens.is_some() && resolved.is_none() {
122 owner_calls::require_output_limited_model(
123 &owner,
124 hint.as_ref().and_then(|hint| hint.model.as_deref()),
125 )
126 .await
127 .map_err(|error| DispatchError::invalid_params(error.to_string()))?;
128 }
129 let runtime_thread_id = match resolved {
130 Some((id, _)) => id,
131 None => {
132 let hint = hint.unwrap_or_default();
133 let record = owner_calls::execute(
134 &owner,
135 RuntimeOwnerRequest::CreateThread(json!({
136 "model": hint.model,
137 "workspace": hint.workspace,
138 "mode": "agent",
139 "archived": false,
140 })),
141 )
142 .await
143 .map_err(|error| DispatchError::runtime_unavailable(format!("{error:#}")))?;
144 extract_runtime_thread_id(&record)
145 .map_err(|error| DispatchError::internal(format!("{error:#}")))?
146 .to_owned()
147 }
148 };
149 let result = async {
150 let registration = turn
151 .interruptible
152 .then(|| (state.in_flight_turns.clone(), turn.thread_key.to_owned()));
153 message_native_thread(
154 owner,
155 &runtime_thread_id,
156 RuntimeTurnInput {
157 input: turn.input,
158 images: turn.images,
159 max_output_tokens: turn.max_output_tokens,
160 expected_workspace: expected_workspace.as_deref(),
161 cancellation: turn.cancellation.as_ref(),
162 },
163 writer,
164 registration,
165 transcript,
166 connection,
167 )
168 .await
169 .map_err(|error| {
170 if error.downcast_ref::<NativeTurnContext>().is_some() {
171 error
172 } else {
173 error.context(NativeTurnContext {
174 thread_id: runtime_thread_id,
175 turn_id: None,
176 operation_key: None,
177 })
178 }
179 })
180 }
181 .await;
182 result.map_err(|error| {
183 let mut response = DispatchError::internal(format!("{error:#}"));
184 if let Some(context) = error.downcast_ref::<NativeTurnContext>() {
185 response.wire.data = Some(json!({
186 "thread_id": context.thread_id, "turn_id": context.turn_id,
187 "operation_key": context.operation_key, "replay_safe": false,
188 }));
189 }
190 if crate::stdio::is_control_write_failure(&error) {
191 response.transport_error = Some(error);
192 }
193 response
194 })
195 }
196
197 /// Run a prompt as a genuine model turn and return what the model actually
198 /// said.
199 ///
200 /// `writer` receives the same streaming frames stdio `thread/message` emits;
201 /// HTTP callers pass a sink and read the frames back out of
202 /// [`PromptResponse::events`].
203 pub(crate) async fn run_prompt_turn<W: AsyncWrite + Unpin>(
204 state: &AppState,
205 writer: &mut W,
206 req: PromptRequest,
207 cancellation: Option<CancellationToken>,
208 ) -> std::result::Result<PromptResponse, DispatchError> {
209 if req.prompt.trim().is_empty() {
210 return Err(DispatchError::invalid_params("prompt must not be empty"));
211 }
212 let ephemeral = req.thread_id.is_none();
213 let thread_key = req
214 .thread_id
215 .clone()
216 .unwrap_or_else(|| format!("prompt-{}", Uuid::new_v4()));
217
218 let mut transcript = TurnTranscript::default();
219 run_native_turn(
220 state,
221 writer,
222 NativeTurn {
223 allowed_tools: req.allowed_tools.as_deref(),
224 max_output_tokens: req.max_output_tokens,
225 thread_key: &thread_key,
226 input: &req.prompt,
227 images: &req.images,
228 model_override: req.model.clone(),
229 // `thread/interrupt` addresses client-facing thread ids. A
230 // one-shot prompt has none to hand back.
231 interruptible: false,
232 ephemeral,
233 cancellation,
234 },
235 Some(&mut transcript),
236 )
237 .await?;
238
239 let model = transcript.model.unwrap_or_else(|| "unknown".to_string());
240
241 Ok(PromptResponse {
242 output: transcript.text,
243 model,
244 events: transcript.events,
245 })
246 }
247
248 pub(crate) async fn handle_prompt_request<W: AsyncWrite + Unpin>(
249 state: &AppState,
250 writer: &mut W,
251 req: PromptRequest,
252 cancellation: Option<CancellationToken>,
253 ) -> std::result::Result<PromptResponse, DispatchError> {
254 run_prompt_turn(state, writer, req, cancellation).await
255 }
256
257 /// HTTP `/thread` with a `Message` body: same engine as stdio
258 /// `thread/message`, but the turn is collected rather than streamed because
259 /// this transport is request/response.
260 pub(crate) async fn run_http_thread_message(
261 state: &AppState,
262 thread_id: String,
263 input: String,
264 allowed_tools: Option<Vec<String>>,
265 images: Vec<RuntimeImageInput>,
266 max_output_tokens: Option<std::num::NonZeroU32>,
267 ) -> std::result::Result<ThreadResponse, DispatchError> {
268 let mut transcript = TurnTranscript::default();
269 let mut sink = tokio::io::sink();
270 let result = run_native_turn(
271 state,
272 &mut sink,
273 NativeTurn {
274 allowed_tools: allowed_tools.as_deref(),
275 max_output_tokens,
276 thread_key: &thread_id,
277 input: &input,
278 images: &images,
279 model_override: None,
280 interruptible: false,
281 ephemeral: false,
282 cancellation: None,
283 },
284 Some(&mut transcript),
285 )
286 .await?;
287
288 Ok(ThreadResponse {
289 thread_id,
290 // The turn ran to a terminal state before this response was built,
291 // which is exactly what the old `accepted` did not mean.
292 status: "completed".to_string(),
293 thread: None,
294 threads: Vec::new(),
295 goal: None,
296 model: transcript.model,
297 model_provider: None,
298 cwd: None,
299 approval_policy: None,
300 sandbox: None,
301 events: transcript.events,
302 data: result.get("data").cloned().unwrap_or_else(|| json!({})),
303 })
304 }
305
306 pub(crate) fn extract_runtime_thread_id(record: &Value) -> Result<&str> {
307 record
308 .get("id")
309 .and_then(Value::as_str)
310 .ok_or_else(|| anyhow!("runtime API thread response missing id"))
311 }
312
313 pub(crate) fn turn_terminal_status(payload: &Value) -> Result<TurnTerminalStatus> {
314 match payload.pointer("/turn/status").and_then(Value::as_str) {
315 Some("completed") => Ok(TurnTerminalStatus::Completed),
316 Some("failed") => Ok(TurnTerminalStatus::Failed),
317 Some("interrupted") => Ok(TurnTerminalStatus::Interrupted),
318 Some("canceled" | "cancelled") => Ok(TurnTerminalStatus::Canceled),
319 _ => anyhow::bail!("native terminal event has no supported terminal status"),
320 }
321 }
322
323 #[derive(Debug, Clone, thiserror::Error)]
324 #[error(
325 "native thread {thread_id}, turn {turn_id:?}; inspect retained native state without replay"
326 )]
327 struct NativeTurnContext {
328 thread_id: String,
329 turn_id: Option<String>,
330 operation_key: Option<String>,
331 }
332
333 struct NativeTurnClaim {
334 live: InFlightTurn,
335 registration: Option<(TurnRegistry, String)>,
336 registration_published: bool,
337 terminal_observed: bool,
338 cleanup: Option<tokio::task::JoinHandle<Result<()>>>,
339 }
340
341 impl NativeTurnClaim {
342 fn begin_cleanup(&mut self) -> Result<()> {
343 if self.cleanup.is_some() {
344 return Ok(());
345 }
346 let handle = tokio::runtime::Handle::try_current()
347 .context("native turn cleanup has no active runtime; inspect without replay")?;
348 let live = self.live.clone();
349 let registration = self.registration.clone();
350 let registration_published = self.registration_published;
351 let terminal_observed = self.terminal_observed;
352 self.cleanup = Some(handle.spawn(async move {
353 let interrupted = if terminal_observed {
354 Ok(())
355 } else {
356 interrupt_turn_request(&live)
357 .await
358 .map(|_| ())
359 .map_err(|error| anyhow!("native interruption remains uncertain: {}", error.wire.message))
360 };
361 if let Some((registry, key)) = registration {
362 if interrupted.is_ok() {
363 retire_turn_registration(&registry, &key, &live).await;
364 } else if !registration_published {
365 registry.lock().await.entry(key).or_insert_with(|| live.clone());
366 }
367 }
368 if let Err(error) = &interrupted {
369 tracing::error!(%error, thread_id = %live.runtime_thread_id, turn_id = %live.turn_id, "native turn transport cleanup did not confirm interruption");
370 }
371 interrupted
372 }));
373 Ok(())
374 }
375
376 async fn finish(&mut self) -> Result<()> {
377 self.begin_cleanup()?;
378 self.cleanup
379 .as_mut()
380 .expect("started cleanup")
381 .await
382 .context("native cleanup task failed; inspect its canonical receipt without replay")?
383 }
384 }
385
386 impl Drop for NativeTurnClaim {
387 fn drop(&mut self) {
388 if let Err(error) = self.begin_cleanup() {
389 tracing::error!(%error, thread_id = %self.live.runtime_thread_id, turn_id = %self.live.turn_id, "native turn transport cleanup could not be scheduled");
390 }
391 }
392 }
393
394 async fn native_turn_cancelled(token: Option<&CancellationToken>) {
395 match token {
396 Some(token) => token.cancelled().await,
397 None => std::future::pending::<()>().await,
398 }
399 }
400
401 struct ConfirmedNativeTurn {
402 turn_id: String,
403 model: Option<String>,
404 refusal: Option<anyhow::Error>,
405 }
406
407 async fn resolve_native_admission(
408 owner: &Arc<dyn RuntimeOwnerFrontend>,
409 thread_id: &str,
410 operation_key: &str,
411 acknowledgement: Result<Value>,
412 ) -> Result<ConfirmedNativeTurn> {
413 let turn_id = |record: &Value| -> Result<String> {
414 anyhow::ensure!(
415 record.get("thread_id").and_then(Value::as_str) == Some(thread_id),
416 "native owner returned another thread identity"
417 );
418 record
419 .get("id")
420 .and_then(Value::as_str)
421 .filter(|id| !id.is_empty())
422 .map(str::to_owned)
423 .context("native owner returned no turn identity")
424 };
425 let admission = match acknowledgement.and_then(|value| {
426 Ok(ConfirmedNativeTurn {
427 turn_id: turn_id(&value["turn"])?,
428 model: value
429 .pointer("/thread/model")
430 .and_then(Value::as_str)
431 .map(str::to_owned),
432 refusal: None,
433 })
434 }) {
435 Ok(result) => return Ok(result),
436 Err(error) => error,
437 };
438 let refused = admission
439 .downcast_ref::<crate::RuntimeOwnerFailure>()
440 .is_some_and(|failure| (400..500).contains(&failure.status));
441 let deadline = tokio::time::Instant::now() + Duration::from_secs(10);
442 let receipt = loop {
443 let lookup = tokio::time::timeout_at(
444 deadline,
445 owner_calls::execute(
446 owner,
447 RuntimeOwnerRequest::LookupTurnOperation {
448 thread_id: thread_id.to_owned(),
449 operation_key: operation_key.to_owned(),
450 },
451 ),
452 )
453 .await;
454 let error = match lookup {
455 Ok(Ok(receipt)) => break receipt,
456 Ok(Err(error)) => error,
457 Err(_) => {
458 return Err(admission.context(
459 "native turn admission could not be confirmed before the lookup deadline",
460 ));
461 }
462 };
463 match error
464 .downcast_ref::<crate::RuntimeOwnerFailure>()
465 .map(|failure| failure.status)
466 {
467 Some(404) if refused => return Err(admission),
468 Some(404 | 409) => {
469 tokio::time::sleep_until(
470 deadline.min(tokio::time::Instant::now() + Duration::from_millis(200)),
471 )
472 .await;
473 if tokio::time::Instant::now() >= deadline {
474 return Err(admission.context(format!(
475 "native turn admission remained unconfirmed: {error:#}"
476 )));
477 }
478 }
479 _ => {
480 return Err(
481 error.context(format!("could not confirm admission after {admission:#}"))
482 );
483 }
484 }
485 };
486 Ok(ConfirmedNativeTurn {
487 turn_id: turn_id(&receipt)?,
488 model: receipt
489 .get("effective_model")
490 .and_then(Value::as_str)
491 .map(str::to_owned),
492 refusal: refused.then_some(admission),
493 })
494 }
495
496 async fn admit_native_turn(
497 owner: Arc<dyn RuntimeOwnerFrontend>,
498 thread_id: &str,
499 mut body: Value,
500 registration: Option<(TurnRegistry, String)>,
501 connection: Option<crate::connection::ConnectionId>,
502 cancellation: Option<&CancellationToken>,
503 ) -> Result<(NativeTurnClaim, Option<String>, NativeTurnContext)> {
504 let operation_key = Uuid::new_v4().to_string();
505 body["operation_key"] = json!(operation_key);
506 let context = NativeTurnContext {
507 thread_id: thread_id.to_owned(),
508 turn_id: None,
509 operation_key: Some(operation_key.clone()),
510 };
511 let (sender, receiver) = tokio::sync::oneshot::channel();
512 let runtime_thread_id = thread_id.to_owned();
513 let cancel_before_dispatch = cancellation.cloned();
514 tokio::spawn(async move {
515 if sender.is_closed()
516 || cancel_before_dispatch
517 .as_ref()
518 .is_some_and(CancellationToken::is_cancelled)
519 {
520 return;
521 }
522 let acknowledgement = owner_calls::execute(
523 &owner,
524 RuntimeOwnerRequest::StartTurn {
525 thread_id: runtime_thread_id.clone(),
526 body,
527 },
528 )
529 .await;
530 let outcome = async {
531 let accepted = resolve_native_admission(
532 &owner,
533 &runtime_thread_id,
534 &operation_key,
535 acknowledgement,
536 )
537 .await?;
538 let mut claim = NativeTurnClaim {
539 live: InFlightTurn {
540 owner: TurnExecutionOwner::Native(owner),
541 runtime_thread_id: runtime_thread_id.clone(),
542 turn_id: accepted.turn_id,
543 connection,
544 },
545 registration,
546 registration_published: false,
547 terminal_observed: false,
548 cleanup: None,
549 };
550 if let Some(refusal) = accepted.refusal {
551 if let Err(cleanup) = claim.finish().await {
552 return Err(refusal.context(format!(
553 "native cleanup did not confirm interruption: {cleanup:#}"
554 )));
555 }
556 return Err(refusal);
557 }
558 Ok((claim, accepted.model))
559 }
560 .await;
561 if let Err(Err(error)) = sender.send(outcome) {
562 tracing::warn!(%error, %runtime_thread_id, %operation_key, "disconnected native turn admission could not be confirmed");
563 }
564 });
565 let admission = tokio::select! {
566 biased;
567 _ = native_turn_cancelled(cancellation) => Err(anyhow!("control request canceled during native turn admission")),
568 result = receiver => result.context("native turn admission task ended").and_then(|result| result),
569 };
570 let (claim, model) = admission.context(context.clone())?;
571 Ok((claim, model, context))
572 }
573
574 pub(super) async fn message_native_thread<W: AsyncWrite + Unpin>(
575 owner: Arc<dyn RuntimeOwnerFrontend>,
576 thread_id: &str,
577 input: RuntimeTurnInput<'_>,
578 writer: &mut W,
579 registration: Option<(TurnRegistry, String)>,
580 mut transcript: Option<&mut TurnTranscript>,
581 connection: Option<crate::connection::ConnectionId>,
582 ) -> Result<Value> {
583 let mut events = tokio::select! {
584 biased;
585 _ = native_turn_cancelled(input.cancellation) => anyhow::bail!("control request was canceled before native turn admission"),
586 subscription = tokio::time::timeout(Duration::from_secs(30), owner.events(thread_id.to_owned(), 0))
587 => subscription.context("native event observation did not open before admission")??,
588 };
589 anyhow::ensure!(
590 !input
591 .cancellation
592 .is_some_and(CancellationToken::is_cancelled),
593 "control request was canceled before native turn admission"
594 );
595 let mut body = json!({ "prompt": input.input, "allowed_tools": [] });
596 if let Some(workspace) = input.expected_workspace {
597 body["expected_workspace"] = json!(workspace);
598 }
599 if !input.images.is_empty() {
600 body["images"] = json!(input.images);
601 }
602 if let Some(limit) = input.max_output_tokens {
603 body["maxOutputTokens"] = json!(limit);
604 }
605 let (mut claim, model, mut context) = admit_native_turn(
606 owner,
607 thread_id,
608 body,
609 registration,
610 connection,
611 input.cancellation,
612 )
613 .await?;
614 let turn_id = claim.live.turn_id.clone();
615 context.turn_id = Some(turn_id.clone());
616 let response_id = format!("{thread_id}:{turn_id}");
617 if let Some(transcript) = transcript.as_deref_mut() {
618 transcript.model = model;
619 transcript.events.push(EventFrame::ResponseStart {
620 response_id: response_id.clone(),
621 });
622 }
623 let result = async {
624 if let Some((registry, key)) = claim.registration.as_ref() {
625 match registry.lock().await.entry(key.clone()) {
626 std::collections::hash_map::Entry::Occupied(_) => anyhow::bail!(
627 "a turn is already registered for thread {key}; refusing a second registration"
628 ),
629 std::collections::hash_map::Entry::Vacant(slot) => {
630 slot.insert(claim.live.clone());
631 }
632 }
633 claim.registration_published = true;
634 }
635 anyhow::ensure!(
636 !input.cancellation.is_some_and(CancellationToken::is_cancelled),
637 "control request was canceled after native turn admission"
638 );
639 emit_stdio_event(writer, json!({
640 "type": "response_start", "response_id": response_id,
641 })).await?;
642 loop {
643 let frame = tokio::select! {
644 _ = native_turn_cancelled(input.cancellation) => anyhow::bail!("control request canceled; native turn cleanup required"),
645 frame = events.next() => frame,
646 };
647 let Some(frame) = frame else { break; };
648 if frame.event == "stream.end" {
649 anyhow::bail!("native journal observation ended before terminal settlement; no automatic replay");
650 }
651 if frame.data.get("thread_id").and_then(Value::as_str) != Some(thread_id)
652 || frame.data.get("turn_id").and_then(Value::as_str) != Some(turn_id.as_str()) {
653 continue;
654 }
655 let payload = frame.data.get("payload").cloned().unwrap_or(Value::Null);
656 match frame.event.as_str() {
657 "approval.required" | "user_input.required" | "tool_call.requested" => {
658 anyhow::bail!("interactive_execution_unsupported: native owner requested interaction during a tool-free turn");
659 }
660 "item.delta" if payload.get("kind").and_then(Value::as_str) == Some("agent_message") => {
661 if let Some(delta) = payload.get("delta").and_then(Value::as_str).filter(|delta| !delta.is_empty()) {
662 emit_stdio_event(writer, json!({
663 "type": "response_delta", "response_id": response_id, "delta": delta,
664 })).await?;
665 if let Some(transcript) = transcript.as_deref_mut() {
666 transcript.text.push_str(delta);
667 transcript.events.push(EventFrame::ResponseDelta {
668 response_id: response_id.clone(), delta: delta.to_owned(),
669 channel: ResponseChannel::Text,
670 });
671 }
672 }
673 }
674 "turn.completed" => {
675 let record = payload.get("turn").context("native terminal event omitted its turn")?;
676 anyhow::ensure!(
677 record.get("id").and_then(Value::as_str) == Some(turn_id.as_str())
678 && record.get("thread_id").and_then(Value::as_str) == Some(thread_id),
679 "native terminal event has another turn identity"
680 );
681 let status = turn_terminal_status(&payload)?;
682 claim.terminal_observed = true;
683 if let Some(transcript) = transcript.as_deref_mut()
684 && let Some(model) = record.get("effective_model").and_then(Value::as_str)
685 {
686 transcript.model = Some(model.to_owned());
687 }
688 match status {
689 TurnTerminalStatus::Completed => return Ok(record.clone()),
690 _ => anyhow::bail!("{}", record.get("error").and_then(Value::as_str).unwrap_or("native turn stopped without successful completion")),
691 }
692 }
693 _ => {}
694 }
695 }
696 anyhow::bail!("native event stream ended before turn.completed; no automatic replay")
697 }.await;
698 let cleanup = claim.finish().await;
699 let record = match (result, cleanup) {
700 (Ok(record), Ok(())) => record,
701 (Err(error), Ok(())) => return Err(error.context(context)),
702 (Ok(_), Err(error)) => return Err(error.context(context)),
703 (Err(error), Err(cleanup)) => {
704 return Err(error
705 .context(format!(
706 "native cleanup did not confirm interruption: {cleanup:#}"
707 ))
708 .context(context));
709 }
710 };
711 emit_stdio_event(
712 writer,
713 json!({ "type": "response_end", "response_id": response_id }),
714 )
715 .await
716 .context(context)?;
717 if let Some(transcript) = transcript {
718 transcript
719 .events
720 .push(EventFrame::ResponseEnd { response_id });
721 }
722 Ok(json!({
723 "thread_id": thread_id, "status": "accepted", "thread": null, "threads": [],
724 "model": null, "model_provider": null, "cwd": null, "approval_policy": null,
725 "sandbox": null, "events": [], "data": { "turn_id": turn_id, "turn": record },
726 }))
727 }
728
728 lines RUST