-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecutor.rs
More file actions
326 lines (293 loc) · 10 KB
/
executor.rs
File metadata and controls
326 lines (293 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};
use anyhow::{Context, Result, bail};
use dispatch_core::{
BackendInvocation, DispatchStore, EventKind, SessionCaptureStrategy, SessionLocator,
SessionRef, TaskStatus, list_pending_questions,
};
use serde::Serialize;
use serde_json::Value;
use uuid::Uuid;
#[derive(Debug, Serialize)]
pub struct ExecutionSummary {
pub task_id: Uuid,
pub status: String,
pub exit_code: Option<i32>,
pub session: Option<SessionRef>,
pub stdout_path: PathBuf,
pub stderr_path: PathBuf,
}
pub fn execute_plan(
store: &DispatchStore,
task_id: Uuid,
invocation: &BackendInvocation,
capture: &SessionCaptureStrategy,
) -> Result<ExecutionSummary> {
let task = store.load_task(task_id)?;
let attempt = task.checkpoint.restart_count;
let stdout_path = task
.artifacts
.outputs_dir
.join(format!("attempt-{attempt:03}.stdout.log"));
let stderr_path = task
.artifacts
.outputs_dir
.join(format!("attempt-{attempt:03}.stderr.log"));
store.append_event(
task_id,
EventKind::InvocationStarted,
format!(
"running `{}` in {}",
invocation.program,
invocation.cwd.display()
),
)?;
let output = run_command(invocation).with_context(|| {
format!(
"failed to execute backend command `{}` in {}",
invocation.program,
invocation.cwd.display()
)
})?;
let stdout_text = String::from_utf8_lossy(&output.stdout).into_owned();
let stderr_text = String::from_utf8_lossy(&output.stderr).into_owned();
fs::write(&stdout_path, &stdout_text)
.with_context(|| format!("write stdout log to {}", stdout_path.display()))?;
fs::write(&stderr_path, &stderr_text)
.with_context(|| format!("write stderr log to {}", stderr_path.display()))?;
store.append_event(
task_id,
EventKind::OutputSaved,
format!(
"saved stdout to {} and stderr to {}",
stdout_path.display(),
stderr_path.display()
),
)?;
let session = resolve_session(capture, &stdout_text, &task.workspace_root, None)?;
let success = output.status.success();
let pending_questions = list_pending_questions(&task.artifacts.mailbox_dir)?;
let completion_marker = task.artifacts.mailbox_dir.join(".done");
store.update_task(task_id, |task| {
task.session = session.clone().or_else(|| task.session.clone());
task.checkpoint.last_error = if success {
None
} else {
Some(render_exit_status(&output.status))
};
task.status = if !pending_questions.is_empty() {
TaskStatus::AwaitingUser
} else if success && completion_marker.exists() {
TaskStatus::Completed
} else if success {
TaskStatus::Running
} else {
TaskStatus::Failed
};
})?;
store.append_event(
task_id,
EventKind::InvocationFinished,
format!("command exited with {}", render_exit_status(&output.status)),
)?;
if success {
store.append_event(task_id, EventKind::Completed, "task execution completed")?;
} else {
store.append_event(task_id, EventKind::Failed, "task execution failed")?;
}
Ok(ExecutionSummary {
task_id,
status: if success { "completed" } else { "failed" }.into(),
exit_code: output.status.code(),
session,
stdout_path,
stderr_path,
})
}
fn run_command(invocation: &BackendInvocation) -> Result<std::process::Output> {
let mut command = Command::new(&invocation.program);
command
.args(&invocation.args)
.current_dir(&invocation.cwd)
.stdin(if invocation.stdin.is_some() {
Stdio::piped()
} else {
Stdio::null()
})
.stdout(Stdio::piped())
.stderr(Stdio::piped());
for (key, value) in &invocation.env {
command.env(key, value);
}
let mut child = command.spawn()?;
if let Some(stdin) = &invocation.stdin {
use std::io::Write;
let mut handle = child
.stdin
.take()
.context("failed to acquire child stdin handle")?;
handle.write_all(stdin.as_bytes())?;
}
Ok(child.wait_with_output()?)
}
fn resolve_session(
capture: &SessionCaptureStrategy,
stdout_text: &str,
workspace_root: &Path,
session_storage: Option<&Path>,
) -> Result<Option<SessionRef>> {
match capture {
SessionCaptureStrategy::None => Ok(None),
SessionCaptureStrategy::Preallocated(session) => Ok(Some(session.clone())),
SessionCaptureStrategy::StdoutJson { field } => {
let value = extract_json_field(stdout_text, field);
match value {
Some(Value::String(id)) => Ok(Some(SessionRef {
backend: dispatch_core::BackendKind::Codex,
locator: SessionLocator::Id(id),
workspace_root: workspace_root.to_path_buf(),
session_storage: session_storage.map(Path::to_path_buf),
})),
Some(other) => bail!("session field `{field}` was not a string: {other}"),
None => Ok(None),
}
}
}
}
fn extract_json_field(stdout_text: &str, field: &str) -> Option<Value> {
for line in stdout_text.lines() {
let trimmed = line.trim();
if trimmed.is_empty() {
continue;
}
if let Ok(value) = serde_json::from_str::<Value>(trimmed) {
if let Some(found) = find_field_recursive(&value, field) {
return Some(found.clone());
}
}
}
None
}
fn find_field_recursive<'a>(value: &'a Value, field: &str) -> Option<&'a Value> {
match value {
Value::Object(map) => {
if let Some(found) = map.get(field) {
return Some(found);
}
for nested in map.values() {
if let Some(found) = find_field_recursive(nested, field) {
return Some(found);
}
}
None
}
Value::Array(items) => items
.iter()
.find_map(|item| find_field_recursive(item, field)),
_ => None,
}
}
fn render_exit_status(status: &ExitStatus) -> String {
match status.code() {
Some(code) => format!("exit code {code}"),
None => "terminated by signal".into(),
}
}
#[cfg(test)]
mod tests {
use std::env;
use std::fs;
use dispatch_core::{
BackendInvocation, BackendKind, DispatchStore, ExecutionMode, SessionCaptureStrategy,
TaskDraft, TaskMode, TaskSource, TaskStatus,
};
use serde_json::json;
use uuid::Uuid;
use super::{execute_plan, extract_json_field, find_field_recursive, resolve_session};
#[test]
fn extracts_nested_session_field_from_jsonl() {
let stdout = r#"{"event":"start"}
{"result":{"session_id":"abc-123","message":"done"}}"#;
let field = extract_json_field(stdout, "session_id").unwrap();
assert_eq!(field, json!("abc-123"));
}
#[test]
fn finds_recursive_fields() {
let value = json!({"a": [{"b": {"session_id": "id-1"}}]});
let found = find_field_recursive(&value, "session_id").unwrap();
assert_eq!(found, &json!("id-1"));
}
#[test]
fn resolves_stdout_json_session() {
let temp = tempfile::tempdir().unwrap();
let workspace = temp.path().join("workspace");
let sessions = temp.path().join("sessions");
let session = resolve_session(
&SessionCaptureStrategy::StdoutJson {
field: "session_id".into(),
},
"{\"session_id\":\"sess-1\"}",
workspace.as_path(),
Some(sessions.as_path()),
)
.unwrap()
.unwrap();
assert!(matches!(session.backend, BackendKind::Codex));
assert!(matches!(
session.locator,
dispatch_core::SessionLocator::Id(_)
));
}
#[test]
fn executes_and_persists_output_artifacts() {
let root = env::temp_dir().join(format!("dispatch-exec-test-{}", Uuid::new_v4()));
let workspace = root.join("workspace");
fs::create_dir_all(&workspace).unwrap();
let store = DispatchStore::new(&root);
let task = store
.create_task(TaskDraft {
title: "Executor smoke".into(),
prompt: "test".into(),
task_mode: TaskMode::Plan,
task_source: TaskSource::InlinePrompt,
backend: BackendKind::Codex,
model: None,
execution_mode: ExecutionMode::Auto,
plan_body: None,
workspace_root: workspace.clone(),
})
.unwrap();
let invocation = BackendInvocation {
program: "/bin/sh".into(),
args: vec![
"-c".into(),
format!(
"printf '{{\"session_id\":\"sess-local\"}}\\n' && : > '{}' && cat > '{}' <<'OUT'\ncompleted\nOUT",
task.artifacts.mailbox_dir.join(".done").display(),
task.artifacts.output_file.display(),
),
],
cwd: workspace,
env: Default::default(),
stdin: None,
};
let summary = execute_plan(
&store,
task.id,
&invocation,
&SessionCaptureStrategy::StdoutJson {
field: "session_id".into(),
},
)
.unwrap();
assert_eq!(summary.status, "completed");
assert!(summary.stdout_path.exists());
assert!(summary.stderr_path.exists());
let updated = store.load_task(task.id).unwrap();
assert!(matches!(updated.status, TaskStatus::Completed));
assert!(updated.session.is_some());
assert!(updated.artifacts.output_file.exists());
fs::remove_dir_all(root).unwrap();
}
}