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