Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions platform/process/src/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ pub(super) fn inherit(
&& !matches!(
upper.as_str(),
"MAKA_CODEX_AUTH_FILE"
| "MAKA_AUTOMATION_STATE"
| "OPENAI_IDENTITY_TOKEN_FILE"
| "OPENAI_WORKLOAD_IDENTITY_CONTEXT"
| "OPENAI_FEDERATION_RULE_ID"
Expand All @@ -82,6 +83,7 @@ mod tests {
("OPENROUTER_API_KEY", "key"),
("api_ToKeN", "token"),
("MAKA_RUNTIME_HOST_LAUNCH_OWNER_LEASE_FD", "7"),
("MAKA_AUTOMATION_STATE", "42"),
("SSH_AUTH_SOCK", "/agent.sock"),
("Database_Password", "password"),
("OPENAI_WORKLOAD_IDENTITY_CONTEXT", "context"),
Expand Down
44 changes: 28 additions & 16 deletions platform/process/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,37 +299,40 @@ impl ShellExecutor {
}

impl Command {
/// Run a program with standard input and collect its output after its process tree exits.
/// Run a protocol program with standard input, bounded stdout tail, and full process-tree wait.
pub async fn run_with_input(
self,
input: Vec<u8>,
stdout_limit: usize,
timeout_ms: u64,
cancellation: CancellationToken,
) -> Result<PipeResult, ToolError> {
validate_timeout(timeout_ms)?;
self.run_captured(Some(input), Some(timeout_ms), cancellation, None)
.await
self.run_captured(
process::Mode::Protocol {
input,
stdout_limit,
},
Some(timeout_ms),
cancellation,
None,
)
.await
}

async fn run_captured(
self,
input: Option<Vec<u8>>,
mode: process::Mode,
timeout_ms: Option<u64>,
cancellation: CancellationToken,
observer: Option<tokio::sync::mpsc::Sender<PipeEvent>>,
) -> Result<PipeResult, ToolError> {
// The worker owns termination even if its caller drops the future.
let cancellation = cancellation.child_token();
let _cancel_on_drop = cancellation.clone().drop_guard();
tokio::spawn(process::run(
self,
input,
timeout_ms,
cancellation,
observer,
))
.await
.map_err(|e| ToolError::CleanupUnconfirmed(format!("Process worker lost: {e}")))?
tokio::spawn(process::run(self, mode, timeout_ms, cancellation, observer))
.await
.map_err(|e| ToolError::CleanupUnconfirmed(format!("Process worker lost: {e}")))?
}

/// No native resources exist until completion is polled. The accepted worker
Expand All @@ -343,8 +346,12 @@ impl Command {
return Err(failed("invalid background shell command or timeout"));
}
let (observer, events) = tokio::sync::mpsc::channel(8);
let completion =
Box::pin(self.run_captured(None, timeout_ms, cancellation, Some(observer)));
let completion = Box::pin(self.run_captured(
process::Mode::Shell,
timeout_ms,
cancellation,
Some(observer),
));
Ok(ObservedProcess { events, completion })
}
}
Expand All @@ -370,7 +377,12 @@ impl ToolExecutor for ShellExecutor {
let executor = executor.with_login_shell(input.login);
let plan = executor.prepare(&input.command, false)?;
let captured = plan
.run_captured(None, Some(input.timeout_ms), cancellation, None)
.run_captured(
process::Mode::Shell,
Some(input.timeout_ms),
cancellation,
None,
)
.await?;
Ok(captured.into_output(executor.cwd, input.command))
})
Expand Down
12 changes: 8 additions & 4 deletions platform/process/src/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ pub struct Captured {
pub stdout: String,
pub stderr: String,
pub stdout_truncated: bool,
pub stdout_eof: bool,
pub stderr_truncated: bool,
}

Expand Down Expand Up @@ -76,12 +77,15 @@ impl Captured {
}

pub(crate) fn new(outcome: Outcome, mut stdout: Tail, mut stderr: Tail) -> Self {
let stdout_text = stdout.text();
let stderr_text = stderr.text();
Self {
outcome,
stdout: stdout.text(),
stderr: stderr.text(),
stdout_truncated: stdout.truncated,
stderr_truncated: stderr.truncated,
stdout: stdout_text,
stderr: stderr_text,
stdout_truncated: stdout.truncated(),
stdout_eof: stdout.reached_eof,
stderr_truncated: stderr.truncated(),
}
}
}
Expand Down
17 changes: 15 additions & 2 deletions platform/process/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,14 @@ use std::{io, time::Duration};
use tokio::io::AsyncWriteExt;
use tokio_util::sync::CancellationToken;

pub(crate) enum Mode {
Shell,
Protocol { input: Vec<u8>, stdout_limit: usize },
}

pub(crate) async fn run(
plan: crate::Command,
input: Option<Vec<u8>>,
mode: Mode,
timeout_ms: Option<u64>,
cancellation: CancellationToken,
observer: Option<tokio::sync::mpsc::Sender<PipeEvent>>,
Expand All @@ -55,7 +60,13 @@ pub(crate) async fn run(
let _ = observer.try_send(PipeEvent::Started);
}
let exited = CancellationToken::new();
let owns_tree = input.is_some();
let (input, owns_tree, stdout_limit) = match mode {
Mode::Shell => (None, false, tail::TAIL_BYTES),
Mode::Protocol {
input,
stdout_limit,
} => (Some(input), true, stdout_limit),
};
let lifecycle = async {
let outcome = settle(&mut child, timeout_ms, cancellation, owns_tree).await;
exited.cancel();
Expand All @@ -77,11 +88,13 @@ pub(crate) async fn run(
tail::capture(
stdout,
exited.clone(),
stdout_limit,
observer.clone().map(|o| (o, PipeStream::Stdout))
),
tail::capture(
stderr,
exited.clone(),
tail::TAIL_BYTES,
observer.map(|o| (o, PipeStream::Stderr))
),
);
Expand Down
118 changes: 94 additions & 24 deletions platform/process/src/tail.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,63 +17,69 @@
* under the License.
*/

use std::time::Duration;
use std::{collections::VecDeque, time::Duration};
use tokio::io::{AsyncRead, AsyncReadExt};
use tokio_util::sync::CancellationToken;

const TAIL_BYTES: usize = 65_536;
pub(crate) const TAIL_BYTES: usize = 65_536;
pub(crate) const DRAIN: Duration = Duration::from_secs(2);

#[derive(Default)]
pub(crate) struct Tail {
bytes: Vec<u8>,
pub truncated: bool,
bytes: VecDeque<u8>,
limit: usize,
pub prefix_dropped: bool,
pub reached_eof: bool,
}

impl Tail {
fn push(&mut self, bytes: &[u8]) {
let overflow = (self.bytes.len() + bytes.len()).saturating_sub(TAIL_BYTES);
let overflow = (self.bytes.len() + bytes.len()).saturating_sub(self.limit);
if overflow > 0 {
self.truncated = true;
if overflow >= self.bytes.len() {
self.bytes.clear();
self.bytes
.extend_from_slice(&bytes[bytes.len().saturating_sub(TAIL_BYTES)..]);
return;
}
self.bytes.drain(..overflow);
self.prefix_dropped = true;
self.bytes.drain(..overflow.min(self.bytes.len()));
}
self.bytes.extend_from_slice(bytes);
self.bytes
.extend(&bytes[bytes.len().saturating_sub(self.limit)..]);
}

pub fn truncated(&self) -> bool {
self.prefix_dropped || !self.reached_eof
}

pub fn text(&mut self) -> String {
let mut start = 0;
// A byte tail can begin inside a valid UTF-8 code point.
if self.truncated {
if self.prefix_dropped {
while start < self.bytes.len() && self.bytes[start] & 0xc0 == 0x80 {
start += 1;
}
}
let text = String::from_utf8_lossy(&self.bytes[start..]);
let text = String::from_utf8_lossy(&self.bytes.make_contiguous()[start..]);
// Invalid source bytes can expand to replacement characters.
let mut start = text.len().saturating_sub(TAIL_BYTES);
let mut start = text.len().saturating_sub(self.limit);
while !text.is_char_boundary(start) {
start += 1;
}
self.truncated |= start > 0;
self.prefix_dropped |= start > 0;
text[start..].to_owned()
}
}

pub(crate) async fn capture(
mut pipe: impl AsyncRead + Unpin,
exited: CancellationToken,
limit: usize,
observer: Option<(
tokio::sync::mpsc::Sender<crate::PipeEvent>,
maka_plugin_core::shell_run::PipeStream,
)>,
) -> Tail {
let mut tail = Tail::default();
let mut tail = Tail {
bytes: VecDeque::new(),
limit,
prefix_dropped: false,
reached_eof: false,
};
let deadline = async {
exited.cancelled().await;
tokio::time::sleep(DRAIN).await
Expand All @@ -83,9 +89,12 @@ pub(crate) async fn capture(
loop {
tokio::select! {
biased;
_ = &mut deadline => { tail.truncated = true; break; }
_ = &mut deadline => break,
read = pipe.read(&mut buffer) => match read {
Ok(0) => break,
Ok(0) => {
tail.reached_eof = true;
break;
}
Ok(n) => {
tail.push(&buffer[..n]);
if let Some((observer, stream)) = &observer {
Expand All @@ -94,14 +103,75 @@ pub(crate) async fn capture(
let event = crate::PipeEvent::Output { stream: *stream, bytes: buffer[..n].to_vec() };
tokio::select! {
biased;
_ = &mut deadline => { tail.truncated = true; break; }
_ = &mut deadline => break,
_ = observer.send(event) => {}
}
}
},
Err(_) => { tail.truncated = true; break; }
Err(_) => break,
}
}
}
tail
}

#[cfg(test)]
mod tests {
use super::*;
use std::{
io,
pin::Pin,
task::{Context, Poll},
};

struct FailAfter {
chunk: Option<&'static [u8]>,
}

impl AsyncRead for FailAfter {
fn poll_read(
mut self: Pin<&mut Self>,
_cx: &mut Context<'_>,
buf: &mut tokio::io::ReadBuf<'_>,
) -> Poll<io::Result<()>> {
if let Some(bytes) = self.chunk.take() {
buf.put_slice(bytes);
Poll::Ready(Ok(()))
} else {
Poll::Ready(Err(io::Error::new(
io::ErrorKind::BrokenPipe,
"pipe failed",
)))
}
}
}

#[tokio::test]
async fn capture_distinguishes_prefix_overflow_from_incomplete_reads() {
let mut overflow = capture(
io::Cursor::new(b"dropped-line\n{\"trigger\":true}\n"),
CancellationToken::new(),
20,
None,
)
.await;
assert_eq!(overflow.text(), "ne\n{\"trigger\":true}\n");
assert!(overflow.prefix_dropped);
assert!(overflow.reached_eof);
assert!(overflow.truncated());

let mut failed = capture(
FailAfter {
chunk: Some(b"checking\ntrue\n"),
},
CancellationToken::new(),
64,
None,
)
.await;
assert_eq!(failed.text(), "checking\ntrue\n");
assert!(!failed.prefix_dropped);
assert!(!failed.reached_eof);
assert!(failed.truncated());
}
}
1 change: 1 addition & 0 deletions plugins/agent/facts/locales/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@
"create_automation": "Automatisierung erstellen",
"create_automation_titled": "Automatisierung erstellen · {title}",
"list_automations": "Automatisierungen auflisten",
"test_automation_script": "Automatisierungsskript testen",
"pause_automation": "Automatisierung pausieren",
"resume_automation": "Automatisierung fortsetzen",
"delete_automation": "Automatisierung löschen",
Expand Down
1 change: 1 addition & 0 deletions plugins/agent/facts/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@
"create_automation": "Create automation",
"create_automation_titled": "Create automation · {title}",
"list_automations": "List automations",
"test_automation_script": "Test automation script",
"pause_automation": "Pause automation",
"resume_automation": "Resume automation",
"delete_automation": "Delete automation",
Expand Down
1 change: 1 addition & 0 deletions plugins/agent/facts/locales/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@
"create_automation": "Crear automatización",
"create_automation_titled": "Crear automatización · {title}",
"list_automations": "Listar automatizaciones",
"test_automation_script": "Probar script de automatización",
"pause_automation": "Pausar automatización",
"resume_automation": "Reanudar automatización",
"delete_automation": "Eliminar automatización",
Expand Down
1 change: 1 addition & 0 deletions plugins/agent/facts/locales/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@
"create_automation": "Créer une automatisation",
"create_automation_titled": "Créer une automatisation · {title}",
"list_automations": "Lister les automatisations",
"test_automation_script": "Tester le script d'automatisation",
"pause_automation": "Mettre en pause l'automatisation",
"resume_automation": "Reprendre l'automatisation",
"delete_automation": "Supprimer l'automatisation",
Expand Down
1 change: 1 addition & 0 deletions plugins/agent/facts/locales/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@
"create_automation": "Crea automazione",
"create_automation_titled": "Crea automazione · {title}",
"list_automations": "Elenca automazioni",
"test_automation_script": "Testa script di automazione",
"pause_automation": "Metti in pausa automazione",
"resume_automation": "Riprendi automazione",
"delete_automation": "Elimina automazione",
Expand Down
Loading