1use std::collections::BTreeMap;
8use std::fmt::Write as _;
9use std::fs;
10use std::path::{Path, PathBuf};
11use std::process::{Command, ExitStatus, Stdio};
12use std::sync::{Arc, Mutex, OnceLock};
13use std::time::{Duration, Instant};
14
15use serde::{Deserialize, Serialize};
16use sha2::{Digest, Sha256};
17
18use super::super::invocation::{
19 CAPABILITY_OBSERVATION_SCHEMA_VERSION, CapabilityAdapter, CapabilityFailureMode,
20 CapabilityInput, CapabilityInvocation, CapabilityObservationV1, CapabilityResult, evidence_ref,
21};
22use super::KillSwitch;
23use crate::core::ocla::{OclaError, OclaResult};
24use crate::core::{pathjail, shell_allowlist};
25
26const CAPABILITY_ID: &str = "rtk-shell-output";
27const CAPABILITY_VERSION: &str = "1.0.0";
28const DEFAULT_MAX_OUTPUT_TOKENS: u64 = 16_384;
29const DEFAULT_PROCESS_CAPTURE_BYTES: usize = 2 * 1024 * 1024;
30const VERSION_PROBE_TIMEOUT_MS: u64 = 1_000;
31const TIMEOUT_MARKER: &str = "ERROR: command timed out after ";
32
33const MANIFEST_JSON: &str = include_str!(concat!(
34 env!("CARGO_MANIFEST_DIR"),
35 "/assets/ocla/capability-manifests/rtk/rtk-shell-v1.json"
36));
37
38#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
40pub struct RtkConfig {
41 pub executable: PathBuf,
43 pub args: Vec<String>,
45 pub timeout_ms: u64,
47 #[cfg(test)]
49 #[serde(skip)]
50 pub(crate) test_version_probe_timeout_ms: Option<u64>,
51 pub working_dir: Option<PathBuf>,
53 pub pinned_version: Option<String>,
55 pub pinned_sha256: Option<String>,
57 pub max_output_tokens: u64,
59 pub max_capture_bytes: usize,
61 pub sandbox_root: Option<PathBuf>,
63}
64
65impl Default for RtkConfig {
66 fn default() -> Self {
67 Self {
68 executable: PathBuf::from("rtk"),
69 args: Vec::new(),
70 timeout_ms: 5_000,
71 #[cfg(test)]
72 test_version_probe_timeout_ms: None,
73 working_dir: None,
74 pinned_version: None,
75 pinned_sha256: None,
76 max_output_tokens: DEFAULT_MAX_OUTPUT_TOKENS,
77 max_capture_bytes: DEFAULT_PROCESS_CAPTURE_BYTES,
78 sandbox_root: None,
79 }
80 }
81}
82
83impl RtkConfig {
84 #[must_use]
86 pub fn new(executable: impl Into<PathBuf>) -> Self {
87 Self {
88 executable: executable.into(),
89 ..Self::default()
90 }
91 }
92
93 #[must_use]
95 pub fn with_args(mut self, args: impl IntoIterator<Item = impl Into<String>>) -> Self {
96 self.args = args.into_iter().map(Into::into).collect();
97 self
98 }
99
100 #[must_use]
102 pub const fn with_timeout_ms(mut self, timeout_ms: u64) -> Self {
103 self.timeout_ms = timeout_ms;
104 self
105 }
106
107 #[cfg(all(test, unix))]
109 #[must_use]
110 pub(crate) fn with_test_version_probe_timeout_ms(mut self, timeout_ms: u64) -> Self {
111 assert!(timeout_ms > 0, "test version-probe timeout must be bounded");
112 self.test_version_probe_timeout_ms = Some(timeout_ms);
113 self
114 }
115
116 #[must_use]
118 pub fn with_working_dir(mut self, working_dir: impl AsRef<Path>) -> Self {
119 self.working_dir = Some(working_dir.as_ref().to_path_buf());
120 self
121 }
122
123 #[must_use]
125 pub fn with_pins(mut self, version: impl Into<String>, sha256: impl Into<String>) -> Self {
126 self.pinned_version = Some(version.into());
127 self.pinned_sha256 = Some(sha256.into());
128 self
129 }
130
131 #[must_use]
133 pub fn with_version(mut self, version: impl Into<String>) -> Self {
134 self.pinned_version = Some(version.into());
135 self
136 }
137
138 #[must_use]
140 pub fn with_sha256(mut self, sha256: impl Into<String>) -> Self {
141 self.pinned_sha256 = Some(sha256.into());
142 self
143 }
144
145 #[must_use]
147 pub const fn with_max_output_tokens(mut self, max_output_tokens: u64) -> Self {
148 self.max_output_tokens = max_output_tokens;
149 self
150 }
151
152 #[must_use]
154 pub const fn with_max_capture_bytes(mut self, max_capture_bytes: usize) -> Self {
155 self.max_capture_bytes = max_capture_bytes;
156 self
157 }
158
159 #[must_use]
161 pub fn with_sandbox_root(mut self, sandbox_root: impl AsRef<Path>) -> Self {
162 self.sandbox_root = Some(sandbox_root.as_ref().to_path_buf());
163 self
164 }
165}
166
167#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
169pub struct CapabilityFailure {
170 pub failure_mode: CapabilityFailureMode,
171 pub reason: String,
172 pub fallback_available: bool,
173 pub evidence_ref: Option<String>,
174}
175
176impl CapabilityFailure {
177 fn new(failure_mode: CapabilityFailureMode, reason: impl Into<String>) -> Self {
178 let reason = reason.into();
179 let evidence_ref = Some(evidence_ref(&reason));
180 Self {
181 failure_mode,
182 reason,
183 fallback_available: true,
184 evidence_ref,
185 }
186 }
187
188 fn kill_switched() -> Self {
189 Self::new(
190 CapabilityFailureMode::FallbackToNative,
191 "RTK capability is disabled by its kill switch",
192 )
193 }
194
195 #[allow(non_upper_case_globals)]
197 pub const KillSwitched: Self = Self {
198 failure_mode: CapabilityFailureMode::FallbackToNative,
199 reason: String::new(),
200 fallback_available: true,
201 evidence_ref: None,
202 };
203}
204
205#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
207pub struct RtkHealthReport {
208 pub executable: PathBuf,
209 pub resolved_executable: Option<PathBuf>,
210 pub available: bool,
211 pub version: Option<String>,
212 pub sha256: Option<String>,
213 pub reason: Option<String>,
214}
215
216struct ProcessOutput {
218 stdout: String,
219 stderr: String,
220 status: ExitStatus,
221 elapsed_ms: u64,
222}
223
224pub struct RtkShellAdapter {
226 config: RtkConfig,
227 kill_switch: Arc<KillSwitch>,
228 last_failure: Mutex<Option<CapabilityFailure>>,
229}
230
231impl RtkShellAdapter {
232 #[must_use]
234 pub fn new(config: RtkConfig) -> Self {
235 Self::with_kill_switch(config, Arc::new(KillSwitch::new(CAPABILITY_ID)))
236 }
237
238 #[must_use]
240 pub fn with_kill_switch(config: RtkConfig, kill_switch: Arc<KillSwitch>) -> Self {
241 Self {
242 config,
243 kill_switch,
244 last_failure: Mutex::new(None),
245 }
246 }
247
248 #[must_use]
250 pub const fn config(&self) -> &RtkConfig {
251 &self.config
252 }
253
254 #[must_use]
256 pub fn kill_switch(&self) -> &Arc<KillSwitch> {
257 &self.kill_switch
258 }
259
260 #[must_use]
262 pub fn last_failure(&self) -> Option<CapabilityFailure> {
263 self.last_failure
264 .lock()
265 .ok()
266 .and_then(|failure| failure.clone())
267 }
268
269 fn remember_failure(&self, failure: &CapabilityFailure) {
270 if let Ok(mut last_failure) = self.last_failure.lock() {
271 *last_failure = Some(failure.clone());
272 }
273 }
274
275 #[must_use]
277 pub fn health_check_detailed(&self) -> RtkHealthReport {
278 let executable = self.config.executable.clone();
279 if self.kill_switch.is_active() {
280 return RtkHealthReport {
281 executable,
282 resolved_executable: None,
283 available: false,
284 version: None,
285 sha256: None,
286 reason: self
287 .kill_switch
288 .reason()
289 .or_else(|| Some("capability disabled by kill switch".to_string())),
290 };
291 }
292
293 let Some(pinned_version) = self.config.pinned_version.as_deref() else {
294 return unavailable_health(executable, "an exact RTK version pin is required");
295 };
296 let Some(pinned_sha256) = self.config.pinned_sha256.as_deref() else {
297 return unavailable_health(executable, "an exact RTK SHA-256 pin is required");
298 };
299 let resolved = match resolve_executable(&self.config.executable) {
300 Ok(path) => path,
301 Err(reason) => return unavailable_health(executable, &reason),
302 };
303 #[cfg(test)]
304 let version_probe_timeout_ms = self
305 .config
306 .test_version_probe_timeout_ms
307 .unwrap_or_else(|| bounded_probe_timeout(self.config.timeout_ms));
308 #[cfg(not(test))]
309 let version_probe_timeout_ms = bounded_probe_timeout(self.config.timeout_ms);
310 let version_probe = match run_bounded_process(
311 &resolved,
312 &["--version".to_string()],
313 self.config
314 .working_dir
315 .as_deref()
316 .unwrap_or_else(|| Path::new(".")),
317 version_probe_timeout_ms,
318 self.config.max_capture_bytes.min(16 * 1024),
319 ) {
320 Ok(output) => output,
321 Err(reason) => return unavailable_health_with_path(executable, resolved, reason),
322 };
323 if !version_probe.status.success() {
324 return unavailable_health_with_path(
325 executable,
326 resolved,
327 format!("version probe exited with {}", version_probe.status),
328 );
329 }
330 let version_text = format!("{}{}", version_probe.stdout, version_probe.stderr);
331 if !version_text.contains(pinned_version) {
332 return unavailable_health_with_path(
333 executable,
334 resolved,
335 format!("version probe did not contain pinned version {pinned_version:?}"),
336 );
337 }
338 let actual_sha256 = match sha256_file(&resolved) {
339 Ok(hash) => hash,
340 Err(reason) => return unavailable_health_with_path(executable, resolved, reason),
341 };
342 if !hashes_equal(&actual_sha256, pinned_sha256) {
343 return unavailable_health_with_path(
344 executable,
345 resolved,
346 "executable SHA-256 does not match the configured pin".to_string(),
347 );
348 }
349
350 RtkHealthReport {
351 executable,
352 resolved_executable: Some(resolved),
353 available: true,
354 version: Some(version_text.trim().to_string()),
355 sha256: Some(actual_sha256),
356 reason: None,
357 }
358 }
359
360 #[must_use]
362 pub fn health_check(&self) -> RtkHealthReport {
363 self.health_check_detailed()
364 }
365
366 pub fn observe_rtk(
369 &self,
370 invocation: &CapabilityInvocation,
371 ) -> Result<CapabilityResult, CapabilityFailure> {
372 if self.kill_switch.is_active() {
373 let failure = CapabilityFailure::kill_switched();
374 self.remember_failure(&failure);
375 return Err(failure);
376 }
377
378 let prepared = match self.prepare_invocation(invocation) {
379 Ok(prepared) => prepared,
380 Err(failure) => {
381 self.remember_failure(&failure);
382 return Err(failure);
383 }
384 };
385 let health = self.health_check_detailed();
386 if !health.available {
387 let failure = CapabilityFailure::new(
388 health
389 .reason
390 .as_deref()
391 .map_or(CapabilityFailureMode::Unavailable, failure_mode_for_reason),
392 health
393 .reason
394 .unwrap_or_else(|| "RTK health check failed".to_string()),
395 );
396 self.remember_failure(&failure);
397 return Err(failure);
398 }
399 let resolved = health
400 .resolved_executable
401 .expect("available health has a path");
402 let started = Instant::now();
403 let rewrite_args = {
404 let mut args = self.config.args.clone();
405 args.push("rewrite".to_string());
406 args.push(prepared.command.clone());
407 args
408 };
409 let rewrite_timeout = effective_timeout(invocation.timeout_ms, self.config.timeout_ms);
410 let rewrite = match run_bounded_process(
411 &resolved,
412 &rewrite_args,
413 &prepared.cwd,
414 rewrite_timeout,
415 self.config.max_capture_bytes,
416 ) {
417 Ok(output) => output,
418 Err(failure) => {
419 let failure = CapabilityFailure::new(failure_mode_for_reason(&failure), failure);
420 self.remember_failure(&failure);
421 return Err(failure);
422 }
423 };
424 if !rewrite.status.success() {
425 let reason = if rewrite.stderr.trim().is_empty() {
426 format!("RTK rewrite exited with {}", rewrite.status)
427 } else {
428 format!("RTK rewrite failed: {}", rewrite.stderr.trim())
429 };
430 let failure = CapabilityFailure::new(CapabilityFailureMode::Unavailable, reason);
431 self.remember_failure(&failure);
432 return Err(failure);
433 }
434 let rewritten = match bounded_text(
435 &redact_output(&rewrite.stdout),
436 self.config.max_output_tokens,
437 ) {
438 Ok(output) => output.trim().to_string(),
439 Err(reason) => {
440 let failure = CapabilityFailure::new(CapabilityFailureMode::InvalidOutput, reason);
441 self.remember_failure(&failure);
442 return Err(failure);
443 }
444 };
445 if rewritten.is_empty() {
446 let failure = CapabilityFailure::new(
447 CapabilityFailureMode::InvalidOutput,
448 "RTK rewrite returned empty output",
449 );
450 self.remember_failure(&failure);
451 return Err(failure);
452 }
453 if let Err(reason) = validate_shell_command(&rewritten) {
454 let failure = CapabilityFailure::new(CapabilityFailureMode::RejectedByPolicy, reason);
455 self.remember_failure(&failure);
456 return Err(failure);
457 }
458
459 let elapsed_ms = started.elapsed().as_millis() as u64;
460 let remaining_timeout = remaining_timeout(rewrite_timeout, elapsed_ms);
461 let native = native_execute(&rewritten, &prepared.cwd, remaining_timeout);
462 let output = redact_output(&native.output);
463 let output = match bounded_text(&output, self.config.max_output_tokens) {
464 Ok(output) => output,
465 Err(reason) => {
466 let failure = CapabilityFailure::new(CapabilityFailureMode::InvalidOutput, reason);
467 self.remember_failure(&failure);
468 return Err(failure);
469 }
470 };
471 let latency_ms = started.elapsed().as_millis() as u64;
472 let mut metrics = BTreeMap::new();
473 metrics.insert("rewrite_latency_ms".to_string(), rewrite.elapsed_ms);
474 metrics.insert("execution_latency_ms".to_string(), native.latency_ms);
475 metrics.insert("output_bytes".to_string(), output.len() as u64);
476 metrics.insert("quality_score".to_string(), 100);
477 metrics.insert(
478 "structurally_equal".to_string(),
479 u64::from(native.exit_code == 0 && !native.timed_out),
480 );
481 let success = native.exit_code == 0 && !native.timed_out;
482 let failure_mode = if native.timed_out {
483 Some(CapabilityFailureMode::Timeout)
484 } else if success {
485 None
486 } else {
487 Some(CapabilityFailureMode::Partial)
488 };
489 let output_ref = Some(evidence_ref(&output));
490 Ok(CapabilityResult {
491 success,
492 output_tokens: crate::core::tokens::count_tokens(&output) as u64,
493 latency_ms,
494 observation: CapabilityObservationV1 {
495 schema_version: CAPABILITY_OBSERVATION_SCHEMA_VERSION,
496 task_id: invocation.task_id.clone(),
497 capability_id: CAPABILITY_ID.to_string(),
498 capability_version: CAPABILITY_VERSION.to_string(),
499 success,
500 input_tokens: crate::core::tokens::count_tokens(&prepared.command) as u64,
501 output_tokens: crate::core::tokens::count_tokens(&output) as u64,
502 latency_ms,
503 failure_mode,
504 output_ref: output_ref.clone(),
505 metrics,
506 },
507 evidence_ref: output_ref,
508 })
509 }
510
511 pub fn observe_native(
513 &self,
514 invocation: &CapabilityInvocation,
515 ) -> OclaResult<CapabilityResult> {
516 let prepared = self
517 .prepare_invocation(invocation)
518 .map_err(|failure| OclaError::InvalidRequest(failure.reason))?;
519 Ok(native_result(
520 invocation,
521 &prepared.command,
522 &prepared.cwd,
523 effective_timeout(invocation.timeout_ms, self.config.timeout_ms),
524 ))
525 }
526
527 pub fn invoke_with_fallback(
530 &self,
531 invocation: &CapabilityInvocation,
532 ) -> OclaResult<CapabilityResult> {
533 invocation.validate()?;
534 if !matches!(invocation.input, CapabilityInput::ShellCommand { .. }) {
535 return Err(OclaError::InvalidRequest(
536 "rtk-shell-output accepts only shell commands".to_string(),
537 ));
538 }
539 match self.observe_rtk(invocation) {
540 Ok(result) => Ok(result),
541 Err(failure) => Ok(self.native_fallback(invocation, &failure)),
542 }
543 }
544
545 fn native_fallback(
546 &self,
547 invocation: &CapabilityInvocation,
548 failure: &CapabilityFailure,
549 ) -> CapabilityResult {
550 let prepared = self.prepare_invocation(invocation);
551 let Ok(prepared) = prepared else {
552 return failed_fallback_result(invocation, failure);
553 };
554 let mut result = native_result(
555 invocation,
556 &prepared.command,
557 &prepared.cwd,
558 native_fallback_timeout(invocation.timeout_ms, self.config.timeout_ms),
559 );
560 result.observation.failure_mode = Some(CapabilityFailureMode::FallbackToNative);
561 result
562 .observation
563 .metrics
564 .insert("fallback_available".to_string(), 1);
565 result.observation.metrics.insert(
566 "external_failure_mode".to_string(),
567 failure_mode_metric(failure.failure_mode),
568 );
569 result
570 }
571
572 fn prepare_invocation(
573 &self,
574 invocation: &CapabilityInvocation,
575 ) -> Result<PreparedInvocation, CapabilityFailure> {
576 if invocation.capability_id != CAPABILITY_ID {
577 return Err(CapabilityFailure::new(
578 CapabilityFailureMode::RejectedByPolicy,
579 format!("unexpected capability id {:?}", invocation.capability_id),
580 ));
581 }
582 let CapabilityInput::ShellCommand { command, workdir } = &invocation.input else {
583 return Err(CapabilityFailure::new(
584 CapabilityFailureMode::RejectedByPolicy,
585 "RTK accepts only shell command input",
586 ));
587 };
588 validate_shell_command(command).map_err(|reason| {
589 CapabilityFailure::new(CapabilityFailureMode::RejectedByPolicy, reason)
590 })?;
591
592 let cwd = workdir
593 .as_deref()
594 .map(PathBuf::from)
595 .or_else(|| self.config.working_dir.clone())
596 .unwrap_or_else(|| PathBuf::from("."));
597 let cwd = pathjail::canonicalize_or_self(&cwd);
598 if !cwd.is_dir() {
599 return Err(CapabilityFailure::new(
600 CapabilityFailureMode::RejectedByPolicy,
601 format!("working directory is not a directory: {}", cwd.display()),
602 ));
603 }
604 let root = self
605 .config
606 .sandbox_root
607 .clone()
608 .or_else(|| crate::core::config::Config::find_project_root().map(PathBuf::from))
609 .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")));
610 let root = pathjail::canonicalize_or_self(&root);
611 let jailed = pathjail::jail_path(&cwd, &root).map_err(|error| {
612 CapabilityFailure::new(
613 CapabilityFailureMode::RejectedByPolicy,
614 format!("PathJail rejected working directory: {error}"),
615 )
616 })?;
617 Ok(PreparedInvocation {
618 command: command.clone(),
619 cwd: jailed,
620 })
621 }
622}
623
624impl CapabilityAdapter for RtkShellAdapter {
625 fn manifest(&self) -> &lean_ctx_protocol::CapabilityManifestV1 {
626 static MANIFEST: OnceLock<lean_ctx_protocol::CapabilityManifestV1> = OnceLock::new();
627 MANIFEST.get_or_init(|| {
628 serde_json::from_str(MANIFEST_JSON).expect("RTK capability manifest must be valid")
629 })
630 }
631
632 fn invoke(&self, invocation: CapabilityInvocation) -> OclaResult<CapabilityResult> {
633 self.invoke_with_fallback(&invocation)
634 }
635
636 fn health_check(&self) -> OclaResult<bool> {
637 Ok(self.health_check_detailed().available)
638 }
639}
640
641impl Default for RtkShellAdapter {
642 fn default() -> Self {
643 Self::new(RtkConfig::default())
644 }
645}
646
647struct PreparedInvocation {
648 command: String,
649 cwd: PathBuf,
650}
651
652struct NativeOutput {
653 output: String,
654 exit_code: i32,
655 timed_out: bool,
656 latency_ms: u64,
657}
658
659fn validate_shell_command(command: &str) -> Result<(), String> {
660 if let Some(reason) = crate::tools::ctx_shell::validate_command(command) {
661 return Err(reason);
662 }
663 shell_allowlist::check_shell_allowlist(command).map_err(|error| error.to_string())
664}
665
666fn native_execute(command: &str, cwd: &Path, timeout_ms: u64) -> NativeOutput {
667 let started = Instant::now();
668 let (output, exit_code) = crate::server::execute::execute_command_with_env(
669 command,
670 &cwd.to_string_lossy(),
671 &BTreeMap::new().into_iter().collect(),
672 (timeout_ms != 0).then_some(timeout_ms),
673 );
674 let timed_out = output.contains(TIMEOUT_MARKER) || exit_code == 124;
675 NativeOutput {
676 output,
677 exit_code,
678 timed_out,
679 latency_ms: started.elapsed().as_millis() as u64,
680 }
681}
682
683fn native_result(
684 invocation: &CapabilityInvocation,
685 command: &str,
686 cwd: &Path,
687 timeout_ms: u64,
688) -> CapabilityResult {
689 let native = native_execute(command, cwd, timeout_ms);
690 let output = redact_output(&native.output);
691 let output_tokens = crate::core::tokens::count_tokens(&output) as u64;
692 let input_tokens = crate::core::tokens::count_tokens(command) as u64;
693 let success = native.exit_code == 0 && !native.timed_out;
694 let output_ref = Some(evidence_ref(&output));
695 let mut metrics = BTreeMap::new();
696 metrics.insert("exit_code".to_string(), native.exit_code.max(0) as u64);
697 metrics.insert("output_bytes".to_string(), output.len() as u64);
698 metrics.insert("quality_score".to_string(), u64::from(success) * 100);
699 CapabilityResult {
700 success,
701 output_tokens,
702 latency_ms: native.latency_ms,
703 observation: CapabilityObservationV1 {
704 schema_version: CAPABILITY_OBSERVATION_SCHEMA_VERSION,
705 task_id: invocation.task_id.clone(),
706 capability_id: CAPABILITY_ID.to_string(),
707 capability_version: CAPABILITY_VERSION.to_string(),
708 success,
709 input_tokens,
710 output_tokens,
711 latency_ms: native.latency_ms,
712 failure_mode: if native.timed_out {
713 Some(CapabilityFailureMode::Timeout)
714 } else if success {
715 None
716 } else {
717 Some(CapabilityFailureMode::Partial)
718 },
719 output_ref: output_ref.clone(),
720 metrics,
721 },
722 evidence_ref: output_ref,
723 }
724}
725
726fn failed_fallback_result(
727 invocation: &CapabilityInvocation,
728 failure: &CapabilityFailure,
729) -> CapabilityResult {
730 let mut metrics = BTreeMap::new();
731 metrics.insert("fallback_available".to_string(), 1);
732 metrics.insert(
733 "external_failure_mode".to_string(),
734 failure_mode_metric(failure.failure_mode),
735 );
736 CapabilityResult {
737 success: false,
738 output_tokens: 0,
739 latency_ms: 0,
740 observation: CapabilityObservationV1 {
741 schema_version: CAPABILITY_OBSERVATION_SCHEMA_VERSION,
742 task_id: invocation.task_id.clone(),
743 capability_id: CAPABILITY_ID.to_string(),
744 capability_version: CAPABILITY_VERSION.to_string(),
745 success: false,
746 input_tokens: crate::core::tokens::count_tokens(invocation.input.payload()) as u64,
747 output_tokens: 0,
748 latency_ms: 0,
749 failure_mode: Some(CapabilityFailureMode::FallbackToNative),
750 output_ref: failure.evidence_ref.clone(),
751 metrics,
752 },
753 evidence_ref: failure.evidence_ref.clone(),
754 }
755}
756
757fn resolve_executable(executable: &Path) -> Result<PathBuf, String> {
758 if executable.components().count() > 1 || executable.is_absolute() {
759 return executable
760 .is_file()
761 .then(|| pathjail::canonicalize_or_self(executable))
762 .ok_or_else(|| format!("RTK binary does not exist: {}", executable.display()));
763 }
764 let path_var = std::env::var_os("PATH").ok_or_else(|| "PATH is not set".to_string())?;
765 for directory in std::env::split_paths(&path_var) {
766 let candidate = directory.join(executable);
767 if candidate.is_file() {
768 return Ok(pathjail::canonicalize_or_self(&candidate));
769 }
770 }
771 Err(format!(
772 "RTK binary was not found on PATH: {}",
773 executable.display()
774 ))
775}
776
777pub(crate) fn sha256_file(path: &Path) -> Result<String, String> {
778 let bytes = fs::read(path).map_err(|error| format!("could not read RTK binary: {error}"))?;
779 let mut digest = Sha256::new();
780 digest.update(bytes);
781 let mut output = String::with_capacity(64);
782 for byte in digest.finalize() {
783 let _ = write!(&mut output, "{byte:02x}");
784 }
785 Ok(output)
786}
787
788fn hashes_equal(actual: &str, expected: &str) -> bool {
789 actual.eq_ignore_ascii_case(expected.trim().trim_start_matches("0x"))
790}
791
792fn unavailable_health(executable: PathBuf, reason: &str) -> RtkHealthReport {
793 unavailable_health_with_path(executable, None, reason.to_string())
794}
795
796fn unavailable_health_with_path(
797 executable: PathBuf,
798 resolved_executable: impl Into<Option<PathBuf>>,
799 reason: impl Into<String>,
800) -> RtkHealthReport {
801 RtkHealthReport {
802 executable,
803 resolved_executable: resolved_executable.into(),
804 available: false,
805 version: None,
806 sha256: None,
807 reason: Some(reason.into()),
808 }
809}
810
811fn bounded_probe_timeout(configured: u64) -> u64 {
812 if configured == 0 {
813 VERSION_PROBE_TIMEOUT_MS
814 } else {
815 configured.min(VERSION_PROBE_TIMEOUT_MS)
816 }
817}
818
819fn effective_timeout(invocation: u64, configured: u64) -> u64 {
820 match (invocation, configured) {
821 (0, value) | (value, 0) => value,
822 (left, right) => left.min(right),
823 }
824}
825
826fn native_fallback_timeout(invocation: u64, configured: u64) -> u64 {
827 if invocation == 0 {
828 configured
829 } else {
830 invocation
831 }
832}
833
834fn remaining_timeout(timeout_ms: u64, elapsed_ms: u64) -> u64 {
835 if timeout_ms == 0 {
836 0
837 } else {
838 timeout_ms.saturating_sub(elapsed_ms).max(1)
839 }
840}
841
842fn failure_mode_for_reason(reason: &str) -> CapabilityFailureMode {
843 if reason.contains("timed out") {
844 CapabilityFailureMode::Timeout
845 } else if reason.contains("output exceeded") {
846 CapabilityFailureMode::InvalidOutput
847 } else {
848 CapabilityFailureMode::Unavailable
849 }
850}
851
852fn failure_mode_metric(mode: CapabilityFailureMode) -> u64 {
853 match mode {
854 CapabilityFailureMode::Timeout => 1,
855 CapabilityFailureMode::Unavailable => 2,
856 CapabilityFailureMode::RejectedByPolicy => 3,
857 CapabilityFailureMode::InvalidOutput => 4,
858 CapabilityFailureMode::Partial => 5,
859 CapabilityFailureMode::FallbackToNative => 6,
860 CapabilityFailureMode::Internal => 7,
861 }
862}
863
864fn redact_output(output: &str) -> String {
865 crate::core::redaction::redact_text_if_enabled(output)
866}
867
868fn bounded_text(text: &str, max_tokens: u64) -> Result<String, String> {
869 if max_tokens == 0 || crate::core::tokens::count_tokens(text) as u64 <= max_tokens {
870 return Ok(text.to_string());
871 }
872 Err(format!(
873 "RTK output exceeded the configured token bound ({max_tokens})"
874 ))
875}
876
877fn run_bounded_process(
878 executable: &Path,
879 args: &[String],
880 cwd: &Path,
881 timeout_ms: u64,
882 capture_bytes: usize,
883) -> Result<ProcessOutput, String> {
884 let mut command = Command::new(executable);
885 command.args(args).current_dir(cwd).stdin(Stdio::null());
886 let started = Instant::now();
887 let captured = crate::core::process_capture::run_with_output_limits(
888 &mut command,
889 (timeout_ms != 0).then(|| Duration::from_millis(timeout_ms)),
890 capture_bytes,
891 capture_bytes.min(64 * 1024),
892 )?;
893 if captured.timed_out {
894 return Err(format!("RTK process timed out after {timeout_ms}ms"));
895 }
896 Ok(ProcessOutput {
897 stdout: String::from_utf8_lossy(&captured.output.stdout).into_owned(),
898 stderr: String::from_utf8_lossy(&captured.output.stderr).into_owned(),
899 status: captured.output.status,
900 elapsed_ms: started.elapsed().as_millis() as u64,
901 })
902}
903
904#[cfg(test)]
905mod tests {
906 use std::collections::BTreeMap;
907 use std::path::Path;
908
909 use super::{CAPABILITY_ID, CapabilityFailure, RtkConfig, RtkShellAdapter};
910 use crate::core::ocla::invocation::{
911 CapabilityAdapter, CapabilityInput, CapabilityInvocation, PolicyConstraints,
912 };
913
914 fn invocation(command: &str) -> CapabilityInvocation {
915 CapabilityInvocation {
916 task_id: "task-rtk-test".to_string(),
917 capability_id: CAPABILITY_ID.to_string(),
918 capability_version: "1.0.0".to_string(),
919 input: CapabilityInput::ShellCommand {
920 command: command.to_string(),
921 workdir: None,
922 },
923 policy_constraints: PolicyConstraints::default(),
924 timeout_ms: 500,
925 }
926 }
927
928 fn invocation_at(command: &str, workdir: &Path) -> CapabilityInvocation {
929 CapabilityInvocation {
930 input: CapabilityInput::ShellCommand {
931 command: command.to_string(),
932 workdir: Some(workdir.to_string_lossy().into_owned()),
933 },
934 ..invocation(command)
935 }
936 }
937
938 #[test]
939 fn kill_switch_blocks_external_execution_and_falls_back() {
940 let adapter = RtkShellAdapter::new(RtkConfig::new("definitely-not-installed"));
941 adapter.kill_switch().activate("test");
942 let failure = adapter.observe_rtk(&invocation("printf fallback"));
943 assert_eq!(failure, Err(CapabilityFailure::kill_switched()));
944 let result = adapter
945 .invoke_with_fallback(&invocation("printf fallback"))
946 .expect("native fallback");
947 assert!(result.observation.failure_mode.is_some());
948 assert_eq!(
949 result.observation.metrics.get("fallback_available"),
950 Some(&1)
951 );
952 }
953
954 #[test]
955 fn missing_binary_is_evidenced_and_falls_back() {
956 let sandbox_root = Path::new(env!("CARGO_MANIFEST_DIR"));
957 let adapter = RtkShellAdapter::new(
958 RtkConfig::new("definitely-not-installed").with_sandbox_root(sandbox_root),
959 );
960 let result = adapter
961 .invoke_with_fallback(&invocation_at("printf fallback", sandbox_root))
962 .expect("native fallback");
963 assert!(
964 result.success,
965 "fallback result: {result:?}; external failure: {:?}",
966 adapter.last_failure()
967 );
968 let failure = adapter.last_failure().expect("failure evidence");
969 assert_eq!(
970 failure.failure_mode,
971 crate::core::ocla::invocation::CapabilityFailureMode::Unavailable
972 );
973 assert!(failure.fallback_available);
974 assert!(failure.evidence_ref.is_some());
975 }
976
977 #[test]
978 fn manifest_has_external_identity() {
979 let adapter = RtkShellAdapter::default();
980 assert_eq!(adapter.manifest().capability_id.as_str(), CAPABILITY_ID);
981 assert!(adapter.manifest().local);
982 assert!(!adapter.manifest().remote);
983 }
984
985 #[cfg(unix)]
986 #[test]
987 fn timeout_is_evidenced_and_falls_back() {
988 use super::sha256_file;
989 use std::os::unix::fs::PermissionsExt;
990 use tempfile::tempdir;
991
992 let directory = tempdir().expect("temporary directory");
993 let binary = directory.path().join("rtk");
994 std::fs::write(
995 &binary,
996 "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then echo 'rtk 1.2.3'; exit 0; fi\nsleep 2\n",
997 )
998 .expect("write fake RTK");
999 std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o755))
1000 .expect("make fake RTK executable");
1001 let hash = sha256_file(&binary).expect("hash fake RTK");
1002 let config = RtkConfig::new(&binary)
1003 .with_pins("1.2.3", hash)
1004 .with_working_dir(directory.path())
1005 .with_sandbox_root(directory.path())
1006 .with_timeout_ms(50);
1007 let adapter = RtkShellAdapter::new(config);
1008 let result = adapter
1009 .invoke_with_fallback(&invocation("printf fallback"))
1010 .expect("native fallback after timeout");
1011 assert!(
1012 result.success,
1013 "fallback result: {result:?}; external failure: {:?}",
1014 adapter.last_failure()
1015 );
1016 let failure = adapter.last_failure().expect("timeout evidence");
1017 assert_eq!(
1018 failure.failure_mode,
1019 crate::core::ocla::invocation::CapabilityFailureMode::Timeout,
1020 "failure: {failure:?}"
1021 );
1022 assert!(failure.fallback_available);
1023 assert!(failure.evidence_ref.is_some());
1024 }
1025
1026 #[cfg(unix)]
1027 #[test]
1028 fn process_capture_does_not_wait_for_inherited_output_handles() {
1029 let directory = tempfile::tempdir().expect("temporary directory");
1030 let started = std::time::Instant::now();
1031 let output = super::run_bounded_process(
1032 std::path::Path::new("/bin/sh"),
1033 &["-c".to_owned(), "sleep 2 & printf ready".to_owned()],
1034 directory.path(),
1035 100,
1036 1024,
1037 )
1038 .expect("parent completed successfully");
1039 assert!(output.status.success());
1040 assert_eq!(output.stdout, "ready");
1041 assert!(
1042 started.elapsed() < std::time::Duration::from_secs(1),
1043 "completed parent must not wait for a descendant's inherited pipe"
1044 );
1045 }
1046
1047 #[cfg(unix)]
1048 #[test]
1049 fn process_capture_preserves_status_streams_and_zero_timeout() {
1050 let directory = tempfile::tempdir().expect("temporary directory");
1051 let output = super::run_bounded_process(
1052 std::path::Path::new("/bin/sh"),
1053 &[
1054 "-c".to_owned(),
1055 "sleep 0.02; printf good; printf bad >&2; exit 7".to_owned(),
1056 ],
1057 directory.path(),
1058 0,
1059 4,
1060 )
1061 .expect("zero timeout is unlimited, not immediate cancellation");
1062 assert_eq!(output.status.code(), Some(7));
1063 assert_eq!(output.stdout, "good");
1064 assert_eq!(output.stderr, "bad");
1065 }
1066
1067 #[cfg(unix)]
1068 #[test]
1069 fn process_capture_rejects_stdout_and_stderr_overflow() {
1070 let directory = tempfile::tempdir().expect("temporary directory");
1071 for script in ["printf four", "printf four >&2"] {
1072 let failure = super::run_bounded_process(
1073 std::path::Path::new("/bin/sh"),
1074 &["-c".to_owned(), script.to_owned()],
1075 directory.path(),
1076 100,
1077 3,
1078 )
1079 .err()
1080 .expect("oversized output cannot be admitted");
1081 assert_eq!(
1082 super::failure_mode_for_reason(&failure),
1083 crate::core::ocla::invocation::CapabilityFailureMode::InvalidOutput
1084 );
1085 }
1086 }
1087
1088 #[cfg(unix)]
1089 #[test]
1090 fn process_capture_stops_oversized_writer_without_timeout() {
1091 let directory = tempfile::tempdir().expect("temporary directory");
1092 let started = std::time::Instant::now();
1093 let failure = super::run_bounded_process(
1094 std::path::Path::new("/bin/sh"),
1095 &["-c".to_owned(), "printf four; sleep 2".to_owned()],
1096 directory.path(),
1097 0,
1098 3,
1099 )
1100 .err()
1101 .expect("overflow must stop the writer even without a time limit");
1102 assert_eq!(
1103 super::failure_mode_for_reason(&failure),
1104 crate::core::ocla::invocation::CapabilityFailureMode::InvalidOutput
1105 );
1106 assert!(started.elapsed() < std::time::Duration::from_secs(1));
1107 }
1108
1109 #[cfg(unix)]
1110 #[test]
1111 fn process_capture_preserves_separate_stderr_ceiling() {
1112 let directory = tempfile::tempdir().expect("temporary directory");
1113 let failure = super::run_bounded_process(
1114 std::path::Path::new("/bin/sh"),
1115 &["-c".to_owned(), "head -c 65537 /dev/zero >&2".to_owned()],
1116 directory.path(),
1117 1000,
1118 128 * 1024,
1119 )
1120 .err()
1121 .expect("stderr remains limited to 64KiB even with a larger stdout limit");
1122 assert!(failure.contains("stderr output exceeded"), "{failure}");
1123 }
1124
1125 #[test]
1126 fn observations_are_payload_free() {
1127 let adapter = RtkShellAdapter::new(RtkConfig::new("missing-rtk"));
1128 let result = adapter
1129 .invoke_with_fallback(&invocation("printf secret-value"))
1130 .expect("native fallback");
1131 assert!(
1132 !result
1133 .observation
1134 .output_ref
1135 .as_deref()
1136 .unwrap_or_default()
1137 .contains("secret-value")
1138 );
1139 assert!(!BTreeMap::<String, u64>::from_iter(result.observation.metrics.clone()).is_empty());
1140 }
1141}