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
13 changes: 7 additions & 6 deletions src/crates/assembly/core/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,17 +211,18 @@ Narrower local guides already exist for some subtrees:

## Verification

For WriteStdin steering, port routing, streaming and legacy result compatibility:
For ExecCommand/WriteStdin steering, port routing, streaming and legacy result compatibility:

```bash
cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git --lib agentic::tools::implementations::exec_command::stdin::
cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git --lib agentic::tools::implementations::exec_command::
cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git --lib yieldable_tools_end_normally_for_every_non_none_round_injection_policy
```

WriteStdin uses the same round-injection yield token as AgentWait. Only the
output wait ends; submitted stdin is not replayed and process control remains
explicit. The optional `wait_end_reason: "steered"` result is separate from
process `completion`; old results without it keep their existing meaning.
ExecCommand and WriteStdin use the same round-injection yield token as AgentWait.
Only the output wait ends; the launched command and submitted stdin are not
replayed, and process control remains explicit. Continue with the returned
session ID through WriteStdin. The optional `wait_end_reason: "steered"` result
is separate from process `completion`; old results without it keep their existing meaning.
These Core fixtures cover both runtime ports with mocks, not live remote hosts.

For desktop card admission, per-turn Peer origin, recovery context and subagent
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -586,6 +586,7 @@ impl ExecCommandTool {
tty,
yield_time_ms: Some(yield_time_ms),
max_output_chars: None,
wait_interrupt: context.round_injection_preemption_token().cloned(),
lifecycle_sink: Self::start_remote_lifecycle_bridge(context, self.name()),
output_sink: output_capture_tx,
};
Expand Down Expand Up @@ -632,7 +633,7 @@ impl ExecCommandTool {
}
}

let data = exec_command_result_value(ExecCommandResultData {
let mut data = exec_command_result_value(ExecCommandResultData {
fields: ExecCommandResultFields {
chunk_id: response.chunk_id,
wall_time_seconds: response.wall_time_seconds,
Expand All @@ -647,6 +648,9 @@ impl ExecCommandTool {
tty,
shell: Self::remote_shell_metadata(&workdir, &shell, env_snapshot.is_some()),
});
if response.wait_interrupted {
data["wait_end_reason"] = json!("steered");
}
let result_for_assistant = Self::response_for_assistant(&data);

Ok(vec![ToolResult::Result {
Expand Down Expand Up @@ -687,6 +691,7 @@ TTY modes:

Waiting and continuation:
- yield_time_ms waits for output until the process exits or the deadline is reached. It does not stop the process.
- User steering can end the wait early and return output collected so far. The process continues running; use the returned session_id with WriteStdin instead of launching the command again.
- If the process is still running after `yield_time_ms`, the result includes a numeric session_id.
- Use WriteStdin to poll for more output or send input to tty=true sessions, and ExecControl to interrupt or kill it.

Expand Down Expand Up @@ -742,6 +747,7 @@ Output:
"output": {"type": "string"},
"session_id": {"anyOf": [{"type": "integer"}, {"type": "null"}]},
"exit_code": {"anyOf": [{"type": "integer"}, {"type": "null"}]},
"wait_end_reason": {"type": "string", "enum": ["steered"]},
"completion": {
"anyOf": [
{"type": "null"},
Expand Down Expand Up @@ -781,6 +787,10 @@ Output:
true
}

fn round_injection_yieldable(&self) -> bool {
true
}

async fn validate_input(
&self,
input: &Value,
Expand Down Expand Up @@ -887,6 +897,7 @@ Output:
tty,
yield_time_ms: Some(yield_time_ms),
max_output_chars: None,
wait_interrupt: context.round_injection_preemption_token().cloned(),
lifecycle_sink: Self::start_local_lifecycle_bridge(context, self.name()),
output_sink: output_capture_tx,
};
Expand Down Expand Up @@ -933,7 +944,7 @@ Output:
}
}

let data = exec_command_result_value(ExecCommandResultData {
let mut data = exec_command_result_value(ExecCommandResultData {
fields: ExecCommandResultFields {
chunk_id: response.chunk_id,
wall_time_seconds: response.wall_time_seconds,
Expand All @@ -948,6 +959,9 @@ Output:
tty,
shell: Self::shell_metadata_value(&shell),
});
if response.wait_interrupted {
data["wait_end_reason"] = json!("steered");
}
let result_for_assistant = Self::response_for_assistant(&data);

Ok(vec![ToolResult::Result {
Expand Down Expand Up @@ -1083,7 +1097,7 @@ mod tests {
assert!(tool.prepared_shells.lock().await.is_empty());
}

fn local_tool_context(workspace: &Path) -> ToolUseContext {
pub(super) fn local_tool_context(workspace: &Path) -> ToolUseContext {
ToolUseContext {
tool_call_id: None,
agent_type: Some("Standard".to_string()),
Expand All @@ -1100,7 +1114,7 @@ mod tests {
}
}

fn remote_tool_context(root: &str) -> ToolUseContext {
pub(super) fn remote_tool_context(root: &str) -> ToolUseContext {
let session_identity =
workspace_session_identity(root, Some("conn-1"), Some("remote-host"))
.expect("remote session identity should build");
Expand Down Expand Up @@ -1468,3 +1482,7 @@ mod tests {
#[cfg(all(test, unix))]
#[path = "guard_tests.rs"]
mod guard_tests;

#[cfg(test)]
#[path = "command_steering_tests.rs"]
mod steering_tests;
Original file line number Diff line number Diff line change
@@ -0,0 +1,265 @@
use super::tests::{local_tool_context, remote_tool_context};
use super::*;
use crate::agentic::tools::framework::ToolResult;
use openbitfun_runtime_ports::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use tokio_util::sync::CancellationToken;

#[derive(Debug)]
struct ExecProbe {
streaming: bool,
calls: AtomicUsize,
}

impl RuntimeServicePort for ExecProbe {
fn capability(&self) -> RuntimeServiceCapability {
RuntimeServiceCapability::Terminal
}
}

#[async_trait::async_trait]
impl TerminalPort for ExecProbe {
async fn exec_command(
&self,
request: TerminalExecCommandRequest,
) -> PortResult<TerminalExecCommandResponse> {
assert_eq!(self.streaming, false);
assert!(request.tty);
assert_eq!(request.yield_time_ms, Some(600_000));
self.calls.fetch_add(1, Ordering::SeqCst);
assert!(request.argv.last().unwrap().contains("echo steering-probe"));
Ok(TerminalExecCommandResponse {
chunk_id: "chunk".into(),
wall_time_seconds: 0.01,
output: "partial".into(),
session_id: Some(42),
exit_code: None,
original_output_chars: 7,
completion: None,
wait_interrupted: request
.wait_interrupt
.as_ref()
.is_some_and(CancellationToken::is_cancelled),
})
}
async fn exec_command_streaming(
&self,
request: TerminalExecCommandRequest,
sink: TerminalExecStreamingOutputSink,
) -> PortResult<TerminalExecCommandResponse> {
assert_eq!(self.streaming, true);
assert!(request.tty);
assert_eq!(request.yield_time_ms, Some(600_000));
self.calls.fetch_add(1, Ordering::SeqCst);
assert!(request.argv.last().unwrap().contains("echo steering-probe"));
sink.send("partial".into()).await.unwrap();
Ok(TerminalExecCommandResponse {
chunk_id: "chunk".into(),
wall_time_seconds: 0.01,
output: "partial".into(),
session_id: Some(42),
exit_code: None,
original_output_chars: 7,
completion: None,
wait_interrupted: request
.wait_interrupt
.as_ref()
.is_some_and(CancellationToken::is_cancelled),
})
}
async fn write_stdin(
&self,
_: TerminalWriteStdinRequest,
) -> PortResult<TerminalExecCommandResponse> {
panic!("initial wait must not replay input or control the process")
}
async fn write_stdin_streaming(
&self,
_: TerminalWriteStdinRequest,
_: TerminalExecStreamingOutputSink,
) -> PortResult<TerminalExecCommandResponse> {
panic!("initial wait must not replay input or control the process")
}
async fn send_stdin(&self, _: TerminalSendStdinRequest) -> PortResult<()> {
panic!("initial wait must not replay input or control the process")
}
async fn control_session(
&self,
_: TerminalExecControlRequest,
) -> PortResult<TerminalExecCommandResponse> {
panic!("initial wait must not replay input or control the process")
}
}

#[async_trait::async_trait]
impl RemoteExecPort for ExecProbe {
async fn exec_command_once(
&self,
_: RemoteExecOneShotCommandRequest,
) -> PortResult<RemoteExecOneShotCommandResponse> {
Ok(RemoteExecOneShotCommandResponse {
stdout: "/bin/sh\n".into(),
stderr: String::new(),
exit_code: 0,
interrupted: false,
timed_out: false,
})
}
async fn exec_command(
&self,
request: RemoteExecCommandRequest,
) -> PortResult<RemoteExecCommandResponse> {
if request.max_output_chars.is_some() {
// Environment capture is a separate best-effort setup command.
assert!(request.wait_interrupt.is_none());
return Err(PortError::new(
PortErrorKind::NotAvailable,
"no environment snapshot",
));
}
assert_eq!(self.streaming, false);
assert!(request.tty);
assert_eq!(request.yield_time_ms, Some(600_000));
self.calls.fetch_add(1, Ordering::SeqCst);
assert!(request.command.contains("echo steering-probe"));
Ok(RemoteExecCommandResponse {
chunk_id: "chunk".into(),
wall_time_seconds: 0.01,
output: "partial".into(),
session_id: Some(42),
exit_code: None,
original_output_chars: 7,
completion: None,
wait_interrupted: request
.wait_interrupt
.as_ref()
.is_some_and(CancellationToken::is_cancelled),
})
}
async fn exec_command_streaming(
&self,
request: RemoteExecCommandRequest,
sink: RemoteExecStreamingOutputSink,
) -> PortResult<RemoteExecCommandResponse> {
assert_eq!(self.streaming, true);
assert!(request.tty);
assert_eq!(request.yield_time_ms, Some(600_000));
self.calls.fetch_add(1, Ordering::SeqCst);
assert!(request.command.contains("echo steering-probe"));
sink.send("partial".into()).await.unwrap();
Ok(RemoteExecCommandResponse {
chunk_id: "chunk".into(),
wall_time_seconds: 0.01,
output: "partial".into(),
session_id: Some(42),
exit_code: None,
original_output_chars: 7,
completion: None,
wait_interrupted: request
.wait_interrupt
.as_ref()
.is_some_and(CancellationToken::is_cancelled),
})
}
async fn write_stdin(
&self,
_: RemoteWriteStdinRequest,
) -> PortResult<RemoteExecCommandResponse> {
panic!("initial wait must not replay input or control the process")
}
async fn write_stdin_streaming(
&self,
_: RemoteWriteStdinRequest,
_: RemoteExecStreamingOutputSink,
) -> PortResult<RemoteExecCommandResponse> {
panic!("initial wait must not replay input or control the process")
}
async fn send_stdin(&self, _: RemoteSendStdinRequest) -> PortResult<()> {
panic!("initial wait must not replay input or control the process")
}
async fn control_session(
&self,
_: RemoteExecControlRequest,
) -> PortResult<RemoteExecCommandResponse> {
panic!("initial wait must not replay input or control the process")
}
}

#[test]
fn exec_command_owns_timeout_and_yields_to_round_injection() {
let tool = ExecCommandTool::new();
assert!(tool.manages_own_execution_timeout());
assert!(tool.round_injection_yieldable());
assert!(tool.is_concurrency_safe(None));
assert!(tool.output_schema()["properties"]
.get("wait_end_reason")
.is_some());
assert!(!tool.output_schema()["required"]
.as_array()
.unwrap()
.contains(&json!("wait_end_reason")));
}

#[tokio::test]
async fn exec_command_steering_reaches_both_ports_and_preserves_legacy_results() {
let workspace = tempfile::tempdir().unwrap();
for remote in [false, true] {
for streaming in [false, true] {
for steered in [false, true] {
let mut context = if remote {
remote_tool_context("/home/me/project")
} else {
local_tool_context(workspace.path())
};
context.tool_call_id =
streaming.then(|| format!("exec-steering-{remote}-{steered}"));
let probe = Arc::new(ExecProbe {
streaming,
calls: AtomicUsize::new(0),
});
let token = CancellationToken::new();
token.cancel();
context.runtime_handles = context
.runtime_handles
.with_round_injection_preemption_token(steered.then_some(token))
.with_terminal_port(Some(probe.clone()))
.with_remote_exec_port(Some(probe.clone()));
let tool = ExecCommandTool::new();
let results = tool
.call_impl(
&json!({
"cmd":"echo steering-probe", "tty":true, "yield_time_ms":600_000,
}),
&context,
)
.await
.unwrap();
assert_eq!(probe.calls.load(Ordering::SeqCst), 1);
let ToolResult::Result {
data,
result_for_assistant,
..
} = &results[0]
else {
panic!("steering must return a normal result");
};
assert_eq!(data["output"], "partial");
assert_eq!(data["session_id"], 42);
assert!(data["exit_code"].is_null());
assert!(data["completion"].is_null());
let assistant = result_for_assistant.as_deref().unwrap();
if steered {
assert_eq!(data["wait_end_reason"], "steered");
assert!(assistant.contains("user steering arrived"));
assert!(assistant.contains("do not launch the command again"));
} else {
assert!(data.get("wait_end_reason").is_none());
assert!(!assistant.contains("user steering arrived"));
}
let restored: serde_json::Value =
serde_json::from_str(&serde_json::to_string(data).unwrap()).unwrap();
assert_eq!(&restored, data);
}
}
}
}
Loading
Loading