Skip to content

Commit 2e97e51

Browse files
committed
feat(exec): Add round-injection yielding
Let ExecCommand yield its initial output wait when user steering arrives. Keep local and SSH processes running and return their session IDs for continuation through WriteStdin. Preserve output cursors, process completion, and legacy result payloads. Cover port routing, streaming, process survival, and compatibility.
1 parent 76bc00e commit 2e97e51

17 files changed

Lines changed: 663 additions & 24 deletions

File tree

‎src/crates/assembly/core/AGENTS.md‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -211,17 +211,18 @@ Narrower local guides already exist for some subtrees:
211211

212212
## Verification
213213

214-
For WriteStdin steering, port routing, streaming and legacy result compatibility:
214+
For ExecCommand/WriteStdin steering, port routing, streaming and legacy result compatibility:
215215

216216
```bash
217-
cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git --lib agentic::tools::implementations::exec_command::stdin::
217+
cargo test --locked -p openbitfun-core --no-default-features --features agent-runtime,git --lib agentic::tools::implementations::exec_command::
218218
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
219219
```
220220

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

227228
For desktop card admission, per-turn Peer origin, recovery context and subagent

‎src/crates/assembly/core/src/agentic/tools/implementations/exec_command/command.rs‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -586,6 +586,7 @@ impl ExecCommandTool {
586586
tty,
587587
yield_time_ms: Some(yield_time_ms),
588588
max_output_chars: None,
589+
wait_interrupt: context.round_injection_preemption_token().cloned(),
589590
lifecycle_sink: Self::start_remote_lifecycle_bridge(context, self.name()),
590591
output_sink: output_capture_tx,
591592
};
@@ -632,7 +633,7 @@ impl ExecCommandTool {
632633
}
633634
}
634635

635-
let data = exec_command_result_value(ExecCommandResultData {
636+
let mut data = exec_command_result_value(ExecCommandResultData {
636637
fields: ExecCommandResultFields {
637638
chunk_id: response.chunk_id,
638639
wall_time_seconds: response.wall_time_seconds,
@@ -647,6 +648,9 @@ impl ExecCommandTool {
647648
tty,
648649
shell: Self::remote_shell_metadata(&workdir, &shell, env_snapshot.is_some()),
649650
});
651+
if response.wait_interrupted {
652+
data["wait_end_reason"] = json!("steered");
653+
}
650654
let result_for_assistant = Self::response_for_assistant(&data);
651655

652656
Ok(vec![ToolResult::Result {
@@ -687,6 +691,7 @@ TTY modes:
687691
688692
Waiting and continuation:
689693
- yield_time_ms waits for output until the process exits or the deadline is reached. It does not stop the process.
694+
- 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.
690695
- If the process is still running after `yield_time_ms`, the result includes a numeric session_id.
691696
- Use WriteStdin to poll for more output or send input to tty=true sessions, and ExecControl to interrupt or kill it.
692697
@@ -742,6 +747,7 @@ Output:
742747
"output": {"type": "string"},
743748
"session_id": {"anyOf": [{"type": "integer"}, {"type": "null"}]},
744749
"exit_code": {"anyOf": [{"type": "integer"}, {"type": "null"}]},
750+
"wait_end_reason": {"type": "string", "enum": ["steered"]},
745751
"completion": {
746752
"anyOf": [
747753
{"type": "null"},
@@ -781,6 +787,10 @@ Output:
781787
true
782788
}
783789

790+
fn round_injection_yieldable(&self) -> bool {
791+
true
792+
}
793+
784794
async fn validate_input(
785795
&self,
786796
input: &Value,
@@ -887,6 +897,7 @@ Output:
887897
tty,
888898
yield_time_ms: Some(yield_time_ms),
889899
max_output_chars: None,
900+
wait_interrupt: context.round_injection_preemption_token().cloned(),
890901
lifecycle_sink: Self::start_local_lifecycle_bridge(context, self.name()),
891902
output_sink: output_capture_tx,
892903
};
@@ -933,7 +944,7 @@ Output:
933944
}
934945
}
935946

936-
let data = exec_command_result_value(ExecCommandResultData {
947+
let mut data = exec_command_result_value(ExecCommandResultData {
937948
fields: ExecCommandResultFields {
938949
chunk_id: response.chunk_id,
939950
wall_time_seconds: response.wall_time_seconds,
@@ -948,6 +959,9 @@ Output:
948959
tty,
949960
shell: Self::shell_metadata_value(&shell),
950961
});
962+
if response.wait_interrupted {
963+
data["wait_end_reason"] = json!("steered");
964+
}
951965
let result_for_assistant = Self::response_for_assistant(&data);
952966

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

1086-
fn local_tool_context(workspace: &Path) -> ToolUseContext {
1100+
pub(super) fn local_tool_context(workspace: &Path) -> ToolUseContext {
10871101
ToolUseContext {
10881102
tool_call_id: None,
10891103
agent_type: Some("Standard".to_string()),
@@ -1100,7 +1114,7 @@ mod tests {
11001114
}
11011115
}
11021116

1103-
fn remote_tool_context(root: &str) -> ToolUseContext {
1117+
pub(super) fn remote_tool_context(root: &str) -> ToolUseContext {
11041118
let session_identity =
11051119
workspace_session_identity(root, Some("conn-1"), Some("remote-host"))
11061120
.expect("remote session identity should build");
@@ -1468,3 +1482,7 @@ mod tests {
14681482
#[cfg(all(test, unix))]
14691483
#[path = "guard_tests.rs"]
14701484
mod guard_tests;
1485+
1486+
#[cfg(test)]
1487+
#[path = "command_steering_tests.rs"]
1488+
mod steering_tests;
Lines changed: 265 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,265 @@
1+
use super::tests::{local_tool_context, remote_tool_context};
2+
use super::*;
3+
use crate::agentic::tools::framework::ToolResult;
4+
use openbitfun_runtime_ports::*;
5+
use std::sync::atomic::{AtomicUsize, Ordering};
6+
use tokio_util::sync::CancellationToken;
7+
8+
#[derive(Debug)]
9+
struct ExecProbe {
10+
streaming: bool,
11+
calls: AtomicUsize,
12+
}
13+
14+
impl RuntimeServicePort for ExecProbe {
15+
fn capability(&self) -> RuntimeServiceCapability {
16+
RuntimeServiceCapability::Terminal
17+
}
18+
}
19+
20+
#[async_trait::async_trait]
21+
impl TerminalPort for ExecProbe {
22+
async fn exec_command(
23+
&self,
24+
request: TerminalExecCommandRequest,
25+
) -> PortResult<TerminalExecCommandResponse> {
26+
assert_eq!(self.streaming, false);
27+
assert!(request.tty);
28+
assert_eq!(request.yield_time_ms, Some(600_000));
29+
self.calls.fetch_add(1, Ordering::SeqCst);
30+
assert!(request.argv.last().unwrap().contains("echo steering-probe"));
31+
Ok(TerminalExecCommandResponse {
32+
chunk_id: "chunk".into(),
33+
wall_time_seconds: 0.01,
34+
output: "partial".into(),
35+
session_id: Some(42),
36+
exit_code: None,
37+
original_output_chars: 7,
38+
completion: None,
39+
wait_interrupted: request
40+
.wait_interrupt
41+
.as_ref()
42+
.is_some_and(CancellationToken::is_cancelled),
43+
})
44+
}
45+
async fn exec_command_streaming(
46+
&self,
47+
request: TerminalExecCommandRequest,
48+
sink: TerminalExecStreamingOutputSink,
49+
) -> PortResult<TerminalExecCommandResponse> {
50+
assert_eq!(self.streaming, true);
51+
assert!(request.tty);
52+
assert_eq!(request.yield_time_ms, Some(600_000));
53+
self.calls.fetch_add(1, Ordering::SeqCst);
54+
assert!(request.argv.last().unwrap().contains("echo steering-probe"));
55+
sink.send("partial".into()).await.unwrap();
56+
Ok(TerminalExecCommandResponse {
57+
chunk_id: "chunk".into(),
58+
wall_time_seconds: 0.01,
59+
output: "partial".into(),
60+
session_id: Some(42),
61+
exit_code: None,
62+
original_output_chars: 7,
63+
completion: None,
64+
wait_interrupted: request
65+
.wait_interrupt
66+
.as_ref()
67+
.is_some_and(CancellationToken::is_cancelled),
68+
})
69+
}
70+
async fn write_stdin(
71+
&self,
72+
_: TerminalWriteStdinRequest,
73+
) -> PortResult<TerminalExecCommandResponse> {
74+
panic!("initial wait must not replay input or control the process")
75+
}
76+
async fn write_stdin_streaming(
77+
&self,
78+
_: TerminalWriteStdinRequest,
79+
_: TerminalExecStreamingOutputSink,
80+
) -> PortResult<TerminalExecCommandResponse> {
81+
panic!("initial wait must not replay input or control the process")
82+
}
83+
async fn send_stdin(&self, _: TerminalSendStdinRequest) -> PortResult<()> {
84+
panic!("initial wait must not replay input or control the process")
85+
}
86+
async fn control_session(
87+
&self,
88+
_: TerminalExecControlRequest,
89+
) -> PortResult<TerminalExecCommandResponse> {
90+
panic!("initial wait must not replay input or control the process")
91+
}
92+
}
93+
94+
#[async_trait::async_trait]
95+
impl RemoteExecPort for ExecProbe {
96+
async fn exec_command_once(
97+
&self,
98+
_: RemoteExecOneShotCommandRequest,
99+
) -> PortResult<RemoteExecOneShotCommandResponse> {
100+
Ok(RemoteExecOneShotCommandResponse {
101+
stdout: "/bin/sh\n".into(),
102+
stderr: String::new(),
103+
exit_code: 0,
104+
interrupted: false,
105+
timed_out: false,
106+
})
107+
}
108+
async fn exec_command(
109+
&self,
110+
request: RemoteExecCommandRequest,
111+
) -> PortResult<RemoteExecCommandResponse> {
112+
if request.max_output_chars.is_some() {
113+
// Environment capture is a separate best-effort setup command.
114+
assert!(request.wait_interrupt.is_none());
115+
return Err(PortError::new(
116+
PortErrorKind::NotAvailable,
117+
"no environment snapshot",
118+
));
119+
}
120+
assert_eq!(self.streaming, false);
121+
assert!(request.tty);
122+
assert_eq!(request.yield_time_ms, Some(600_000));
123+
self.calls.fetch_add(1, Ordering::SeqCst);
124+
assert!(request.command.contains("echo steering-probe"));
125+
Ok(RemoteExecCommandResponse {
126+
chunk_id: "chunk".into(),
127+
wall_time_seconds: 0.01,
128+
output: "partial".into(),
129+
session_id: Some(42),
130+
exit_code: None,
131+
original_output_chars: 7,
132+
completion: None,
133+
wait_interrupted: request
134+
.wait_interrupt
135+
.as_ref()
136+
.is_some_and(CancellationToken::is_cancelled),
137+
})
138+
}
139+
async fn exec_command_streaming(
140+
&self,
141+
request: RemoteExecCommandRequest,
142+
sink: RemoteExecStreamingOutputSink,
143+
) -> PortResult<RemoteExecCommandResponse> {
144+
assert_eq!(self.streaming, true);
145+
assert!(request.tty);
146+
assert_eq!(request.yield_time_ms, Some(600_000));
147+
self.calls.fetch_add(1, Ordering::SeqCst);
148+
assert!(request.command.contains("echo steering-probe"));
149+
sink.send("partial".into()).await.unwrap();
150+
Ok(RemoteExecCommandResponse {
151+
chunk_id: "chunk".into(),
152+
wall_time_seconds: 0.01,
153+
output: "partial".into(),
154+
session_id: Some(42),
155+
exit_code: None,
156+
original_output_chars: 7,
157+
completion: None,
158+
wait_interrupted: request
159+
.wait_interrupt
160+
.as_ref()
161+
.is_some_and(CancellationToken::is_cancelled),
162+
})
163+
}
164+
async fn write_stdin(
165+
&self,
166+
_: RemoteWriteStdinRequest,
167+
) -> PortResult<RemoteExecCommandResponse> {
168+
panic!("initial wait must not replay input or control the process")
169+
}
170+
async fn write_stdin_streaming(
171+
&self,
172+
_: RemoteWriteStdinRequest,
173+
_: RemoteExecStreamingOutputSink,
174+
) -> PortResult<RemoteExecCommandResponse> {
175+
panic!("initial wait must not replay input or control the process")
176+
}
177+
async fn send_stdin(&self, _: RemoteSendStdinRequest) -> PortResult<()> {
178+
panic!("initial wait must not replay input or control the process")
179+
}
180+
async fn control_session(
181+
&self,
182+
_: RemoteExecControlRequest,
183+
) -> PortResult<RemoteExecCommandResponse> {
184+
panic!("initial wait must not replay input or control the process")
185+
}
186+
}
187+
188+
#[test]
189+
fn exec_command_owns_timeout_and_yields_to_round_injection() {
190+
let tool = ExecCommandTool::new();
191+
assert!(tool.manages_own_execution_timeout());
192+
assert!(tool.round_injection_yieldable());
193+
assert!(tool.is_concurrency_safe(None));
194+
assert!(tool.output_schema()["properties"]
195+
.get("wait_end_reason")
196+
.is_some());
197+
assert!(!tool.output_schema()["required"]
198+
.as_array()
199+
.unwrap()
200+
.contains(&json!("wait_end_reason")));
201+
}
202+
203+
#[tokio::test]
204+
async fn exec_command_steering_reaches_both_ports_and_preserves_legacy_results() {
205+
let workspace = tempfile::tempdir().unwrap();
206+
for remote in [false, true] {
207+
for streaming in [false, true] {
208+
for steered in [false, true] {
209+
let mut context = if remote {
210+
remote_tool_context("/home/me/project")
211+
} else {
212+
local_tool_context(workspace.path())
213+
};
214+
context.tool_call_id =
215+
streaming.then(|| format!("exec-steering-{remote}-{steered}"));
216+
let probe = Arc::new(ExecProbe {
217+
streaming,
218+
calls: AtomicUsize::new(0),
219+
});
220+
let token = CancellationToken::new();
221+
token.cancel();
222+
context.runtime_handles = context
223+
.runtime_handles
224+
.with_round_injection_preemption_token(steered.then_some(token))
225+
.with_terminal_port(Some(probe.clone()))
226+
.with_remote_exec_port(Some(probe.clone()));
227+
let tool = ExecCommandTool::new();
228+
let results = tool
229+
.call_impl(
230+
&json!({
231+
"cmd":"echo steering-probe", "tty":true, "yield_time_ms":600_000,
232+
}),
233+
&context,
234+
)
235+
.await
236+
.unwrap();
237+
assert_eq!(probe.calls.load(Ordering::SeqCst), 1);
238+
let ToolResult::Result {
239+
data,
240+
result_for_assistant,
241+
..
242+
} = &results[0]
243+
else {
244+
panic!("steering must return a normal result");
245+
};
246+
assert_eq!(data["output"], "partial");
247+
assert_eq!(data["session_id"], 42);
248+
assert!(data["exit_code"].is_null());
249+
assert!(data["completion"].is_null());
250+
let assistant = result_for_assistant.as_deref().unwrap();
251+
if steered {
252+
assert_eq!(data["wait_end_reason"], "steered");
253+
assert!(assistant.contains("user steering arrived"));
254+
assert!(assistant.contains("do not launch the command again"));
255+
} else {
256+
assert!(data.get("wait_end_reason").is_none());
257+
assert!(!assistant.contains("user steering arrived"));
258+
}
259+
let restored: serde_json::Value =
260+
serde_json::from_str(&serde_json::to_string(data).unwrap()).unwrap();
261+
assert_eq!(&restored, data);
262+
}
263+
}
264+
}
265+
}

0 commit comments

Comments
 (0)