返回 CodeWhale
runtime_chat_relay.rs
根目录 / crates / app-server / src / runtime_chat_relay.rs
1 //! Isolated native Runtime execution for account-owned Chat relay commands.
2 //!
3 //! The managed control plane supplies only opaque tenant/thread/turn bindings
4 //! and an exact non-secret provider route. Provider credentials and local
5 //! paths stay inside the Runtime. Every Chat thread is a dedicated
6 //! [`RuntimeThreadManager`] thread with an empty model-visible tool allowlist;
7 //! the active interactive TUI thread is never reused.
8
9 use std::{
10 collections::{BTreeMap, HashSet},
11 fs::{self, File},
12 path::{Path, PathBuf},
13 sync::Arc,
14 time::{Duration, Instant},
15 };
16
17 use anyhow::{Context, Result, bail};
18 use codewhale_plugins::PluginRegistry;
19 use parking_lot::Mutex;
20 use serde::{Deserialize, Serialize};
21 use serde_json::{Value, json};
22 use sha2::{Digest, Sha256};
23
24 use codewhale_engine::{
25 core::engine::ISOLATED_CHAT_SYSTEM_PROMPT,
26 runtime_threads::{
27 RuntimeEventRecord, RuntimeTurnStatus, manager::CreateThreadRequest,
28 manager::RuntimeThreadManager, manager::RuntimeThreadManagerConfig,
29 manager::StartTurnRequest,
30 },
31 };
32 use codewhale_runtime::config::{Config, MemoryBackend, MemoryConfig, SkillsConfig};
33
34 #[cfg(test)]
35 use codewhale_runtime::config::ContextConfig;
36
37 const STATE_SCHEMA_VERSION: u32 = 2;
38 const MAX_RELAY_ID_BYTES: usize = 240;
39 const MAX_OPERATION_KEY_BYTES: usize = 128;
40 const STATE_FILE: &str = "runtime-chat-bindings.json";
41 const SCOPE_LOCK_FILE: &str = "runtime-chat.owner.lock";
42
43 #[cfg(test)]
44 static TEST_STATE_PERSIST_FAILURES: std::sync::Mutex<Vec<(PathBuf, usize)>> =
45 std::sync::Mutex::new(Vec::new());
46
47 #[cfg(test)]
48 fn inject_state_persist_failures(path: &Path, count: usize) {
49 assert!(count > 0);
50 TEST_STATE_PERSIST_FAILURES
51 .lock()
52 .unwrap_or_else(std::sync::PoisonError::into_inner)
53 .push((path.to_path_buf(), count));
54 }
55
56 #[cfg(test)]
57 fn take_state_persist_failure(path: &Path) -> bool {
58 let mut failures = TEST_STATE_PERSIST_FAILURES
59 .lock()
60 .unwrap_or_else(std::sync::PoisonError::into_inner);
61 let Some(index) = failures.iter().position(|(target, _)| target == path) else {
62 return false;
63 };
64 if failures[index].1 > 1 {
65 failures[index].1 -= 1;
66 } else {
67 failures.remove(index);
68 }
69 true
70 }
71
72 #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
73 #[serde(rename_all = "camelCase", deny_unknown_fields)]
74 pub struct RuntimeChatPrompt {
75 #[serde(default, skip_serializing_if = "Option::is_none")]
76 pub structured_review: Option<codewhale_protocol::op::ReviewOperation>,
77 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub account_model_owner: Option<String>,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub profile_constitution:
81 Option<codewhale_config::user_constitution::ProfileConstitutionSnapshot>,
82 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub max_output_tokens: Option<std::num::NonZeroU32>,
84 #[serde(rename = "type")]
85 pub command_type: String,
86 pub run_id: String,
87 pub turn_id: String,
88 pub operation_key: String,
89 pub runtime_binding_id: String,
90 pub runtime_thread_id: String,
91 pub prompt: String,
92 #[serde(default, skip_serializing_if = "Vec::is_empty")]
93 pub images: Vec<codewhale_app_server_protocol::runtime::RuntimeImageInput>,
94 #[serde(default, skip_serializing_if = "Option::is_none")]
95 pub system_prompt: Option<String>,
96 pub model: String,
97 pub model_provider: String,
98 pub model_provider_id: String,
99 #[serde(default, skip_serializing_if = "Option::is_none")]
100 pub reasoning_effort: Option<String>,
101 pub allowed_tools: Vec<String>,
102 pub mode: String,
103 pub requested_mode: String,
104 pub workspace: RuntimeChatWorkspace,
105 }
106
107 #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
108 #[serde(rename_all = "camelCase", deny_unknown_fields)]
109 pub struct RuntimeChatWorkspace {
110 pub id: String,
111 pub target_ref: String,
112 }
113
114 #[derive(Debug, Clone, PartialEq, Eq)]
115 pub struct RuntimeChatControlScope {
116 pub(crate) runtime_binding_id: String,
117 pub(crate) runtime_thread_id: String,
118 }
119
120 #[derive(Debug, Clone)]
121 pub struct RuntimeChatProjection {
122 pub run_id: String,
123 pub native_thread_id: String,
124 pub native_seq: u64,
125 pub source_event_id: String,
126 pub virtual_thread_id: String,
127 pub virtual_turn_id: String,
128 pub event: &'static str,
129 pub timestamp: String,
130 pub payload: Value,
131 }
132
133 #[derive(Clone)]
134 pub(crate) struct RuntimeChatRelayHost {
135 manager: Arc<RuntimeThreadManager>,
136 config: Arc<Config>,
137 state: Arc<Mutex<RelayState>>,
138 state_path: Arc<PathBuf>,
139 target_ref: Arc<String>,
140 session_id: Arc<String>,
141 _scope_lock: Arc<RelayScopeLock>,
142 apply_lock: Arc<tokio::sync::Mutex<()>>,
143 inference_ownership:
144 Arc<Mutex<Option<codewhale_engine::client::RuntimeChatInferenceOwnership>>>,
145 claimed_projections: Arc<Mutex<HashSet<(String, u64)>>>,
146 authorized_run_id: Arc<Mutex<Option<String>>>,
147 }
148
149 #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
150 #[serde(rename_all = "camelCase", deny_unknown_fields)]
151 struct RelayState {
152 schema_version: u32,
153 #[serde(default, skip_serializing_if = "Option::is_none")]
154 owner_scope_fingerprint: Option<String>,
155 #[serde(default)]
156 bindings: Vec<RelayThreadBinding>,
157 }
158
159 impl Default for RelayState {
160 fn default() -> Self {
161 Self {
162 schema_version: STATE_SCHEMA_VERSION,
163 owner_scope_fingerprint: None,
164 bindings: Vec::new(),
165 }
166 }
167 }
168
169 #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
170 #[serde(rename_all = "camelCase", deny_unknown_fields)]
171 struct RelayThreadBinding {
172 run_id: String,
173 runtime_binding_id: String,
174 virtual_thread_id: String,
175 native_thread_id: String,
176 model: String,
177 model_provider: String,
178 model_provider_id: String,
179 first_operation_fingerprint: String,
180 system_prompt_fingerprint: Option<String>,
181 #[serde(default)]
182 turns: BTreeMap<String, RelayTurnBinding>,
183 #[serde(default)]
184 projected_native_seq: u64,
185 }
186
187 #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
188 #[serde(rename_all = "camelCase", deny_unknown_fields)]
189 struct RelayTurnBinding {
190 #[serde(default, skip_serializing_if = "Option::is_none")]
191 review_request_fingerprint: Option<String>,
192 native_turn_id: String,
193 operation_fingerprint: String,
194 request_fingerprint: String,
195 #[serde(default)]
196 terminal_projected: bool,
197 /// True only when the deterministic reservation was durably written but
198 /// native start was proven to have rejected before accepting provider work.
199 /// This distinguishes a retryable reservation from an already-projected
200 /// terminal turn, whose exact replay must remain settled.
201 #[serde(default)]
202 start_rejected: bool,
203 }
204
205 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
206 enum TurnReservationDisposition {
207 New,
208 Reopened,
209 ExistingUnsettled,
210 ExistingTerminal,
211 }
212
213 impl RelayState {
214 fn validate(&self) -> Result<()> {
215 if self.schema_version != STATE_SCHEMA_VERSION {
216 bail!("Runtime Chat binding state uses an unsupported schema");
217 }
218 if let Some(owner) = self.owner_scope_fingerprint.as_deref() {
219 validate_fingerprint(owner)?;
220 } else if !self.bindings.is_empty() {
221 bail!("Runtime Chat binding state has no account owner");
222 }
223 let mut binding_ids = HashSet::new();
224 let mut virtual_threads = HashSet::new();
225 let mut native_threads = HashSet::new();
226 for binding in &self.bindings {
227 validate_relay_id(&binding.run_id, "run id")?;
228 validate_relay_id(&binding.runtime_binding_id, "binding id")?;
229 validate_virtual_thread_id(&binding.virtual_thread_id)?;
230 validate_native_record_id(&binding.native_thread_id, "native thread id")?;
231 validate_route_id(&binding.model_provider, "provider id")?;
232 validate_route_id(&binding.model_provider_id, "model-provider id")?;
233 validate_model_id(&binding.model)?;
234 validate_fingerprint(&binding.first_operation_fingerprint)?;
235 if let Some(fingerprint) = binding.system_prompt_fingerprint.as_deref() {
236 validate_fingerprint(fingerprint)?;
237 }
238 if !binding_ids.insert(binding.runtime_binding_id.clone())
239 || !virtual_threads.insert(binding.virtual_thread_id.clone())
240 || !native_threads.insert(binding.native_thread_id.clone())
241 {
242 bail!("Runtime Chat binding state contains duplicate thread authority");
243 }
244 for (virtual_turn_id, turn) in &binding.turns {
245 validate_virtual_turn_id(virtual_turn_id)?;
246 validate_native_record_id(&turn.native_turn_id, "native turn id")?;
247 if let Some(fingerprint) = &turn.review_request_fingerprint {
248 validate_fingerprint(fingerprint)?;
249 }
250 validate_fingerprint(&turn.operation_fingerprint)?;
251 validate_fingerprint(&turn.request_fingerprint)?;
252 }
253 }
254 Ok(())
255 }
256 }
257
258 impl RuntimeChatRelayHost {
259 pub(crate) async fn workspace_restore_guard(
260 &self,
261 workspace: &Path,
262 ) -> Result<tokio::sync::OwnedRwLockWriteGuard<()>, String> {
263 self.manager
264 .workspace_restore_guard(workspace)
265 .await
266 .map_err(|error| error.to_string())
267 }
268
269 pub(crate) fn open(
270 config: Config,
271 _plugin_registry: Arc<PluginRegistry>,
272 private_root: PathBuf,
273 target_ref: String,
274 session_id: String,
275 ) -> Result<Self, String> {
276 validate_owner_component(&target_ref, "target")?;
277 validate_owner_component(&session_id, "session")?;
278 let private_dir = scoped_private_dir(&private_root, &target_ref, &session_id);
279 fs::create_dir_all(&private_dir)
280 .map_err(|_| "Runtime Chat could not prepare private local state.".to_string())?;
281 #[cfg(unix)]
282 {
283 use std::os::unix::fs::PermissionsExt;
284 fs::set_permissions(&private_dir, fs::Permissions::from_mode(0o700))
285 .map_err(|_| "Runtime Chat could not protect private local state.".to_string())?;
286 }
287 let scope_lock =
288 RelayScopeLock::acquire(&private_dir.join(SCOPE_LOCK_FILE)).map_err(|error| {
289 // Only WouldBlock is genuine contention. Any other lock
290 // failure is a local IO fault, and misreporting it as
291 // ownership hides the cause (#5735's flake evidence).
292 let contention = error
293 .downcast_ref::<std::io::Error>()
294 .is_some_and(|io| io.kind() == std::io::ErrorKind::WouldBlock);
295 if contention {
296 "Another Codewhale process already owns this Runtime Chat account session."
297 .to_string()
298 } else {
299 format!("Runtime Chat could not take its owner lock: {error:#}")
300 }
301 })?;
302 let state_path = private_dir.join(STATE_FILE);
303 let state = load_state(&state_path).map_err(|_| {
304 "The saved Runtime Chat binding state could not be trusted.".to_string()
305 })?;
306 state.validate().map_err(|_| {
307 "The saved Runtime Chat binding state could not be trusted.".to_string()
308 })?;
309
310 // Reuse the native Runtime thread engine and durable records, but keep
311 // account Chat in its own private store and empty workspace. The
312 // dedicated system-prompt override below is the model-visible boundary;
313 // this workspace/config hardening also prevents local project, memory,
314 // instruction, and skill sources from becoming fallback context.
315 let (execution_config, chat_workspace) =
316 isolated_chat_execution_config(&config, &private_dir)?;
317 let relay_plugin_registry = Arc::new(PluginRegistry::empty(&chat_workspace));
318 let task_data_dir = private_dir.join("tasks");
319 let mut manager_cfg = RuntimeThreadManagerConfig::from_task_data_dir(task_data_dir);
320 manager_cfg.data_dir = private_dir.join("runtime");
321 let manager = RuntimeThreadManager::open_host(
322 execution_config,
323 chat_workspace,
324 manager_cfg,
325 relay_plugin_registry,
326 codewhale_engine::core::engine::EngineHostProfile::Headless,
327 None,
328 None,
329 )
330 .map_err(|_| "Runtime Chat could not open its isolated native thread store.".to_string())?;
331
332 Ok(Self {
333 manager: Arc::new(manager),
334 config: Arc::new(config),
335 state: Arc::new(Mutex::new(state)),
336 state_path: Arc::new(state_path),
337 target_ref: Arc::new(target_ref),
338 session_id: Arc::new(session_id),
339 _scope_lock: Arc::new(scope_lock),
340 apply_lock: Arc::new(tokio::sync::Mutex::new(())),
341 inference_ownership: Arc::new(Mutex::new(None)),
342 claimed_projections: Arc::new(Mutex::new(HashSet::new())),
343 authorized_run_id: Arc::new(Mutex::new(None)),
344 })
345 }
346
347 pub(crate) fn catalog(&self, challenge: &str) -> Result<Value, String> {
348 self.ensure_account_bound()?;
349 crate::runtime_api::runtime_chat_relay_catalog(&self.config, challenge)
350 }
351
352 pub(crate) fn catalog_payload_fingerprint(payload: &Value) -> Result<String, String> {
353 serde_json::to_vec(&canonical_json_value(payload))
354 .map(|bytes| hex_digest(Sha256::digest(bytes)))
355 .map_err(|_| "Runtime Chat could not fingerprint its safe catalog.".to_string())
356 }
357
358 pub(crate) fn bind_account(&self, account_ref: &str, target_ref: &str) -> Result<(), String> {
359 validate_owner_component(account_ref, "account")?;
360 if target_ref != self.target_ref.as_str() {
361 return Err("The Runtime Chat account owner does not match this target.".to_string());
362 }
363 let owner = owner_scope_fingerprint(account_ref, target_ref, &self.session_id);
364 self.persist_state_update_blocking(
365 "Runtime Chat could not persist its account ownership.",
366 |state| bind_owner_scope(state, &owner),
367 )
368 }
369
370 pub(crate) fn authorize_run(&self, run_id: &str) -> Result<(), String> {
371 validate_relay_id(run_id, "run id")
372 .map_err(|_| "The Runtime Chat attachment has an invalid run identity.".to_string())?;
373 self.ensure_account_bound()?;
374 let durable_other_run_is_unsettled = self.state.lock().bindings.iter().any(|binding| {
375 binding.run_id != run_id && binding.turns.values().any(|turn| !turn.terminal_projected)
376 });
377 if durable_other_run_is_unsettled {
378 return Err(
379 "Finish or interrupt the active Runtime Chat turn before attaching another run."
380 .to_string(),
381 );
382 }
383 if self.has_any_unsettled_turns() && self.inference_ownership.lock().is_none() {
384 let ownership =
385 codewhale_engine::client::try_acquire_runtime_chat_inference_ownership()
386 .ok_or_else(|| {
387 "Finish the active local turn before recovering Runtime Chat.".to_string()
388 })?;
389 *self.inference_ownership.lock() = Some(ownership);
390 }
391 *self.authorized_run_id.lock() = Some(run_id.to_string());
392 Ok(())
393 }
394
395 #[cfg(test)]
396 pub(crate) fn has_unsettled_authorized_turns(&self) -> bool {
397 self.authorized_run_id
398 .lock()
399 .as_deref()
400 .is_some_and(|run_id| self.has_unsettled_turns_for_run(run_id))
401 }
402
403 pub(crate) fn has_any_unsettled_turns(&self) -> bool {
404 self.state
405 .lock()
406 .bindings
407 .iter()
408 .any(|binding| binding.turns.values().any(|turn| !turn.terminal_projected))
409 }
410
411 #[cfg(test)]
412 async fn ensure_inference_ownership(&self) {
413 if self.inference_ownership.lock().is_some() {
414 return;
415 }
416 let ownership = codewhale_engine::client::acquire_runtime_chat_inference_ownership().await;
417 let mut current = self.inference_ownership.lock();
418 if current.is_none() {
419 *current = Some(ownership);
420 }
421 }
422
423 fn try_ensure_inference_ownership(&self) -> Result<(), String> {
424 if self.inference_ownership.lock().is_some() {
425 return Ok(());
426 }
427 let ownership = codewhale_engine::client::try_acquire_runtime_chat_inference_ownership()
428 .ok_or_else(|| {
429 "Finish the active local provider work before starting Runtime Chat.".to_string()
430 })?;
431 let mut current = self.inference_ownership.lock();
432 if current.is_none() {
433 *current = Some(ownership);
434 }
435 Ok(())
436 }
437
438 pub(crate) fn recover_inference_ownership_for_pending_delivery(&self) -> Result<(), String> {
439 if self.inference_ownership.lock().is_some() {
440 return Ok(());
441 }
442 let ownership = codewhale_engine::client::try_acquire_runtime_chat_inference_ownership()
443 .ok_or_else(|| {
444 "Finish the active local turn before recovering Runtime Chat delivery.".to_string()
445 })?;
446 *self.inference_ownership.lock() = Some(ownership);
447 Ok(())
448 }
449
450 pub(crate) fn release_inference_ownership_if_settled(&self) {
451 if !self.has_any_unsettled_turns() {
452 self.inference_ownership.lock().take();
453 }
454 }
455
456 pub(crate) fn is_exact_prompt_replay(
457 &self,
458 command: &RuntimeChatPrompt,
459 ) -> Result<bool, String> {
460 command.validate_shape()?;
461 let operation_fingerprint = fingerprint(&command.operation_key);
462 let request_fingerprint = runtime_chat_request_fingerprint(command)?;
463 let state = self.state.lock();
464 let by_binding = state
465 .bindings
466 .iter()
467 .position(|binding| binding.runtime_binding_id == command.runtime_binding_id);
468 let by_thread = state
469 .bindings
470 .iter()
471 .position(|binding| binding.virtual_thread_id == command.runtime_thread_id);
472 let binding = match (by_binding, by_thread) {
473 (None, None) => return Ok(false),
474 (Some(binding_index), Some(thread_index)) if binding_index == thread_index => {
475 &state.bindings[binding_index]
476 }
477 _ => {
478 return Err(
479 "The Runtime Chat thread authority does not match its binding.".to_string(),
480 );
481 }
482 };
483 if binding.run_id != command.run_id {
484 return Err("The Runtime Chat replay belongs to another run.".to_string());
485 }
486 let Some(turn) = binding.turns.get(&command.turn_id) else {
487 return Ok(false);
488 };
489 if turn.operation_fingerprint == operation_fingerprint
490 && turn.request_fingerprint == request_fingerprint
491 {
492 return Ok(true);
493 }
494 Err("The Runtime Chat turn binding does not match its replay.".to_string())
495 }
496
497 pub(crate) fn scope_matches(&self, target_ref: &str, session_id: &str) -> bool {
498 self.target_ref.as_str() == target_ref && self.session_id.as_str() == session_id
499 }
500
501 #[cfg(test)]
502 pub(crate) fn configured_default_model_for_tests(&self) -> String {
503 self.config.default_model()
504 }
505
506 #[cfg(test)]
507 pub(crate) fn inference_ownership_is_held_for_tests(&self) -> bool {
508 self.inference_ownership.lock().is_some()
509 }
510
511 #[cfg(test)]
512 pub(crate) async fn acquire_inference_ownership_for_tests(&self) {
513 self.ensure_inference_ownership().await;
514 }
515
516 #[cfg(test)]
517 pub(crate) async fn install_unsettled_turn_for_tests(
518 &self,
519 run_id: &str,
520 native_thread_id: &str,
521 virtual_thread_id: &str,
522 virtual_turn_id: &str,
523 ) -> Result<(), String> {
524 self.insert_binding(RelayThreadBinding {
525 run_id: run_id.to_string(),
526 runtime_binding_id: "binding_test_fixture".to_string(),
527 virtual_thread_id: virtual_thread_id.to_string(),
528 native_thread_id: native_thread_id.to_string(),
529 model: "model-1".to_string(),
530 model_provider: "custom".to_string(),
531 model_provider_id: "local-provider".to_string(),
532 first_operation_fingerprint: fingerprint("operation-test-fixture"),
533 system_prompt_fingerprint: None,
534 turns: BTreeMap::from([(
535 virtual_turn_id.to_string(),
536 RelayTurnBinding {
537 review_request_fingerprint: None,
538 native_turn_id: "turn_test_fixture".to_string(),
539 operation_fingerprint: fingerprint("operation-test-fixture"),
540 request_fingerprint: fingerprint("request-test-fixture"),
541 terminal_projected: false,
542 start_rejected: false,
543 },
544 )]),
545 projected_native_seq: 0,
546 })
547 .await
548 }
549
550 #[cfg(test)]
551 pub(crate) async fn install_prompt_replay_for_tests(
552 &self,
553 command: &RuntimeChatPrompt,
554 terminal_projected: bool,
555 ) -> Result<(), String> {
556 command.validate_shape()?;
557 let operation_fingerprint = fingerprint(&command.operation_key);
558 let request_fingerprint = runtime_chat_request_fingerprint(command)?;
559 let native_thread_id = self
560 .manager
561 .create_thread(CreateThreadRequest {
562 whale_id: None,
563 child_posture: None,
564 route_selection: None,
565 parent_thread_id: None,
566 parent_edge_kind: None,
567 run_id: None,
568 origin: None,
569 executor: None,
570 environment: None,
571 agent_preset: None,
572 operation_key: None,
573 model: Some(command.model.clone()),
574 model_provider: Some(command.model_provider.clone()),
575 model_provider_id: Some(command.model_provider_id.clone()),
576 reasoning_effort: command.reasoning_effort.clone(),
577 allowed_tools: Some(Vec::new()),
578 workspace: None,
579 mode: Some("agent".to_string()),
580 permission_posture: Some("ask".to_string()),
581 allow_shell: Some(false),
582 trust_mode: Some(false),
583 auto_approve: Some(false),
584 archived: false,
585 system_prompt: Some(dedicated_chat_system_prompt(
586 command.system_prompt.as_deref(),
587 )),
588 task_id: None,
589 dynamic_tools: Vec::new(),
590 environments: Vec::new(),
591 add_dirs: Vec::new(),
592 disallowed_tools: Vec::new(),
593 })
594 .await
595 .map_err(|_| "Runtime Chat could not create its replay fixture.".to_string())?
596 .id;
597 let native_turn_id = reserved_native_turn_id(
598 &native_thread_id,
599 &command.runtime_binding_id,
600 &command.turn_id,
601 &operation_fingerprint,
602 );
603 self.insert_binding(RelayThreadBinding {
604 run_id: command.run_id.clone(),
605 runtime_binding_id: command.runtime_binding_id.clone(),
606 virtual_thread_id: command.runtime_thread_id.clone(),
607 native_thread_id,
608 model: command.model.clone(),
609 model_provider: command.model_provider.clone(),
610 model_provider_id: command.model_provider_id.clone(),
611 first_operation_fingerprint: operation_fingerprint.clone(),
612 system_prompt_fingerprint: command.system_prompt.as_deref().map(fingerprint),
613 turns: BTreeMap::from([(
614 command.turn_id.clone(),
615 RelayTurnBinding {
616 review_request_fingerprint: command
617 .structured_review
618 .as_ref()
619 .map(codewhale_engine::core::engine::review::fingerprint)
620 .transpose()
621 .map_err(|error| error.to_string())?,
622 native_turn_id,
623 operation_fingerprint,
624 request_fingerprint,
625 terminal_projected,
626 start_rejected: false,
627 },
628 )]),
629 projected_native_seq: if terminal_projected { 1 } else { 0 },
630 })
631 .await
632 }
633
634 fn has_unsettled_turns_for_run(&self, run_id: &str) -> bool {
635 self.state.lock().bindings.iter().any(|binding| {
636 binding.run_id == run_id && binding.turns.values().any(|turn| !turn.terminal_projected)
637 })
638 }
639
640 pub(crate) async fn apply_prompt(&self, command: &RuntimeChatPrompt) -> Result<(), String> {
641 self.ensure_account_bound()?;
642 if self.authorized_run_id.lock().as_deref() != Some(command.run_id.as_str()) {
643 return Err("The Runtime Chat command is not authorized for this run.".to_string());
644 }
645 let _apply = self.apply_lock.lock().await;
646 command.validate_shape()?;
647 let operation_fingerprint = fingerprint(&command.operation_key);
648 let request_fingerprint = runtime_chat_request_fingerprint(command)?;
649 let system_prompt_fingerprint = command.system_prompt.as_deref().map(fingerprint);
650 let review_request_fingerprint = command
651 .structured_review
652 .as_ref()
653 .map(codewhale_engine::core::engine::review::fingerprint)
654 .transpose()
655 .map_err(|error| error.to_string())?;
656
657 let existing = {
658 let state = self.state.lock();
659 let by_binding = state
660 .bindings
661 .iter()
662 .position(|binding| binding.runtime_binding_id == command.runtime_binding_id);
663 let by_thread = state
664 .bindings
665 .iter()
666 .position(|binding| binding.virtual_thread_id == command.runtime_thread_id);
667 match (by_binding, by_thread) {
668 (None, None) => None,
669 (Some(binding_index), Some(thread_index)) if binding_index == thread_index => {
670 Some(state.bindings[binding_index].clone())
671 }
672 _ => {
673 return Err(
674 "The Runtime Chat thread authority does not match its binding.".to_string(),
675 );
676 }
677 }
678 };
679 let exact_operation_replay = existing.as_ref().is_some_and(|binding| {
680 binding.turns.get(&command.turn_id).is_some_and(|turn| {
681 turn.operation_fingerprint == operation_fingerprint
682 && turn.request_fingerprint == request_fingerprint
683 })
684 });
685 if !exact_operation_replay {
686 self.validate_route(command)?;
687 }
688 if !exact_operation_replay && self.has_unsettled_turns_for_run(&command.run_id) {
689 return Err(
690 "Finish or interrupt the active Runtime Chat turn before starting another."
691 .to_string(),
692 );
693 }
694
695 let binding = if let Some(binding) = existing {
696 validate_existing_binding(
697 &binding,
698 command,
699 &operation_fingerprint,
700 system_prompt_fingerprint.as_deref(),
701 )?;
702 self.manager
703 .get_thread(&binding.native_thread_id)
704 .await
705 .map_err(|_| "The isolated Runtime Chat thread is unavailable.".to_string())?;
706 binding
707 } else {
708 let thread = self
709 .manager
710 .create_thread(CreateThreadRequest {
711 whale_id: None,
712 child_posture: None,
713 route_selection: None,
714 parent_edge_kind: None,
715 run_id: None,
716 origin: None,
717 operation_key: None,
718 model: Some(command.model.clone()),
719 model_provider: Some(command.model_provider.clone()),
720 model_provider_id: Some(command.model_provider_id.clone()),
721 reasoning_effort: command.reasoning_effort.clone(),
722 allowed_tools: Some(Vec::new()),
723 add_dirs: Vec::new(),
724 workspace: None,
725 // The native engine's existing Act loop executes a pure
726 // chat turn once its model-visible tool catalog is empty.
727 // `chat` remains the account wire mode, not a second loop.
728 mode: Some("agent".to_string()),
729 permission_posture: Some("ask".to_string()),
730 allow_shell: Some(false),
731 trust_mode: Some(false),
732 auto_approve: Some(false),
733 archived: false,
734 system_prompt: Some(dedicated_chat_system_prompt(
735 command.system_prompt.as_deref(),
736 )),
737 task_id: None,
738 parent_thread_id: None,
739 executor: None,
740 environment: None,
741 agent_preset: None,
742 dynamic_tools: Vec::new(),
743 environments: Vec::new(),
744 disallowed_tools: Vec::new(),
745 })
746 .await
747 .map_err(|_| {
748 "Runtime Chat could not create an isolated native thread.".to_string()
749 })?;
750 let binding = RelayThreadBinding {
751 runtime_binding_id: command.runtime_binding_id.clone(),
752 run_id: command.run_id.clone(),
753 virtual_thread_id: command.runtime_thread_id.clone(),
754 native_thread_id: thread.id,
755 model: command.model.clone(),
756 model_provider: command.model_provider.clone(),
757 model_provider_id: command.model_provider_id.clone(),
758 first_operation_fingerprint: operation_fingerprint.clone(),
759 system_prompt_fingerprint,
760 turns: BTreeMap::new(),
761 projected_native_seq: 0,
762 };
763 if let Err(error) = self.insert_binding(binding.clone()).await {
764 let _ = self
765 .manager
766 .discard_empty_thread(&binding.native_thread_id)
767 .await;
768 return Err(error);
769 }
770 binding
771 };
772
773 // Reject virtual-turn and operation-key drift before asking the native
774 // manager to start anything. RuntimeThreadManager independently
775 // enforces the same operation-key idempotency for crash replay.
776 if let Some(existing_turn) = binding.turns.get(&command.turn_id)
777 && (existing_turn.operation_fingerprint != operation_fingerprint
778 || existing_turn.request_fingerprint != request_fingerprint)
779 {
780 return Err("The Runtime Chat turn binding does not match its replay.".to_string());
781 }
782 if binding.turns.iter().any(|(virtual_turn_id, turn)| {
783 virtual_turn_id != &command.turn_id
784 && turn.operation_fingerprint == operation_fingerprint
785 }) {
786 return Err("The Runtime Chat operation key belongs to another turn.".to_string());
787 }
788
789 // Preallocate and persist the exact native id before the manager may
790 // submit anything to a provider. RuntimeThreadManager binds the same id
791 // inside its operation-key transaction, eliminating the crash window
792 // between native acceptance and relay correlation.
793 let reserved_native_turn_id = reserved_native_turn_id(
794 &binding.native_thread_id,
795 &command.runtime_binding_id,
796 &command.turn_id,
797 &operation_fingerprint,
798 );
799 let reservation = self
800 .reserve_turn(
801 &command.runtime_binding_id,
802 &command.runtime_thread_id,
803 &command.turn_id,
804 &reserved_native_turn_id,
805 &operation_fingerprint,
806 &request_fingerprint,
807 review_request_fingerprint.as_deref(),
808 )
809 .await?;
810 if matches!(reservation, TurnReservationDisposition::ExistingTerminal) {
811 return Ok(());
812 }
813
814 // The exclusive provider-request lease is acquired only after all
815 // command/route/binding validation and deterministic reservation are
816 // durable, but before native Runtime can resolve Auto or dispatch any
817 // provider request. At the common client seam it also blocks advisor,
818 // detached-subagent, compaction, purge, and interactive requests that
819 // could otherwise feed this attached CWC run.
820 if let Err(error) = self.try_ensure_inference_ownership() {
821 if !matches!(reservation, TurnReservationDisposition::ExistingUnsettled) {
822 self.finish_turn_reservation(
823 &command.runtime_binding_id,
824 &command.runtime_thread_id,
825 &command.turn_id,
826 )
827 .await?;
828 }
829 self.release_inference_ownership_if_settled();
830 return Err(error);
831 }
832
833 let admission = if let Some(review) = &command.structured_review {
834 self.manager
835 .start_review_turn_with_reserved_id(
836 &binding.native_thread_id,
837 codewhale_engine::runtime_threads::manager::StartReviewRequest {
838 review: review.clone(),
839 operation_key: command.operation_key.clone(),
840 account_model_owner: command.account_model_owner.clone(),
841 model: command.model.clone(),
842 model_provider: None,
843 model_provider_id: None,
844 reasoning_effort: command.reasoning_effort.clone(),
845 max_output_tokens: command
846 .max_output_tokens
847 .ok_or_else(|| "Review output allowance is required.".to_string())?,
848 },
849 &reserved_native_turn_id,
850 )
851 .await
852 } else {
853 self.manager
854 .start_turn_with_reserved_id(
855 &binding.native_thread_id,
856 StartTurnRequest {
857 account_model_owner: command.account_model_owner.clone(),
858 profile_constitution: command.profile_constitution.clone(),
859 expected_workspace: None,
860 max_output_tokens: command.max_output_tokens,
861 prompt: command.prompt.clone(),
862 images: command.images.clone(),
863 operation_key: Some(command.operation_key.clone()),
864 input_summary: None,
865 model: Some(command.model.clone()),
866 reasoning_effort: command.reasoning_effort.clone(),
867 allowed_tools: Some(Vec::new()),
868 mode: Some("agent".to_string()),
869 permission_posture: Some("ask".to_string()),
870 allow_shell: Some(false),
871 trust_mode: Some(false),
872 auto_approve: Some(false),
873 dynamic_tools: Vec::new(),
874 environment_id: None,
875 model_provider: None,
876 model_provider_id: None,
877 user_command: None,
878 },
879 &reserved_native_turn_id,
880 )
881 .await
882 };
883 let turn = match admission {
884 Ok(turn) => turn,
885 Err(error) => {
886 // A process may crash after the relay reservation is durable
887 // but before Runtime persists its operation binding/turn. On
888 // exact replay that appears as ExistingUnsettled. Settle it
889 // only when the native thread snapshot positively proves the
890 // deterministic turn id was never accepted; any unreadable or
891 // present native record stays fail-closed and projectable.
892 let native_turn_is_durable = self
893 .manager
894 .get_thread_detail(&binding.native_thread_id)
895 .await
896 .map(|detail| {
897 detail
898 .turns
899 .iter()
900 .any(|turn| turn.id == reserved_native_turn_id)
901 })
902 .unwrap_or(true);
903 if !native_turn_is_durable {
904 self.finish_turn_reservation(
905 &command.runtime_binding_id,
906 &command.runtime_thread_id,
907 &command.turn_id,
908 )
909 .await?;
910 }
911 self.release_inference_ownership_if_settled();
912 return Err(sanitized_runtime_error("start", &error));
913 }
914 };
915 debug_assert_eq!(turn.id, reserved_native_turn_id);
916 Ok(())
917 }
918
919 pub(crate) async fn interrupt(
920 &self,
921 run_id: &str,
922 scope: &RuntimeChatControlScope,
923 virtual_turn_id: &str,
924 ) -> Result<(), String> {
925 self.ensure_account_bound()?;
926 validate_relay_id(run_id, "run id")
927 .map_err(|_| "The Runtime Chat interrupt run is invalid.".to_string())?;
928 validate_relay_id(&scope.runtime_binding_id, "binding id")
929 .map_err(|_| "The Runtime Chat interrupt binding is invalid.".to_string())?;
930 validate_virtual_thread_id(&scope.runtime_thread_id)
931 .map_err(|_| "The Runtime Chat interrupt thread is invalid.".to_string())?;
932 validate_virtual_turn_id(virtual_turn_id)
933 .map_err(|_| "The Runtime Chat interrupt turn is invalid.".to_string())?;
934 let (native_thread_id, native_turn_id) = {
935 let state = self.state.lock();
936 resolve_interrupt_target(&state, run_id, scope, virtual_turn_id)?
937 };
938
939 let detail = self
940 .manager
941 .get_thread_detail(&native_thread_id)
942 .await
943 .map_err(|_| "The isolated Runtime Chat thread is unavailable.".to_string())?;
944 let turn = detail
945 .turns
946 .iter()
947 .find(|turn| turn.id == native_turn_id)
948 .ok_or_else(|| "The isolated Runtime Chat turn is unavailable.".to_string())?;
949 if !matches!(
950 turn.status,
951 RuntimeTurnStatus::Queued | RuntimeTurnStatus::InProgress
952 ) {
953 // Exact replay after the terminal boundary is already applied.
954 return Ok(());
955 }
956 self.manager
957 .interrupt_turn(&native_thread_id, &native_turn_id)
958 .await
959 .map(|_| ())
960 .map_err(|error| sanitized_runtime_error("interrupt", &error))
961 }
962
963 /// Return at most one not-yet-journaled projection per poll. The caller
964 /// journals it before advancing `projected_native_seq`, so a crash can
965 /// cause a safe replay but never silently lose an accepted native event.
966 pub(crate) async fn pending_projections(&self) -> Result<Vec<RuntimeChatProjection>, String> {
967 let Some(authorized_run_id) = self.authorized_run_id.lock().clone() else {
968 return Ok(Vec::new());
969 };
970 let bindings = {
971 let state = self.state.lock();
972 if state.owner_scope_fingerprint.is_none() {
973 return Ok(Vec::new());
974 }
975 state
976 .bindings
977 .iter()
978 .filter(|binding| binding.run_id == authorized_run_id)
979 .cloned()
980 .collect::<Vec<_>>()
981 };
982 for binding in bindings {
983 let events = self
984 .manager
985 .events_since_async(
986 &binding.native_thread_id,
987 Some(binding.projected_native_seq),
988 )
989 .await
990 .map_err(|_| "Runtime Chat could not read its native event ledger.".to_string())?;
991 for event in events {
992 let key = (binding.native_thread_id.clone(), event.seq);
993 if self.claimed_projections.lock().contains(&key) {
994 break;
995 }
996 match project_native_event(&binding, &event) {
997 ProjectionDecision::Project(projection) => {
998 self.claimed_projections.lock().insert(key);
999 // Return immediately after acquiring the claim. No
1000 // later binding read can fail and accidentally drop a
1001 // previously acquired in-process claim.
1002 return Ok(vec![*projection]);
1003 }
1004 ProjectionDecision::Skip => {
1005 self.advance_projection_cursor_async(
1006 &binding.native_thread_id,
1007 event.seq,
1008 None,
1009 )
1010 .await?;
1011 }
1012 ProjectionDecision::WaitForTurnBinding => break,
1013 }
1014 }
1015 }
1016 Ok(Vec::new())
1017 }
1018
1019 pub(crate) fn mark_projected(
1020 &self,
1021 native_thread_id: &str,
1022 native_seq: u64,
1023 virtual_turn_id: &str,
1024 event: &str,
1025 ) -> Result<(), String> {
1026 self.claimed_projections
1027 .lock()
1028 .remove(&(native_thread_id.to_string(), native_seq));
1029 self.advance_projection_cursor(
1030 native_thread_id,
1031 native_seq,
1032 (event == "turn.completed").then_some(virtual_turn_id),
1033 )
1034 }
1035
1036 pub(crate) fn release_projection(&self, native_thread_id: &str, native_seq: u64) {
1037 self.claimed_projections
1038 .lock()
1039 .remove(&(native_thread_id.to_string(), native_seq));
1040 }
1041
1042 pub(crate) fn release_all_projection_claims(&self) {
1043 self.claimed_projections.lock().clear();
1044 }
1045
1046 #[cfg(test)]
1047 pub(crate) fn install_projection_claim_for_tests(
1048 &self,
1049 native_thread_id: &str,
1050 native_seq: u64,
1051 ) {
1052 self.claimed_projections
1053 .lock()
1054 .insert((native_thread_id.to_string(), native_seq));
1055 }
1056
1057 #[cfg(test)]
1058 pub(crate) fn projection_is_claimed_for_tests(
1059 &self,
1060 native_thread_id: &str,
1061 native_seq: u64,
1062 ) -> bool {
1063 self.claimed_projections
1064 .lock()
1065 .contains(&(native_thread_id.to_string(), native_seq))
1066 }
1067
1068 #[cfg(test)]
1069 async fn native_turn_count_for_binding_for_tests(&self, runtime_binding_id: &str) -> usize {
1070 let native_thread_id = self
1071 .state
1072 .lock()
1073 .bindings
1074 .iter()
1075 .find(|binding| binding.runtime_binding_id == runtime_binding_id)
1076 .map(|binding| binding.native_thread_id.clone())
1077 .expect("test binding exists");
1078 self.manager
1079 .get_thread_detail(&native_thread_id)
1080 .await
1081 .expect("test native thread detail")
1082 .turns
1083 .len()
1084 }
1085
1086 fn validate_route(&self, command: &RuntimeChatPrompt) -> Result<(), String> {
1087 if let Some(owner) = &command.account_model_owner {
1088 let expected = owner_scope_fingerprint(owner, &self.target_ref, &self.session_id);
1089 if self.state.lock().owner_scope_fingerprint.as_deref() != Some(expected.as_str()) {
1090 return Err("The agent model belongs to another account.".to_string());
1091 }
1092 let mut config = (*self.config).clone();
1093 return config
1094 .bind_account_model_owner(owner)
1095 .map_err(|error| error.to_string());
1096 }
1097 let catalog = self.catalog("a2345678901234567890123456789012")?;
1098 let provider = catalog
1099 .get("providers")
1100 .and_then(Value::as_array)
1101 .and_then(|providers| providers.first())
1102 .ok_or_else(|| "The active Runtime Chat route is unavailable.".to_string())?;
1103 let route_matches = provider.get("id").and_then(Value::as_str)
1104 == Some(command.model_provider.as_str())
1105 && provider.get("modelProviderId").and_then(Value::as_str)
1106 == Some(command.model_provider_id.as_str())
1107 && provider
1108 .get("models")
1109 .and_then(Value::as_array)
1110 .is_some_and(|models| {
1111 models.iter().any(|model| {
1112 model.get("id").and_then(Value::as_str) == Some(command.model.as_str())
1113 && (command.images.is_empty()
1114 || model.get("imageInput").and_then(Value::as_str)
1115 == Some("supported"))
1116 })
1117 });
1118 if command.max_output_tokens.is_some()
1119 && !provider
1120 .get("models")
1121 .and_then(Value::as_array)
1122 .is_some_and(|models| {
1123 models.iter().any(|model| {
1124 model.get("id").and_then(Value::as_str) == Some(command.model.as_str())
1125 && model.get("outputTokenLimit").and_then(Value::as_str)
1126 == Some("supported")
1127 })
1128 })
1129 {
1130 return Err(
1131 "The selected Runtime Chat route does not support maxOutputTokens.".to_string(),
1132 );
1133 }
1134 if !route_matches {
1135 return Err(
1136 "The requested Runtime Chat route is not the active ready route.".to_string(),
1137 );
1138 }
1139 Ok(())
1140 }
1141
1142 async fn insert_binding(&self, binding: RelayThreadBinding) -> Result<(), String> {
1143 self.persist_state_update(
1144 "Runtime Chat could not persist its private thread binding.",
1145 move |state| {
1146 if state.owner_scope_fingerprint.is_none() {
1147 return Err("The Runtime Chat account owner is not established.".to_string());
1148 }
1149 if state.bindings.iter().any(|existing| {
1150 existing.runtime_binding_id == binding.runtime_binding_id
1151 || existing.virtual_thread_id == binding.virtual_thread_id
1152 }) {
1153 return Err(
1154 "The Runtime Chat thread binding changed while it was being created."
1155 .to_string(),
1156 );
1157 }
1158 state.bindings.push(binding);
1159 Ok(())
1160 },
1161 )
1162 .await
1163 }
1164
1165 #[allow(clippy::too_many_arguments)]
1166 async fn reserve_turn(
1167 &self,
1168 runtime_binding_id: &str,
1169 virtual_thread_id: &str,
1170 virtual_turn_id: &str,
1171 native_turn_id: &str,
1172 operation_fingerprint: &str,
1173 request_fingerprint: &str,
1174 review_request_fingerprint: Option<&str>,
1175 ) -> Result<TurnReservationDisposition, String> {
1176 validate_native_record_id(native_turn_id, "native turn id")
1177 .map_err(public_validation_error)?;
1178 validate_fingerprint(request_fingerprint).map_err(public_validation_error)?;
1179 if let Some(fingerprint) = review_request_fingerprint {
1180 validate_fingerprint(fingerprint).map_err(public_validation_error)?;
1181 }
1182 let runtime_binding_id = runtime_binding_id.to_string();
1183 let virtual_thread_id = virtual_thread_id.to_string();
1184 let virtual_turn_id = virtual_turn_id.to_string();
1185 let native_turn_id = native_turn_id.to_string();
1186 let operation_fingerprint = operation_fingerprint.to_string();
1187 let request_fingerprint = request_fingerprint.to_string();
1188 let review_request_fingerprint = review_request_fingerprint.map(str::to_string);
1189 self.persist_state_update(
1190 "Runtime Chat could not persist its private turn reservation.",
1191 move |state| {
1192 let binding = state
1193 .bindings
1194 .iter_mut()
1195 .find(|binding| {
1196 binding.runtime_binding_id == runtime_binding_id
1197 && binding.virtual_thread_id == virtual_thread_id
1198 })
1199 .ok_or_else(|| "The Runtime Chat thread binding disappeared.".to_string())?;
1200 if let Some(existing) = binding.turns.get_mut(&virtual_turn_id) {
1201 if existing.operation_fingerprint == operation_fingerprint
1202 && existing.request_fingerprint == request_fingerprint
1203 && existing.native_turn_id == native_turn_id
1204 && existing.review_request_fingerprint.as_deref()
1205 == review_request_fingerprint.as_deref()
1206 {
1207 // A retry after a proven pre-dispatch failure reopens
1208 // the same deterministic reservation. Any accepted or
1209 // replayed native turn is therefore unsettled again
1210 // until its terminal event is durably projected.
1211 let disposition = if existing.terminal_projected && existing.start_rejected
1212 {
1213 TurnReservationDisposition::Reopened
1214 } else if existing.terminal_projected {
1215 TurnReservationDisposition::ExistingTerminal
1216 } else {
1217 TurnReservationDisposition::ExistingUnsettled
1218 };
1219 if matches!(disposition, TurnReservationDisposition::Reopened) {
1220 existing.terminal_projected = false;
1221 existing.start_rejected = false;
1222 }
1223 return Ok(disposition);
1224 }
1225 return Err(
1226 "The Runtime Chat turn binding does not match its replay.".to_string()
1227 );
1228 }
1229 if binding
1230 .turns
1231 .values()
1232 .any(|turn| turn.operation_fingerprint == operation_fingerprint)
1233 {
1234 return Err(
1235 "The Runtime Chat operation key belongs to another turn.".to_string()
1236 );
1237 }
1238 binding.turns.insert(
1239 virtual_turn_id,
1240 RelayTurnBinding {
1241 review_request_fingerprint,
1242 native_turn_id,
1243 operation_fingerprint,
1244 request_fingerprint,
1245 terminal_projected: false,
1246 start_rejected: false,
1247 },
1248 );
1249 Ok(TurnReservationDisposition::New)
1250 },
1251 )
1252 .await
1253 }
1254
1255 async fn finish_turn_reservation(
1256 &self,
1257 runtime_binding_id: &str,
1258 virtual_thread_id: &str,
1259 virtual_turn_id: &str,
1260 ) -> Result<(), String> {
1261 let runtime_binding_id = runtime_binding_id.to_string();
1262 let virtual_thread_id = virtual_thread_id.to_string();
1263 let virtual_turn_id = virtual_turn_id.to_string();
1264 self.persist_state_update(
1265 "Runtime Chat could not settle its rejected turn reservation.",
1266 move |state| {
1267 let turn = state
1268 .bindings
1269 .iter_mut()
1270 .find(|binding| {
1271 binding.runtime_binding_id == runtime_binding_id
1272 && binding.virtual_thread_id == virtual_thread_id
1273 })
1274 .and_then(|binding| binding.turns.get_mut(&virtual_turn_id))
1275 .ok_or_else(|| "The Runtime Chat turn reservation disappeared.".to_string())?;
1276 turn.terminal_projected = true;
1277 turn.start_rejected = true;
1278 Ok(())
1279 },
1280 )
1281 .await
1282 }
1283
1284 fn advance_projection_cursor(
1285 &self,
1286 native_thread_id: &str,
1287 native_seq: u64,
1288 terminal_virtual_turn_id: Option<&str>,
1289 ) -> Result<(), String> {
1290 self.persist_state_update_blocking(
1291 "Runtime Chat could not persist its event cursor.",
1292 |state| {
1293 persist_projection_cursor(
1294 state,
1295 native_thread_id,
1296 native_seq,
1297 terminal_virtual_turn_id,
1298 )
1299 },
1300 )
1301 }
1302
1303 async fn advance_projection_cursor_async(
1304 &self,
1305 native_thread_id: &str,
1306 native_seq: u64,
1307 terminal_virtual_turn_id: Option<&str>,
1308 ) -> Result<(), String> {
1309 let native_thread_id = native_thread_id.to_string();
1310 let terminal_virtual_turn_id = terminal_virtual_turn_id.map(str::to_string);
1311 self.persist_state_update(
1312 "Runtime Chat could not persist its event cursor.",
1313 move |state| {
1314 persist_projection_cursor(
1315 state,
1316 &native_thread_id,
1317 native_seq,
1318 terminal_virtual_turn_id.as_deref(),
1319 )
1320 },
1321 )
1322 .await
1323 }
1324
1325 async fn persist_state_update<T>(
1326 &self,
1327 persistence_error: &'static str,
1328 update: impl FnOnce(&mut RelayState) -> Result<T, String> + Send + 'static,
1329 ) -> Result<T, String>
1330 where
1331 T: Send + 'static,
1332 {
1333 let host = self.clone();
1334 tokio::task::spawn_blocking(move || {
1335 host.persist_state_update_blocking(persistence_error, update)
1336 })
1337 .await
1338 .map_err(|_| persistence_error.to_string())?
1339 }
1340
1341 fn persist_state_update_blocking<T>(
1342 &self,
1343 persistence_error: &'static str,
1344 update: impl FnOnce(&mut RelayState) -> Result<T, String>,
1345 ) -> Result<T, String> {
1346 let mut current = self.state.lock();
1347 let mut candidate = current.clone();
1348 let output = update(&mut candidate)?;
1349 persist_state(&self.state_path, &candidate).map_err(|_| persistence_error.to_string())?;
1350 *current = candidate;
1351 Ok(output)
1352 }
1353
1354 fn ensure_account_bound(&self) -> Result<(), String> {
1355 if self.state.lock().owner_scope_fingerprint.is_none() {
1356 return Err("The Runtime Chat account owner is not established.".to_string());
1357 }
1358 Ok(())
1359 }
1360 }
1361
1362 impl RuntimeChatPrompt {
1363 pub(crate) fn validate_shape(&self) -> Result<(), String> {
1364 if let Some(review) = &self.structured_review {
1365 codewhale_engine::core::engine::review::validate(review)
1366 .map_err(|error| error.to_string())?;
1367 if self.account_model_owner.is_none()
1368 || !self.prompt.is_empty()
1369 || !self.images.is_empty()
1370 || self.profile_constitution.is_some()
1371 || self.system_prompt.is_some()
1372 || !self
1373 .max_output_tokens
1374 .is_some_and(|value| (256..=8192).contains(&value.get()))
1375 {
1376 return Err("A native review requires an account model and bounded output, with no Chat prompt, images or caller instructions.".to_string());
1377 }
1378 }
1379 if let Some(owner) = &self.account_model_owner {
1380 validate_owner_component(owner, "account")?;
1381 if self.model_provider != "codewhale"
1382 || self.model_provider_id != "codewhale"
1383 || !self.model.contains('/')
1384 || self.model.starts_with("codewhale/")
1385 || !self.images.is_empty()
1386 || self.reasoning_effort.is_some()
1387 {
1388 return Err(
1389 "The agent model requires an exact account provider and model.".to_string(),
1390 );
1391 }
1392 }
1393 codewhale_engine::image_attach::prepare_runtime_images(&self.images)
1394 .map_err(|error| error.to_string())?;
1395 if !self.images.is_empty() && self.model.trim().eq_ignore_ascii_case("auto") {
1396 return Err(
1397 "Image inputs require an exact named model; Auto is unavailable for images."
1398 .to_string(),
1399 );
1400 }
1401 if self.command_type != "prompt.request" {
1402 return Err("Codewhale sent an unsupported Runtime Chat command.".to_string());
1403 }
1404 validate_relay_id(&self.run_id, "run id").map_err(public_validation_error)?;
1405 validate_virtual_turn_id(&self.turn_id).map_err(public_validation_error)?;
1406 validate_operation_key(&self.operation_key).map_err(public_validation_error)?;
1407 validate_relay_id(&self.runtime_binding_id, "binding id")
1408 .map_err(public_validation_error)?;
1409 validate_virtual_thread_id(&self.runtime_thread_id).map_err(public_validation_error)?;
1410 validate_model_id(&self.model).map_err(public_validation_error)?;
1411 validate_route_id(&self.model_provider, "provider id").map_err(public_validation_error)?;
1412 validate_route_id(&self.model_provider_id, "model-provider id")
1413 .map_err(public_validation_error)?;
1414 if self.structured_review.is_none()
1415 && (self.prompt.trim().is_empty()
1416 || self.prompt.len() > 128 * 1024
1417 || self.prompt.contains('\0'))
1418 {
1419 return Err("The Runtime Chat prompt is empty or oversized.".to_string());
1420 }
1421 if let Some(snapshot) = &self.profile_constitution {
1422 snapshot.validate().map_err(|error| error.to_string())?;
1423 if self
1424 .account_model_owner
1425 .as_ref()
1426 .is_some_and(|owner| &snapshot.account_id != owner)
1427 {
1428 return Err(
1429 "The profile constitution and agent model must belong to the same account."
1430 .to_string(),
1431 );
1432 }
1433 }
1434 if let Some(system_prompt) = self.system_prompt.as_deref()
1435 && (system_prompt.trim().is_empty()
1436 || system_prompt.len() > 64_000
1437 || system_prompt.contains('\0'))
1438 {
1439 return Err("The Runtime Chat system instructions are invalid.".to_string());
1440 }
1441 if !self.allowed_tools.is_empty() {
1442 return Err("Runtime-backed Chat does not grant work-execution tools.".to_string());
1443 }
1444 if self.mode != "chat" || self.requested_mode != "chat" {
1445 return Err("Runtime relay turns must use Chat mode.".to_string());
1446 }
1447 if let Some(reasoning) = self.reasoning_effort.as_deref()
1448 && codewhale_engine::reasoning_preference::ReasoningEffort::parse_strict(reasoning)
1449 .is_err()
1450 {
1451 return Err("The Runtime Chat reasoning effort is invalid.".to_string());
1452 }
1453 validate_relay_id(&self.workspace.id, "workspace id").map_err(public_validation_error)?;
1454 validate_relay_id(&self.workspace.target_ref, "target reference")
1455 .map_err(public_validation_error)?;
1456 Ok(())
1457 }
1458 }
1459
1460 impl RuntimeChatControlScope {
1461 pub(crate) fn validate_for_turn(&self, virtual_turn_id: &str) -> Result<(), String> {
1462 validate_relay_id(&self.runtime_binding_id, "binding id")
1463 .map_err(public_validation_error)?;
1464 validate_virtual_thread_id(&self.runtime_thread_id).map_err(public_validation_error)?;
1465 validate_virtual_turn_id(virtual_turn_id).map_err(public_validation_error)
1466 }
1467 }
1468
1469 fn validate_existing_binding(
1470 binding: &RelayThreadBinding,
1471 command: &RuntimeChatPrompt,
1472 operation_fingerprint: &str,
1473 system_prompt_fingerprint: Option<&str>,
1474 ) -> Result<(), String> {
1475 if binding.model != command.model
1476 || binding.run_id != command.run_id
1477 || binding.model_provider != command.model_provider
1478 || binding.model_provider_id != command.model_provider_id
1479 {
1480 return Err("The Runtime Chat thread is pinned to a different provider route.".to_string());
1481 }
1482 if command.system_prompt.is_some()
1483 && (binding.first_operation_fingerprint != operation_fingerprint
1484 || binding.system_prompt_fingerprint.as_deref() != system_prompt_fingerprint)
1485 {
1486 return Err(
1487 "Runtime Chat system instructions are allowed only on the first turn.".to_string(),
1488 );
1489 }
1490 Ok(())
1491 }
1492
1493 fn resolve_interrupt_target(
1494 state: &RelayState,
1495 run_id: &str,
1496 scope: &RuntimeChatControlScope,
1497 virtual_turn_id: &str,
1498 ) -> Result<(String, String), String> {
1499 let binding = state
1500 .bindings
1501 .iter()
1502 .find(|binding| {
1503 binding.runtime_binding_id == scope.runtime_binding_id
1504 && binding.virtual_thread_id == scope.runtime_thread_id
1505 })
1506 .ok_or_else(|| "The Runtime Chat interrupt binding is unknown.".to_string())?;
1507 if binding.run_id != run_id {
1508 return Err("The Runtime Chat interrupt binding belongs to another run.".to_string());
1509 }
1510 let turn = binding
1511 .turns
1512 .get(virtual_turn_id)
1513 .ok_or_else(|| "The Runtime Chat interrupt turn is unknown.".to_string())?;
1514 Ok((
1515 binding.native_thread_id.clone(),
1516 turn.native_turn_id.clone(),
1517 ))
1518 }
1519
1520 pub(crate) fn dedicated_chat_system_prompt(account_instructions: Option<&str>) -> String {
1521 match account_instructions
1522 .map(str::trim)
1523 .filter(|value| !value.is_empty())
1524 {
1525 Some(instructions) => format!(
1526 "{ISOLATED_CHAT_SYSTEM_PROMPT}\n\n<account_chat_instructions>\n{instructions}\n</account_chat_instructions>"
1527 ),
1528 None => ISOLATED_CHAT_SYSTEM_PROMPT.to_string(),
1529 }
1530 }
1531
1532 enum ProjectionDecision {
1533 Project(Box<RuntimeChatProjection>),
1534 Skip,
1535 WaitForTurnBinding,
1536 }
1537
1538 fn project_native_event(
1539 binding: &RelayThreadBinding,
1540 event: &RuntimeEventRecord,
1541 ) -> ProjectionDecision {
1542 let Some(native_turn_id) = event.turn_id.as_deref() else {
1543 return ProjectionDecision::Skip;
1544 };
1545 let Some((virtual_turn_id, turn_binding)) = binding
1546 .turns
1547 .iter()
1548 .find(|(_, turn)| turn.native_turn_id == native_turn_id)
1549 else {
1550 return ProjectionDecision::WaitForTurnBinding;
1551 };
1552 let base = || RuntimeChatProjection {
1553 run_id: binding.run_id.clone(),
1554 native_thread_id: binding.native_thread_id.clone(),
1555 native_seq: event.seq,
1556 source_event_id: source_event_id(&binding.native_thread_id, event.seq),
1557 virtual_thread_id: binding.virtual_thread_id.clone(),
1558 virtual_turn_id: virtual_turn_id.clone(),
1559 event: "",
1560 timestamp: event.timestamp.to_rfc3339(),
1561 payload: Value::Null,
1562 };
1563 match event.event.as_str() {
1564 "turn.started" => {
1565 let mut projection = base();
1566 projection.event = "turn.started";
1567 projection.payload = json!({
1568 "turn": {
1569 "model": event.payload.pointer("/turn/effective_model")
1570 .and_then(Value::as_str)
1571 .unwrap_or(binding.model.as_str()),
1572 "mode": "chat",
1573 },
1574 });
1575 ProjectionDecision::Project(Box::new(projection))
1576 }
1577 "item.delta"
1578 if event.payload.get("kind").and_then(Value::as_str) == Some("agent_message") =>
1579 {
1580 let Some(delta) = event.payload.get("delta").and_then(Value::as_str) else {
1581 return ProjectionDecision::Skip;
1582 };
1583 let mut projection = base();
1584 projection.event = "item.delta";
1585 projection.payload = json!({ "kind": "agent_message", "delta": delta });
1586 ProjectionDecision::Project(Box::new(projection))
1587 }
1588 "item.completed" => {
1589 let Some(expected_fingerprint) = turn_binding.review_request_fingerprint.as_deref()
1590 else {
1591 return ProjectionDecision::Skip;
1592 };
1593 let Some(item) = event.payload.get("item") else {
1594 return ProjectionDecision::Skip;
1595 };
1596 let Some(metadata) = item.get("metadata") else {
1597 return ProjectionDecision::Skip;
1598 };
1599 let Some(operation) = metadata.get("review_operation") else {
1600 return ProjectionDecision::Skip;
1601 };
1602 if item.get("kind").and_then(Value::as_str) != Some("tool_call")
1603 || item.get("status").and_then(Value::as_str) != Some("completed")
1604 || metadata.get("tool_name").and_then(Value::as_str) != Some("review")
1605 || metadata.get("is_error").and_then(Value::as_bool) != Some(false)
1606 || !metadata
1607 .get("tool_result_for")
1608 .and_then(Value::as_str)
1609 .is_some_and(|value| !value.is_empty())
1610 || operation.get("version").and_then(Value::as_u64) != Some(1)
1611 || operation.get("source").and_then(Value::as_str) != Some("codewhale.review_core")
1612 || operation.get("request_fingerprint").and_then(Value::as_str)
1613 != Some(expected_fingerprint)
1614 || operation.get("complete").and_then(Value::as_bool) != Some(true)
1615 || operation.get("outcome").and_then(Value::as_str) != Some("completed")
1616 {
1617 return ProjectionDecision::Skip;
1618 }
1619 let Some(detail) = item.get("detail").and_then(Value::as_str).filter(|value| {
1620 value.len() <= codewhale_engine::core::engine::review::MAX_RESULT_BYTES
1621 }) else {
1622 return ProjectionDecision::Skip;
1623 };
1624 let Ok(output) = serde_json::from_str::<Value>(detail) else {
1625 return ProjectionDecision::Skip;
1626 };
1627 let mut projection = base();
1628 projection.event = "review.completed";
1629 projection.payload = json!({ "review": { "operation": operation, "output": output } });
1630 ProjectionDecision::Project(Box::new(projection))
1631 }
1632 "turn.completed" => {
1633 let turn = event
1634 .payload
1635 .get("turn")
1636 .cloned()
1637 .unwrap_or_else(|| json!({}));
1638 let status = turn
1639 .get("status")
1640 .and_then(Value::as_str)
1641 .unwrap_or("failed");
1642 let mut projection = base();
1643 projection.event = "turn.completed";
1644 projection.payload = json!({
1645 "turn": {
1646 "status": status,
1647 "usage": turn.get("usage").cloned().unwrap_or_else(|| json!({})),
1648 "effective_model": turn.get("effective_model").and_then(Value::as_str)
1649 .unwrap_or(binding.model.as_str()),
1650 "effective_provider": turn.get("effective_provider").and_then(Value::as_str)
1651 .unwrap_or(binding.model_provider.as_str()),
1652 "effective_billing_surface": turn.get("effective_billing_surface")
1653 .and_then(Value::as_str).unwrap_or("provider_byok"),
1654 "effective_billing_mode": turn.get("effective_billing_mode")
1655 .and_then(Value::as_str).unwrap_or("local"),
1656 },
1657 });
1658 ProjectionDecision::Project(Box::new(projection))
1659 }
1660 _ => ProjectionDecision::Skip,
1661 }
1662 }
1663
1664 fn validate_owner_component(value: &str, label: &str) -> Result<(), String> {
1665 if value.trim() != value || value.is_empty() || value.len() > 512 || value.contains('\0') {
1666 return Err(format!("The Runtime Chat {label} owner is invalid."));
1667 }
1668 Ok(())
1669 }
1670
1671 fn scoped_private_dir(root: &Path, target_ref: &str, session_id: &str) -> PathBuf {
1672 let mut hasher = Sha256::new();
1673 hasher.update(b"codewhale.runtime-chat-scope.v1\0");
1674 hasher.update(target_ref.as_bytes());
1675 hasher.update(b"\0");
1676 hasher.update(session_id.as_bytes());
1677 root.join(format!("scope-{}", hex_digest(hasher.finalize())))
1678 }
1679
1680 fn owner_scope_fingerprint(account_ref: &str, target_ref: &str, session_id: &str) -> String {
1681 let mut hasher = Sha256::new();
1682 hasher.update(b"codewhale.runtime-chat-owner.v1\0");
1683 hasher.update(account_ref.as_bytes());
1684 hasher.update(b"\0");
1685 hasher.update(target_ref.as_bytes());
1686 hasher.update(b"\0");
1687 hasher.update(session_id.as_bytes());
1688 hex_digest(hasher.finalize())
1689 }
1690
1691 fn bind_owner_scope(state: &mut RelayState, owner: &str) -> Result<(), String> {
1692 validate_fingerprint(owner)
1693 .map_err(|_| "The Runtime Chat account owner is invalid.".to_string())?;
1694 match state.owner_scope_fingerprint.as_deref() {
1695 Some(existing) if existing == owner => Ok(()),
1696 Some(_) => Err("This Runtime Chat session belongs to another account.".to_string()),
1697 None if state.bindings.is_empty() => {
1698 state.owner_scope_fingerprint = Some(owner.to_string());
1699 Ok(())
1700 }
1701 None => Err("The saved Runtime Chat state has no trusted account owner.".to_string()),
1702 }
1703 }
1704
1705 fn source_event_id(native_thread_id: &str, native_seq: u64) -> String {
1706 let mut hasher = Sha256::new();
1707 hasher.update(b"codewhale.runtime-chat-source-event.v1\0");
1708 hasher.update(native_thread_id.as_bytes());
1709 hasher.update(b"\0");
1710 hasher.update(native_seq.to_be_bytes());
1711 format!("native_event_{}", hex_digest(hasher.finalize()))
1712 }
1713
1714 fn reserved_native_turn_id(
1715 native_thread_id: &str,
1716 runtime_binding_id: &str,
1717 virtual_turn_id: &str,
1718 operation_fingerprint: &str,
1719 ) -> String {
1720 let mut hasher = Sha256::new();
1721 hasher.update(b"codewhale.runtime-chat-native-turn.v1\0");
1722 hasher.update(native_thread_id.as_bytes());
1723 hasher.update(b"\0");
1724 hasher.update(runtime_binding_id.as_bytes());
1725 hasher.update(b"\0");
1726 hasher.update(virtual_turn_id.as_bytes());
1727 hasher.update(b"\0");
1728 hasher.update(operation_fingerprint.as_bytes());
1729 format!("turn_{}", hex_digest(hasher.finalize()))
1730 }
1731
1732 fn hex_digest(digest: impl AsRef<[u8]>) -> String {
1733 digest
1734 .as_ref()
1735 .iter()
1736 .map(|byte| format!("{byte:02x}"))
1737 .collect()
1738 }
1739
1740 fn canonical_json_value(value: &Value) -> Value {
1741 match value {
1742 Value::Array(values) => Value::Array(values.iter().map(canonical_json_value).collect()),
1743 Value::Object(values) => {
1744 let mut keys = values.keys().collect::<Vec<_>>();
1745 keys.sort_unstable();
1746 let mut canonical = serde_json::Map::new();
1747 for key in keys {
1748 canonical.insert(key.clone(), canonical_json_value(&values[key]));
1749 }
1750 Value::Object(canonical)
1751 }
1752 _ => value.clone(),
1753 }
1754 }
1755
1756 fn isolated_chat_execution_config(
1757 config: &Config,
1758 private_dir: &Path,
1759 ) -> Result<(Config, PathBuf), String> {
1760 let workspace = private_dir.join("chat-workspace");
1761 let context_dir = private_dir.join("prompt-context");
1762 let skills_dir = context_dir.join("skills-empty");
1763 fs::create_dir_all(&workspace)
1764 .and_then(|()| fs::create_dir_all(&skills_dir))
1765 .map_err(|_| "Runtime Chat could not prepare its isolated Chat context.".to_string())?;
1766 #[cfg(unix)]
1767 {
1768 // A mount that assigns modes itself refuses every `chmod`; the context
1769 // directories are linked only from this session either way.
1770 for path in [&workspace, &context_dir, &skills_dir] {
1771 codewhale_config::private_directory::tighten_mode(path, 0o700).map_err(|_| {
1772 "Runtime Chat could not protect its isolated Chat context.".to_string()
1773 })?;
1774 }
1775 }
1776
1777 let mut execution = config.clone();
1778 execution.runtime_chat_isolated = true;
1779 execution.skills_dir = Some(skills_dir.to_string_lossy().into_owned());
1780 execution.instructions = None;
1781 execution.mcp_config_path = Some(
1782 context_dir
1783 .join("mcp-disabled.json")
1784 .to_string_lossy()
1785 .into_owned(),
1786 );
1787 execution.memory = Some(MemoryConfig {
1788 enabled: Some(false),
1789 backend: Some(MemoryBackend::Off),
1790 });
1791 execution.memory_path = Some(
1792 context_dir
1793 .join("memory-disabled.md")
1794 .to_string_lossy()
1795 .into_owned(),
1796 );
1797 execution.context.project_pack = Some(false);
1798 execution
1799 .skills
1800 .get_or_insert_with(SkillsConfig::default)
1801 .scan_codewhale_only = Some(true);
1802 Ok((execution, workspace))
1803 }
1804
1805 #[derive(Debug)]
1806 struct RelayScopeLock {
1807 _file: File,
1808 }
1809
1810 impl RelayScopeLock {
1811 fn acquire(path: &Path) -> Result<Self> {
1812 if fs::symlink_metadata(path).is_ok_and(|metadata| metadata.file_type().is_symlink()) {
1813 bail!("refusing a symlinked Runtime Chat owner lock");
1814 }
1815 let mut options = fs::OpenOptions::new();
1816 options.read(true).write(true).create(true);
1817 #[cfg(unix)]
1818 {
1819 use std::os::unix::fs::OpenOptionsExt as _;
1820 options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
1821 }
1822 #[cfg(windows)]
1823 {
1824 use std::os::windows::fs::OpenOptionsExt as _;
1825 use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
1826 options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
1827 }
1828 let file = options.open(path).context("open Runtime Chat owner lock")?;
1829 if !file
1830 .metadata()
1831 .context("inspect Runtime Chat owner lock")?
1832 .file_type()
1833 .is_file()
1834 {
1835 bail!("Runtime Chat owner lock is not a regular file");
1836 }
1837 #[cfg(unix)]
1838 {
1839 use std::os::unix::fs::PermissionsExt as _;
1840 file.set_permissions(fs::Permissions::from_mode(0o600))
1841 .context("protect Runtime Chat owner lock")?;
1842 }
1843 // Same-process drop-then-reopen can observe WouldBlock for a brief
1844 // window while the previous fd is still closing (#5735). Retry only
1845 // that contention; a lock that stays held is still ownership.
1846 let deadline = Instant::now() + Duration::from_millis(25);
1847 loop {
1848 match Self::try_lock_exclusive(&file) {
1849 Ok(()) => break,
1850 Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
1851 if Instant::now() >= deadline {
1852 return Err(error).context("acquire Runtime Chat owner lock");
1853 }
1854 std::thread::yield_now();
1855 std::thread::sleep(Duration::from_millis(1));
1856 }
1857 Err(error) => {
1858 return Err(error).context("acquire Runtime Chat owner lock");
1859 }
1860 }
1861 }
1862 Ok(Self { _file: file })
1863 }
1864
1865 fn try_lock_exclusive(file: &File) -> std::io::Result<()> {
1866 #[cfg(unix)]
1867 {
1868 use std::os::fd::AsRawFd as _;
1869 // SAFETY: `file` owns a valid descriptor for the duration of the
1870 // call and remains alive in `Self` for the full lock lifetime.
1871 if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 {
1872 return Err(std::io::Error::last_os_error());
1873 }
1874 Ok(())
1875 }
1876 #[cfg(windows)]
1877 {
1878 use std::os::windows::io::AsRawHandle as _;
1879 use windows_sys::Win32::Storage::FileSystem::LockFile;
1880 // SAFETY: `file` owns a valid handle that remains alive in `Self`.
1881 if unsafe { LockFile(file.as_raw_handle() as _, 0, 0, u32::MAX, u32::MAX) } == 0 {
1882 return Err(std::io::Error::last_os_error());
1883 }
1884 Ok(())
1885 }
1886 #[cfg(not(any(unix, windows)))]
1887 {
1888 let _ = file;
1889 Ok(())
1890 }
1891 }
1892 }
1893
1894 impl Drop for RelayScopeLock {
1895 fn drop(&mut self) {
1896 // close() also releases, but unlocking first lets a same-process
1897 // reopen proceed without racing the previous fd's teardown (#5735).
1898 #[cfg(unix)]
1899 {
1900 use std::os::fd::AsRawFd as _;
1901 // SAFETY: Drop runs only while `_file` still owns this descriptor.
1902 unsafe {
1903 libc::flock(self._file.as_raw_fd(), libc::LOCK_UN);
1904 }
1905 }
1906 #[cfg(windows)]
1907 {
1908 use std::os::windows::io::AsRawHandle as _;
1909 use windows_sys::Win32::Storage::FileSystem::UnlockFile;
1910 // SAFETY: Drop runs only while `_file` still owns this handle.
1911 unsafe {
1912 UnlockFile(self._file.as_raw_handle() as _, 0, 0, u32::MAX, u32::MAX);
1913 }
1914 }
1915 }
1916 }
1917
1918 fn load_state(path: &Path) -> Result<RelayState> {
1919 match fs::read(path) {
1920 Ok(bytes) => serde_json::from_slice(&bytes).context("decode Runtime Chat binding state"),
1921 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(RelayState::default()),
1922 Err(error) => Err(error).context("read Runtime Chat binding state"),
1923 }
1924 }
1925
1926 fn persist_projection_cursor(
1927 state: &mut RelayState,
1928 native_thread_id: &str,
1929 native_seq: u64,
1930 terminal_virtual_turn_id: Option<&str>,
1931 ) -> Result<(), String> {
1932 let binding = state
1933 .bindings
1934 .iter_mut()
1935 .find(|binding| binding.native_thread_id == native_thread_id)
1936 .ok_or_else(|| "The Runtime Chat projection binding is unknown.".to_string())?;
1937 binding.projected_native_seq = binding.projected_native_seq.max(native_seq);
1938 if let Some(virtual_turn_id) = terminal_virtual_turn_id {
1939 let turn = binding.turns.get_mut(virtual_turn_id).ok_or_else(|| {
1940 "The Runtime Chat terminal projection has no turn binding.".to_string()
1941 })?;
1942 turn.terminal_projected = true;
1943 turn.start_rejected = false;
1944 }
1945 Ok(())
1946 }
1947
1948 fn persist_state(path: &Path, state: &RelayState) -> Result<()> {
1949 state.validate()?;
1950 #[cfg(test)]
1951 if take_state_persist_failure(path) {
1952 bail!("injected Runtime Chat state persistence failure");
1953 }
1954 let body = serde_json::to_vec(state).context("encode Runtime Chat binding state")?;
1955 codewhale_util::utils::write_atomic(path, &body).context("persist Runtime Chat binding state")
1956 }
1957
1958 fn validate_relay_id(value: &str, label: &str) -> Result<()> {
1959 if value.is_empty()
1960 || value.len() > MAX_RELAY_ID_BYTES
1961 || value.contains("..")
1962 || value.contains("://")
1963 || !value.bytes().all(|byte| {
1964 byte.is_ascii_alphanumeric()
1965 || matches!(byte, b'.' | b'_' | b':' | b'@' | b'/' | b'+' | b'~' | b'-')
1966 })
1967 {
1968 bail!("invalid Runtime Chat {label}");
1969 }
1970 Ok(())
1971 }
1972
1973 fn validate_operation_key(value: &str) -> Result<()> {
1974 validate_relay_id(value, "operation key")?;
1975 if value.len() > MAX_OPERATION_KEY_BYTES {
1976 bail!("Runtime Chat operation key is too long");
1977 }
1978 Ok(())
1979 }
1980
1981 fn validate_virtual_thread_id(value: &str) -> Result<()> {
1982 if value.len() != 37
1983 || !value.starts_with("local_thread_")
1984 || !value[13..]
1985 .bytes()
1986 .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
1987 {
1988 bail!("invalid Runtime Chat virtual thread id");
1989 }
1990 Ok(())
1991 }
1992
1993 fn validate_virtual_turn_id(value: &str) -> Result<()> {
1994 if value.len() != 35
1995 || !value.starts_with("local_turn_")
1996 || !value[11..]
1997 .bytes()
1998 .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
1999 {
2000 bail!("invalid Runtime Chat virtual turn id");
2001 }
2002 Ok(())
2003 }
2004
2005 fn validate_native_record_id(value: &str, label: &str) -> Result<()> {
2006 if value.len() < 5
2007 || value.len() > 80
2008 || !value
2009 .bytes()
2010 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
2011 {
2012 bail!("invalid {label}");
2013 }
2014 Ok(())
2015 }
2016
2017 fn validate_route_id(value: &str, label: &str) -> Result<()> {
2018 if !crate::runtime_api::runtime_chat_route_id_is_safe(value) {
2019 bail!("invalid Runtime Chat {label}");
2020 }
2021 Ok(())
2022 }
2023
2024 fn validate_model_id(value: &str) -> Result<()> {
2025 if !crate::runtime_api::runtime_chat_model_id_is_safe(value) {
2026 bail!("invalid Runtime Chat model id");
2027 }
2028 Ok(())
2029 }
2030
2031 fn validate_fingerprint(value: &str) -> Result<()> {
2032 if value.len() != 64 || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
2033 bail!("invalid Runtime Chat fingerprint");
2034 }
2035 Ok(())
2036 }
2037
2038 fn fingerprint(value: &str) -> String {
2039 hex_digest(Sha256::digest(value.as_bytes()))
2040 }
2041
2042 fn runtime_chat_request_fingerprint(command: &RuntimeChatPrompt) -> Result<String, String> {
2043 serde_json::to_value(command)
2044 .map(|value| canonical_json_value(&value))
2045 .and_then(|value| serde_json::to_vec(&value))
2046 .map(|bytes| hex_digest(Sha256::digest(bytes)))
2047 .map_err(|_| "Runtime Chat could not fingerprint its validated request.".to_string())
2048 }
2049
2050 fn public_validation_error(_error: anyhow::Error) -> String {
2051 "The Runtime Chat command contains an invalid opaque identity.".to_string()
2052 }
2053
2054 fn sanitized_runtime_error(action: &str, error: &anyhow::Error) -> String {
2055 let text = error.to_string().to_ascii_lowercase();
2056 if text.contains("operation_key") || text.contains("operation key") {
2057 return "The Runtime Chat operation key does not match its original turn.".to_string();
2058 }
2059 format!("The isolated Runtime Chat turn could not {action}.")
2060 }
2061
2062 #[cfg(test)]
2063 mod tests {
2064 use super::*;
2065 use chrono::Utc;
2066 use std::time::Duration;
2067
2068 fn open_host(root: &Path) -> RuntimeChatRelayHost {
2069 RuntimeChatRelayHost::open(
2070 Config::default(),
2071 Arc::new(PluginRegistry::empty(root)),
2072 root.to_path_buf(),
2073 "target_fixture".to_string(),
2074 "session_fixture".to_string(),
2075 )
2076 .expect("open Runtime Chat host")
2077 }
2078
2079 fn binding() -> RelayThreadBinding {
2080 RelayThreadBinding {
2081 run_id: "run_fixture".to_string(),
2082 runtime_binding_id: "binding_fixture".to_string(),
2083 virtual_thread_id: format!("local_thread_{}", "a".repeat(24)),
2084 native_thread_id: "thr_fixture".to_string(),
2085 model: "model-1".to_string(),
2086 model_provider: "custom".to_string(),
2087 model_provider_id: "local-provider".to_string(),
2088 first_operation_fingerprint: fingerprint("operation-1"),
2089 system_prompt_fingerprint: None,
2090 turns: BTreeMap::from([(
2091 format!("local_turn_{}", "b".repeat(24)),
2092 RelayTurnBinding {
2093 review_request_fingerprint: None,
2094 native_turn_id: "turn_native".to_string(),
2095 operation_fingerprint: fingerprint("operation-1"),
2096 request_fingerprint: fingerprint("request-1"),
2097 terminal_projected: false,
2098 start_rejected: false,
2099 },
2100 )]),
2101 projected_native_seq: 0,
2102 }
2103 }
2104
2105 #[test]
2106 fn persisted_binding_state_rejects_duplicate_or_nonopaque_authority() {
2107 let one = binding();
2108 let state = RelayState {
2109 schema_version: STATE_SCHEMA_VERSION,
2110 owner_scope_fingerprint: Some(fingerprint("owner")),
2111 bindings: vec![one.clone()],
2112 };
2113 state.validate().unwrap();
2114 let duplicate = RelayState {
2115 schema_version: STATE_SCHEMA_VERSION,
2116 owner_scope_fingerprint: Some(fingerprint("owner")),
2117 bindings: vec![one.clone(), one],
2118 };
2119 assert!(duplicate.validate().is_err());
2120 }
2121
2122 #[test]
2123 fn projection_rewrites_native_ids_to_virtual_chat_ids_and_keeps_route_receipt() {
2124 let binding = binding();
2125 let event = RuntimeEventRecord {
2126 schema_version: 2,
2127 seq: 9,
2128 timestamp: Utc::now(),
2129 thread_id: binding.native_thread_id.clone(),
2130 turn_id: Some("turn_native".to_string()),
2131 item_id: None,
2132 event: "turn.completed".to_string(),
2133 payload: json!({
2134 "turn": {
2135 "status": "completed",
2136 "usage": { "input_tokens": 2, "output_tokens": 3 },
2137 "effective_model": "model-1",
2138 "effective_provider": "custom",
2139 "effective_billing_surface": "provider_byok",
2140 "effective_billing_mode": "local",
2141 }
2142 }),
2143 };
2144 let ProjectionDecision::Project(projected) = project_native_event(&binding, &event) else {
2145 panic!("terminal event must project");
2146 };
2147 assert_eq!(projected.virtual_thread_id, binding.virtual_thread_id);
2148 assert!(projected.virtual_turn_id.starts_with("local_turn_"));
2149 assert_eq!(projected.event, "turn.completed");
2150 assert_eq!(
2151 projected.source_event_id,
2152 source_event_id(&binding.native_thread_id, event.seq)
2153 );
2154 assert_eq!(projected.source_event_id.len(), 77);
2155 assert_eq!(projected.payload["turn"]["effective_billing_mode"], "local");
2156 assert!(!projected.payload.to_string().contains("thr_fixture"));
2157 }
2158
2159 #[test]
2160 fn chat_command_shape_requires_empty_tools_and_exact_chat_modes() {
2161 let mut prompt = RuntimeChatPrompt {
2162 structured_review: None,
2163 account_model_owner: None,
2164 profile_constitution: None,
2165 images: Vec::new(),
2166 max_output_tokens: None,
2167 command_type: "prompt.request".to_string(),
2168 run_id: "run_fixture".to_string(),
2169 turn_id: format!("local_turn_{}", "b".repeat(24)),
2170 operation_key: "operation-1".to_string(),
2171 runtime_binding_id: "binding_fixture".to_string(),
2172 runtime_thread_id: format!("local_thread_{}", "a".repeat(24)),
2173 prompt: "hello".to_string(),
2174 system_prompt: None,
2175 model: "model-1".to_string(),
2176 model_provider: "custom".to_string(),
2177 model_provider_id: "local-provider".to_string(),
2178 reasoning_effort: Some("high".to_string()),
2179 allowed_tools: Vec::new(),
2180 mode: "chat".to_string(),
2181 requested_mode: "chat".to_string(),
2182 workspace: RuntimeChatWorkspace {
2183 id: "workspace_fixture".to_string(),
2184 target_ref: "target_fixture".to_string(),
2185 },
2186 };
2187 prompt.validate_shape().unwrap();
2188 for reasoning in ["minimal", "ultra"] {
2189 prompt.reasoning_effort = Some(reasoning.into());
2190 prompt.validate_shape().unwrap();
2191 }
2192 prompt.reasoning_effort = Some("invented-effort".into());
2193 assert!(prompt.validate_shape().is_err());
2194 prompt.reasoning_effort = None;
2195 prompt.allowed_tools.push("bash".to_string());
2196 assert!(prompt.validate_shape().is_err());
2197 prompt.allowed_tools.clear();
2198 prompt.requested_mode = "work".to_string();
2199 assert!(prompt.validate_shape().is_err());
2200 }
2201
2202 #[tokio::test]
2203 async fn active_participant_rejects_new_and_exact_replay_without_blocking_or_starting() {
2204 let root = tempfile::tempdir().unwrap();
2205 let config = {
2206 let __cw_config_init_0_0 = Some("ollama".to_string());
2207 let __cw_config_init_0_1 = Some("relay-local:fixture".to_string());
2208 let mut __cw_config_init_0_value: Config = Config::default();
2209 __cw_config_init_0_value.provider = __cw_config_init_0_0;
2210 __cw_config_init_0_value.default_text_model = __cw_config_init_0_1;
2211 __cw_config_init_0_value
2212 };
2213 let host = RuntimeChatRelayHost::open(
2214 config,
2215 Arc::new(PluginRegistry::empty(root.path())),
2216 root.path().to_path_buf(),
2217 "target_fixture".to_string(),
2218 "session_fixture".to_string(),
2219 )
2220 .unwrap();
2221 host.bind_account("account_fixture", "target_fixture")
2222 .unwrap();
2223 host.authorize_run("run_fixture").unwrap();
2224 let prompt = RuntimeChatPrompt {
2225 structured_review: None,
2226 account_model_owner: None,
2227 profile_constitution: None,
2228 images: Vec::new(),
2229 max_output_tokens: None,
2230 command_type: "prompt.request".to_string(),
2231 run_id: "run_fixture".to_string(),
2232 turn_id: format!("local_turn_{}", "e".repeat(24)),
2233 operation_key: "operation-gate-fixture".to_string(),
2234 runtime_binding_id: "binding-gate-fixture".to_string(),
2235 runtime_thread_id: format!("local_thread_{}", "f".repeat(24)),
2236 prompt: "hello".to_string(),
2237 system_prompt: None,
2238 model: "relay-local:fixture".to_string(),
2239 model_provider: "ollama".to_string(),
2240 model_provider_id: "ollama".to_string(),
2241 reasoning_effort: None,
2242 allowed_tools: Vec::new(),
2243 mode: "chat".to_string(),
2244 requested_mode: "chat".to_string(),
2245 workspace: RuntimeChatWorkspace {
2246 id: "workspace_fixture".to_string(),
2247 target_ref: "target_fixture".to_string(),
2248 },
2249 };
2250
2251 let participant =
2252 codewhale_engine::client::acquire_remote_control_inference_participant().await;
2253 let direct_error = host.try_ensure_inference_ownership().unwrap_err();
2254 assert!(
2255 direct_error.contains("active local provider work"),
2256 "{direct_error}"
2257 );
2258 for attempt in 0..2 {
2259 let error = tokio::time::timeout(Duration::from_secs(30), host.apply_prompt(&prompt))
2260 .await
2261 .expect("Runtime Chat admission must not deadlock behind the UI-owned writer")
2262 .unwrap_err();
2263 assert!(error.contains("active local provider work"), "{error}");
2264 assert!(
2265 !host.has_any_unsettled_turns(),
2266 "rejected attempt {attempt} must not leave a phantom reservation"
2267 );
2268 }
2269 assert_eq!(
2270 host.native_turn_count_for_binding_for_tests(&prompt.runtime_binding_id)
2271 .await,
2272 0,
2273 "neither the new command nor its exact replay may reach provider-backed native start"
2274 );
2275 drop(participant);
2276 host.try_ensure_inference_ownership().unwrap();
2277 host.release_inference_ownership_if_settled();
2278 }
2279
2280 #[tokio::test]
2281 async fn recovered_reservation_without_native_turn_settles_after_definitive_start_rejection() {
2282 let root = tempfile::tempdir().unwrap();
2283 let host = open_host(root.path());
2284 host.bind_account("account_fixture", "target_fixture")
2285 .unwrap();
2286 host.authorize_run("run_fixture").unwrap();
2287 let identity = host.config.active_provider_identity().unwrap();
2288 let provider = identity.provider;
2289 let model_provider_id = host
2290 .config
2291 .active_provider_identity()
2292 .unwrap()
2293 .persisted_id()
2294 .unwrap_or_else(|| provider.as_str())
2295 .to_string();
2296 let prompt = RuntimeChatPrompt {
2297 structured_review: None,
2298 account_model_owner: None,
2299 profile_constitution: None,
2300 images: Vec::new(),
2301 max_output_tokens: None,
2302 command_type: "prompt.request".to_string(),
2303 run_id: "run_fixture".to_string(),
2304 turn_id: format!("local_turn_{}", "8".repeat(24)),
2305 operation_key: "operation-crash-window".to_string(),
2306 runtime_binding_id: "binding-crash-window".to_string(),
2307 runtime_thread_id: format!("local_thread_{}", "9".repeat(24)),
2308 prompt: "hello".to_string(),
2309 system_prompt: None,
2310 model: host.config.default_model(),
2311 model_provider: provider.as_str().to_string(),
2312 model_provider_id,
2313 reasoning_effort: None,
2314 allowed_tools: Vec::new(),
2315 mode: "chat".to_string(),
2316 requested_mode: "chat".to_string(),
2317 workspace: RuntimeChatWorkspace {
2318 id: "workspace_fixture".to_string(),
2319 target_ref: "target_fixture".to_string(),
2320 },
2321 };
2322 host.install_prompt_replay_for_tests(&prompt, false)
2323 .await
2324 .unwrap();
2325 assert!(host.has_any_unsettled_turns());
2326 assert_eq!(
2327 host.native_turn_count_for_binding_for_tests(&prompt.runtime_binding_id)
2328 .await,
2329 0
2330 );
2331
2332 let error = host.apply_prompt(&prompt).await.unwrap_err();
2333 assert!(error.contains("could not start"), "{error}");
2334 assert!(
2335 !host.has_any_unsettled_turns(),
2336 "a proven pre-native crash reservation must not hold ownership forever"
2337 );
2338 assert!(!host.inference_ownership_is_held_for_tests());
2339 assert_eq!(
2340 host.native_turn_count_for_binding_for_tests(&prompt.runtime_binding_id)
2341 .await,
2342 0
2343 );
2344 }
2345
2346 #[test]
2347 fn catalog_is_challenge_bound_active_ready_and_secret_free() {
2348 let mut config = {
2349 let __cw_config_init_1_0 = Some("ollama".to_string());
2350 let __cw_config_init_1_1 =
2351 Some(codewhale_config::descriptors::defaults::DEFAULT_OLLAMA_MODEL.to_string());
2352 let mut __cw_config_init_1_value: Config = Config::default();
2353 __cw_config_init_1_value.provider = __cw_config_init_1_0;
2354 __cw_config_init_1_value.default_text_model = __cw_config_init_1_1;
2355 __cw_config_init_1_value
2356 };
2357 config.set_legacy_root(Some("must-not-cross".to_string()), None);
2358 config.set_legacy_root(None, Some("http://127.0.0.1:11434/v1".to_string()));
2359 let challenge = "c".repeat(32);
2360 assert!(crate::runtime_api::runtime_chat_relay_catalog(&config, &challenge).is_err());
2361 config.default_text_model = Some("relay-local:fixture".to_string());
2362 let catalog = crate::runtime_api::runtime_chat_relay_catalog(&config, &challenge).unwrap();
2363 assert_eq!(catalog["protocol"], "codewhale.runtime-chat-relay.v1");
2364 assert_eq!(catalog["challenge"], challenge);
2365 assert_eq!(catalog["runtime"]["service"], "codewhale-runtime-api");
2366 assert_eq!(catalog["runtime"]["apiVersion"], "1.0");
2367 assert_eq!(catalog["runtime"]["capabilities"]["stable_event_ids"], true);
2368 assert_eq!(catalog["providers"].as_array().unwrap().len(), 1);
2369 assert_eq!(
2370 catalog["providers"][0]["models"][0]["imageInput"],
2371 "unknown"
2372 );
2373 assert_eq!(
2374 catalog["runtime"]["capabilities"]["turn_image_inputs"],
2375 true
2376 );
2377 let serialized = catalog.to_string();
2378 assert!(!serialized.contains("must-not-cross"));
2379 assert!(!serialized.contains("127.0.0.1"));
2380 assert!(!serialized.contains("baseUrl"));
2381 assert!(!serialized.contains("endpoint"));
2382 }
2383
2384 #[test]
2385 fn interrupt_resolution_is_bound_to_the_current_run() {
2386 let binding = binding();
2387 let turn_id = binding.turns.keys().next().unwrap().clone();
2388 let scope = RuntimeChatControlScope {
2389 runtime_binding_id: binding.runtime_binding_id.clone(),
2390 runtime_thread_id: binding.virtual_thread_id.clone(),
2391 };
2392 let state = RelayState {
2393 schema_version: STATE_SCHEMA_VERSION,
2394 owner_scope_fingerprint: Some(fingerprint("owner")),
2395 bindings: vec![binding],
2396 };
2397 assert!(resolve_interrupt_target(&state, "run_fixture", &scope, &turn_id).is_ok());
2398 assert!(resolve_interrupt_target(&state, "run_other", &scope, &turn_id).is_err());
2399 }
2400
2401 #[test]
2402 fn scoped_state_is_exclusive_account_bound_and_restart_stable() {
2403 let root = tempfile::tempdir().unwrap();
2404 let first_path = scoped_private_dir(root.path(), "target_fixture", "session_fixture");
2405 let same_path = scoped_private_dir(root.path(), "target_fixture", "session_fixture");
2406 let other_path = scoped_private_dir(root.path(), "target_fixture", "session_other");
2407 assert_eq!(first_path, same_path);
2408 assert_ne!(first_path, other_path);
2409 assert!(!first_path.to_string_lossy().contains("target_fixture"));
2410
2411 fs::create_dir_all(&first_path).unwrap();
2412 let lock_path = first_path.join(SCOPE_LOCK_FILE);
2413 let first_lock = RelayScopeLock::acquire(&lock_path).unwrap();
2414 assert!(RelayScopeLock::acquire(&lock_path).is_err());
2415
2416 let owner = owner_scope_fingerprint("account_one", "target_fixture", "session_fixture");
2417 let mut state = RelayState::default();
2418 bind_owner_scope(&mut state, &owner).unwrap();
2419 bind_owner_scope(&mut state, &owner).unwrap();
2420 assert!(
2421 bind_owner_scope(
2422 &mut state,
2423 &owner_scope_fingerprint("account_other", "target_fixture", "session_fixture")
2424 )
2425 .is_err()
2426 );
2427 state.bindings.push(binding());
2428 let state_path = first_path.join(STATE_FILE);
2429 persist_state(&state_path, &state).unwrap();
2430 assert_eq!(load_state(&state_path).unwrap(), state);
2431 assert!(
2432 fs::read_dir(&first_path)
2433 .unwrap()
2434 .filter_map(Result::ok)
2435 .all(|entry| !entry.file_name().to_string_lossy().ends_with(".tmp"))
2436 );
2437
2438 drop(first_lock);
2439 RelayScopeLock::acquire(&lock_path).unwrap();
2440 }
2441
2442 #[test]
2443 fn isolated_chat_prompt_drops_local_project_memory_and_skill_context() {
2444 let root = tempfile::tempdir().unwrap();
2445 let config = {
2446 let __cw_config_init_2_0 = Some("/Users/alice/CANARY_SKILLS".to_string());
2447 let __cw_config_init_2_1 = Some(vec!["/Users/alice/CANARY_AGENTS.md".to_string()]);
2448 let __cw_config_init_2_2 = Some("/Users/alice/CANARY_MEMORY.md".to_string());
2449 let __cw_config_init_2_3 = Some(MemoryConfig {
2450 enabled: Some(true),
2451 backend: Some(MemoryBackend::Native),
2452 });
2453 let __cw_config_init_2_4 = ContextConfig {
2454 project_pack: Some(true),
2455 };
2456 let mut __cw_config_init_2_value: Config = Config::default();
2457 __cw_config_init_2_value.skills_dir = __cw_config_init_2_0;
2458 __cw_config_init_2_value.instructions = __cw_config_init_2_1;
2459 __cw_config_init_2_value.memory_path = __cw_config_init_2_2;
2460 __cw_config_init_2_value.memory = __cw_config_init_2_3;
2461 __cw_config_init_2_value.context = __cw_config_init_2_4;
2462 __cw_config_init_2_value
2463 };
2464
2465 let (execution, workspace) = isolated_chat_execution_config(&config, root.path()).unwrap();
2466 assert!(workspace.starts_with(root.path()));
2467 assert_ne!(workspace, PathBuf::from("/Users/alice"));
2468 assert!(!execution.memory_enabled());
2469 assert!(execution.instructions_paths().is_empty());
2470 assert!(!execution.project_context_pack_enabled());
2471 assert!(execution.skills_dir().starts_with(root.path()));
2472 assert!(execution.memory_path().starts_with(root.path()));
2473 assert!(execution.mcp_config_path().starts_with(root.path()));
2474 assert!(execution.skills_config().scan_codewhale_only());
2475
2476 let prompt = dedicated_chat_system_prompt(None);
2477 assert_eq!(prompt, ISOLATED_CHAT_SYSTEM_PROMPT);
2478 for canary in [
2479 "CANARY_SKILLS",
2480 "CANARY_AGENTS",
2481 "CANARY_MEMORY",
2482 "/Users/alice",
2483 ] {
2484 assert!(!prompt.contains(canary));
2485 }
2486 let account_prompt = dedicated_chat_system_prompt(Some("Reply in short paragraphs."));
2487 assert!(account_prompt.starts_with(ISOLATED_CHAT_SYSTEM_PROMPT));
2488 assert!(account_prompt.contains("<account_chat_instructions>"));
2489 }
2490
2491 #[test]
2492 fn unsafe_model_ids_are_rejected_and_never_cross_the_catalog() {
2493 for model in [
2494 "/Users/alice/private-model",
2495 "~/.ssh/provider-model",
2496 "sk-live-secret",
2497 "../secrets/model",
2498 "redacted-local-path",
2499 "alice:hunter2@internal.example:443/model",
2500 "internal.example:443/model",
2501 "internal:443/model",
2502 ] {
2503 assert!(validate_model_id(model).is_err(), "accepted {model:?}");
2504 let config = {
2505 let __cw_config_init_3_0 = Some("ollama".to_string());
2506 let __cw_config_init_3_1 = Some(model.to_string());
2507 let mut __cw_config_init_3_value: Config = Config::default();
2508 __cw_config_init_3_value.provider = __cw_config_init_3_0;
2509 __cw_config_init_3_value.default_text_model = __cw_config_init_3_1;
2510 __cw_config_init_3_value
2511 };
2512 if let Ok(catalog) =
2513 crate::runtime_api::runtime_chat_relay_catalog(&config, &"c".repeat(32))
2514 {
2515 let ids = catalog["providers"][0]["models"]
2516 .as_array()
2517 .unwrap()
2518 .iter()
2519 .filter_map(|entry| entry["id"].as_str())
2520 .collect::<Vec<_>>();
2521 assert!(!ids.contains(&model), "catalog leaked {model:?}");
2522 }
2523 }
2524 validate_model_id("anthropic/claude-sonnet-5").unwrap();
2525
2526 for provider_id in ["ghp_secret-provider", "hf_secret-provider", "glpat-secret"] {
2527 assert!(!crate::runtime_api::runtime_chat_route_id_is_safe(
2528 provider_id
2529 ));
2530 let config = {
2531 let __cw_config_init_4_0 = Some(provider_id.to_string());
2532 let __cw_config_init_4_1 = Some(codewhale_runtime::config::ProvidersConfig {
2533 custom: std::collections::HashMap::from([(
2534 provider_id.to_string(),
2535 codewhale_runtime::config::ProviderConfig {
2536 kind: Some("openai-compatible".to_string()),
2537 api_key: Some("fixture-key".to_string()),
2538 base_url: Some("https://example.test/v1".to_string()),
2539 model: Some("safe-model".to_string()),
2540 ..Default::default()
2541 },
2542 )]),
2543 ..Default::default()
2544 });
2545 let mut __cw_config_init_4_value: Config = Config::default();
2546 __cw_config_init_4_value.provider = __cw_config_init_4_0;
2547 __cw_config_init_4_value.providers = __cw_config_init_4_1;
2548 __cw_config_init_4_value
2549 };
2550 let error = crate::runtime_api::runtime_chat_relay_catalog(&config, &"c".repeat(32))
2551 .unwrap_err();
2552 assert!(!error.contains(provider_id));
2553 }
2554 }
2555
2556 #[test]
2557 fn native_source_event_id_is_stable_across_transport_replay() {
2558 let first = source_event_id("thr_fixture", 41);
2559 assert_eq!(first, source_event_id("thr_fixture", 41));
2560 assert_ne!(first, source_event_id("thr_fixture", 42));
2561 assert_ne!(first, source_event_id("thr_other", 41));
2562 assert!(first.starts_with("native_event_"));
2563 assert!(
2564 first
2565 .bytes()
2566 .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
2567 );
2568 }
2569
2570 #[tokio::test]
2571 async fn failed_state_writes_never_become_in_memory_authority_and_exact_retry_reopens() {
2572 let root = tempfile::tempdir().unwrap();
2573 let host = open_host(root.path());
2574
2575 inject_state_persist_failures(&host.state_path, 1);
2576 assert!(
2577 host.bind_account("account_fixture", "target_fixture")
2578 .is_err()
2579 );
2580 assert!(host.state.lock().owner_scope_fingerprint.is_none());
2581 host.bind_account("account_fixture", "target_fixture")
2582 .unwrap();
2583
2584 let mut relay_binding = binding();
2585 relay_binding.turns.clear();
2586 inject_state_persist_failures(&host.state_path, 1);
2587 assert!(host.insert_binding(relay_binding.clone()).await.is_err());
2588 assert!(host.state.lock().bindings.is_empty());
2589 host.insert_binding(relay_binding.clone()).await.unwrap();
2590
2591 let virtual_turn_id = format!("local_turn_{}", "c".repeat(24));
2592 let operation_fingerprint = fingerprint("operation-state-fault");
2593 let request_fingerprint = fingerprint("request-state-fault");
2594 let native_turn_id = reserved_native_turn_id(
2595 &relay_binding.native_thread_id,
2596 &relay_binding.runtime_binding_id,
2597 &virtual_turn_id,
2598 &operation_fingerprint,
2599 );
2600 inject_state_persist_failures(&host.state_path, 1);
2601 assert!(
2602 host.reserve_turn(
2603 &relay_binding.runtime_binding_id,
2604 &relay_binding.virtual_thread_id,
2605 &virtual_turn_id,
2606 &native_turn_id,
2607 &operation_fingerprint,
2608 &request_fingerprint,
2609 None,
2610 )
2611 .await
2612 .is_err()
2613 );
2614 assert!(
2615 !host.state.lock().bindings[0]
2616 .turns
2617 .contains_key(&virtual_turn_id)
2618 );
2619 host.reserve_turn(
2620 &relay_binding.runtime_binding_id,
2621 &relay_binding.virtual_thread_id,
2622 &virtual_turn_id,
2623 &native_turn_id,
2624 &operation_fingerprint,
2625 &request_fingerprint,
2626 None,
2627 )
2628 .await
2629 .unwrap();
2630
2631 inject_state_persist_failures(&host.state_path, 1);
2632 assert!(
2633 host.advance_projection_cursor_async(&relay_binding.native_thread_id, 7, None)
2634 .await
2635 .is_err()
2636 );
2637 assert_eq!(host.state.lock().bindings[0].projected_native_seq, 0);
2638 host.advance_projection_cursor_async(&relay_binding.native_thread_id, 7, None)
2639 .await
2640 .unwrap();
2641
2642 drop(host);
2643 let reopened = open_host(root.path());
2644 let state = reopened.state.lock();
2645 assert!(state.owner_scope_fingerprint.is_some());
2646 assert_eq!(state.bindings.len(), 1);
2647 assert_eq!(state.bindings[0].projected_native_seq, 7);
2648 assert_eq!(
2649 state.bindings[0].turns[&virtual_turn_id].native_turn_id,
2650 native_turn_id
2651 );
2652 }
2653
2654 #[tokio::test]
2655 async fn conflicting_replay_never_settles_a_live_turn_reservation() {
2656 let root = tempfile::tempdir().unwrap();
2657 let host = open_host(root.path());
2658 host.bind_account("account_fixture", "target_fixture")
2659 .unwrap();
2660 let mut relay_binding = binding();
2661 relay_binding.turns.clear();
2662 host.insert_binding(relay_binding.clone()).await.unwrap();
2663
2664 let virtual_turn_id = format!("local_turn_{}", "d".repeat(24));
2665 let operation_fingerprint = fingerprint("same-operation");
2666 let original_request = fingerprint("original-request");
2667 let changed_request = fingerprint("changed-request");
2668 let native_turn_id = reserved_native_turn_id(
2669 &relay_binding.native_thread_id,
2670 &relay_binding.runtime_binding_id,
2671 &virtual_turn_id,
2672 &operation_fingerprint,
2673 );
2674 assert_eq!(
2675 host.reserve_turn(
2676 &relay_binding.runtime_binding_id,
2677 &relay_binding.virtual_thread_id,
2678 &virtual_turn_id,
2679 &native_turn_id,
2680 &operation_fingerprint,
2681 &original_request,
2682 None,
2683 )
2684 .await
2685 .unwrap(),
2686 TurnReservationDisposition::New
2687 );
2688 assert!(
2689 host.reserve_turn(
2690 &relay_binding.runtime_binding_id,
2691 &relay_binding.virtual_thread_id,
2692 &virtual_turn_id,
2693 &native_turn_id,
2694 &operation_fingerprint,
2695 &changed_request,
2696 None,
2697 )
2698 .await
2699 .is_err()
2700 );
2701 assert!(host.has_any_unsettled_turns());
2702 assert!(!host.state.lock().bindings[0].turns[&virtual_turn_id].terminal_projected);
2703 }
2704
2705 #[tokio::test]
2706 async fn rejected_start_retry_reopens_the_same_deterministic_reservation() {
2707 let root = tempfile::tempdir().unwrap();
2708 let host = open_host(root.path());
2709 host.bind_account("account_fixture", "target_fixture")
2710 .unwrap();
2711 let mut relay_binding = binding();
2712 relay_binding.turns.clear();
2713 host.insert_binding(relay_binding.clone()).await.unwrap();
2714
2715 let virtual_turn_id = format!("local_turn_{}", "e".repeat(24));
2716 let operation_fingerprint = fingerprint("retry-operation");
2717 let request_fingerprint = fingerprint("retry-request");
2718 let native_turn_id = reserved_native_turn_id(
2719 &relay_binding.native_thread_id,
2720 &relay_binding.runtime_binding_id,
2721 &virtual_turn_id,
2722 &operation_fingerprint,
2723 );
2724 assert_eq!(
2725 host.reserve_turn(
2726 &relay_binding.runtime_binding_id,
2727 &relay_binding.virtual_thread_id,
2728 &virtual_turn_id,
2729 &native_turn_id,
2730 &operation_fingerprint,
2731 &request_fingerprint,
2732 None,
2733 )
2734 .await
2735 .unwrap(),
2736 TurnReservationDisposition::New
2737 );
2738 host.finish_turn_reservation(
2739 &relay_binding.runtime_binding_id,
2740 &relay_binding.virtual_thread_id,
2741 &virtual_turn_id,
2742 )
2743 .await
2744 .unwrap();
2745 assert!(!host.has_any_unsettled_turns());
2746 assert_eq!(
2747 host.reserve_turn(
2748 &relay_binding.runtime_binding_id,
2749 &relay_binding.virtual_thread_id,
2750 &virtual_turn_id,
2751 &native_turn_id,
2752 &operation_fingerprint,
2753 &request_fingerprint,
2754 None,
2755 )
2756 .await
2757 .unwrap(),
2758 TurnReservationDisposition::Reopened
2759 );
2760 assert!(host.has_any_unsettled_turns());
2761 }
2762
2763 #[tokio::test]
2764 async fn exact_replay_of_a_projected_terminal_turn_stays_settled() {
2765 let root = tempfile::tempdir().unwrap();
2766 let host = open_host(root.path());
2767 host.bind_account("account_fixture", "target_fixture")
2768 .unwrap();
2769 let mut relay_binding = binding();
2770 relay_binding.turns.clear();
2771 host.insert_binding(relay_binding.clone()).await.unwrap();
2772
2773 let virtual_turn_id = format!("local_turn_{}", "f".repeat(24));
2774 let operation_fingerprint = fingerprint("terminal-replay-operation");
2775 let request_fingerprint = fingerprint("terminal-replay-request");
2776 let native_turn_id = reserved_native_turn_id(
2777 &relay_binding.native_thread_id,
2778 &relay_binding.runtime_binding_id,
2779 &virtual_turn_id,
2780 &operation_fingerprint,
2781 );
2782 assert_eq!(
2783 host.reserve_turn(
2784 &relay_binding.runtime_binding_id,
2785 &relay_binding.virtual_thread_id,
2786 &virtual_turn_id,
2787 &native_turn_id,
2788 &operation_fingerprint,
2789 &request_fingerprint,
2790 None,
2791 )
2792 .await
2793 .unwrap(),
2794 TurnReservationDisposition::New
2795 );
2796 host.advance_projection_cursor(&relay_binding.native_thread_id, 11, Some(&virtual_turn_id))
2797 .unwrap();
2798 assert!(!host.has_any_unsettled_turns());
2799
2800 assert_eq!(
2801 host.reserve_turn(
2802 &relay_binding.runtime_binding_id,
2803 &relay_binding.virtual_thread_id,
2804 &virtual_turn_id,
2805 &native_turn_id,
2806 &operation_fingerprint,
2807 &request_fingerprint,
2808 None,
2809 )
2810 .await
2811 .unwrap(),
2812 TurnReservationDisposition::ExistingTerminal
2813 );
2814 assert!(
2815 !host.has_any_unsettled_turns(),
2816 "an idempotent replay of already-projected output cannot reopen provider work"
2817 );
2818 }
2819
2820 #[tokio::test]
2821 async fn restart_refuses_a_new_run_until_the_durable_old_turn_is_projected() {
2822 let root = tempfile::tempdir().unwrap();
2823 {
2824 let host = open_host(root.path());
2825 host.bind_account("account_fixture", "target_fixture")
2826 .unwrap();
2827 host.insert_binding(binding()).await.unwrap();
2828 host.authorize_run("run_fixture").unwrap();
2829 assert!(host.has_unsettled_authorized_turns());
2830 }
2831
2832 let reopened = open_host(root.path());
2833 reopened
2834 .bind_account("account_fixture", "target_fixture")
2835 .unwrap();
2836 assert!(reopened.authorize_run("run_other").is_err());
2837 reopened.authorize_run("run_fixture").unwrap();
2838 let relay_binding = reopened.state.lock().bindings[0].clone();
2839 let virtual_turn_id = relay_binding.turns.keys().next().unwrap().clone();
2840 reopened
2841 .mark_projected(
2842 &relay_binding.native_thread_id,
2843 9,
2844 &virtual_turn_id,
2845 "turn.completed",
2846 )
2847 .unwrap();
2848 assert!(!reopened.has_unsettled_authorized_turns());
2849 reopened.authorize_run("run_other").unwrap();
2850 }
2851 #[test]
2852 fn runtime_image_relay_hash_preserves_text_and_binds_order() {
2853 let legacy = json!({"type":"prompt.request","runId":"run_fixture","turnId":format!("local_turn_{}", "b".repeat(24)),"operationKey":"operation-1","runtimeBindingId":"binding_fixture","runtimeThreadId":format!("local_thread_{}", "a".repeat(24)),"prompt":"look","model":"deepseek-v4-flash-vision-exp","modelProvider":"deepseek","modelProviderId":"deepseek","allowedTools":[],"mode":"chat","requestedMode":"chat","workspace":{"id":"workspace_fixture","targetRef":"target_fixture"}});
2854 let mut command: RuntimeChatPrompt = serde_json::from_value(legacy.clone()).unwrap();
2855 command.validate_shape().unwrap();
2856 let expected = hex_digest(Sha256::digest(
2857 serde_json::to_vec(&canonical_json_value(&legacy)).unwrap(),
2858 ));
2859 assert_eq!(
2860 runtime_chat_request_fingerprint(&command).unwrap(),
2861 expected
2862 );
2863 let mut with_empty = legacy;
2864 with_empty["images"] = json!([]);
2865 let empty: RuntimeChatPrompt = serde_json::from_value(with_empty).unwrap();
2866 assert_eq!(runtime_chat_request_fingerprint(&empty).unwrap(), expected);
2867 command.images = vec![
2868 codewhale_engine::image_attach::test_support::runtime_image_fixture(1),
2869 codewhale_engine::image_attach::test_support::runtime_image_fixture(2),
2870 ];
2871 command.validate_shape().unwrap();
2872 let first = runtime_chat_request_fingerprint(&command).unwrap();
2873 command.images.reverse();
2874 assert_ne!(runtime_chat_request_fingerprint(&command).unwrap(), first);
2875 command.model = "auto".into();
2876 assert!(command.validate_shape().is_err());
2877 }
2878 }
2879
2879 lines RUST