-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathexecute.rs
More file actions
244 lines (223 loc) · 8.96 KB
/
Copy pathexecute.rs
File metadata and controls
244 lines (223 loc) · 8.96 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
// Copyright (c) 2026 vectorless developers
// SPDX-License-Identifier: Apache-2.0
//! Command execution — dispatch parsed Command to tool functions.
use tracing::{info, warn};
use crate::llm::LlmClient;
use super::super::command::{Command, parse_command};
use super::super::config::{DocContext, Step};
use super::super::events::EventEmitter;
use super::super::prompts::{check_sufficiency, parse_sufficiency_response};
use super::super::state::WorkerState;
use super::super::tools::worker as tools;
/// Execute a single parsed command, mutating state.
///
/// Returns a `Step` indicating whether to continue or stop.
pub async fn execute_command(
command: &Command,
ctx: &DocContext<'_>,
state: &mut WorkerState,
query: &str,
llm: &LlmClient,
llm_calls: &mut u32,
emitter: &EventEmitter,
) -> Step {
info!(
doc = ctx.doc_name,
command = ?command,
"Executing tool"
);
match command {
Command::Ls => {
let result = tools::ls(ctx, state);
info!(doc = ctx.doc_name, feedback = %truncate_log(&result.feedback), "ls result");
state.set_feedback(result.feedback);
Step::Continue
}
Command::Cd { target } => {
let result = tools::cd(target, ctx, state);
info!(doc = ctx.doc_name, target, feedback = %truncate_log(&result.feedback), "cd result");
state.set_feedback(result.feedback);
Step::Continue
}
Command::CdUp => {
let result = tools::cd_up(ctx, state);
info!(doc = ctx.doc_name, feedback = %truncate_log(&result.feedback), "cd_up result");
state.set_feedback(result.feedback);
Step::Continue
}
Command::Cat { target } => {
let evidence_before = state.evidence.len();
let result = tools::cat(target, ctx, state);
info!(doc = ctx.doc_name, target, feedback = %truncate_log(&result.feedback), "cat result");
state.set_feedback(result.feedback);
if state.evidence.len() > evidence_before {
if let Some(ev) = state.evidence.last() {
info!(
doc = ctx.doc_name,
node = %ev.node_title,
path = %ev.source_path,
len = ev.content.len(),
total = state.evidence.len(),
"Evidence collected"
);
emitter.emit_evidence(
ctx.doc_name,
&ev.node_title,
&ev.source_path,
ev.content.len(),
state.evidence.len(),
);
}
}
Step::Continue
}
Command::Find { keyword } => {
let feedback = match ctx.find(keyword) {
Some(hit) => {
let mut entries = hit.entries.clone();
entries.sort_by(|a, b| {
b.weight
.partial_cmp(&a.weight)
.unwrap_or(std::cmp::Ordering::Equal)
});
let mut seen_nodes = std::collections::HashSet::new();
let mut output = format!("Results for '{}':\n", keyword);
for entry in &entries {
if !seen_nodes.insert(entry.node_id) {
continue;
}
let title = ctx.node_title(entry.node_id).unwrap_or("unknown");
let summary = ctx
.nav_entry(entry.node_id)
.map(|e| e.overview.as_str())
.unwrap_or("");
output.push_str(&format!(
" - {} (depth {}, weight {:.2})",
title, entry.depth, entry.weight
));
if !summary.is_empty() {
output.push_str(&format!(" — {}", summary));
}
output.push('\n');
}
output
}
None => format!("No results for '{}'", keyword),
};
info!(doc = ctx.doc_name, keyword, feedback = %truncate_log(&feedback), "find result");
state.set_feedback(feedback);
Step::Continue
}
Command::Pwd => {
let result = tools::pwd(state);
state.set_feedback(result.feedback);
Step::Continue
}
Command::Check => {
let evidence_summary = state.evidence_summary();
let (system, user) = check_sufficiency(query, &evidence_summary);
info!(
doc = ctx.doc_name,
system = %system,
user = %user,
"Check prompt"
);
match llm.complete(&system, &user).await {
Ok(response) => {
*llm_calls += 1;
state.check_count += 1;
let sufficient = parse_sufficiency_response(&response);
info!(
doc = ctx.doc_name,
sufficient,
evidence = state.evidence.len(),
response = %response,
"Sufficiency check"
);
emitter.emit_worker_sufficiency_check(
ctx.doc_name,
sufficient,
state.evidence.len(),
None,
);
if sufficient {
state.last_feedback =
"Evidence is sufficient. Use done to finish.".to_string();
Step::Done
} else {
let reason = response
.trim()
.strip_prefix("INSUFFICIENT")
.unwrap_or(response.trim())
.trim()
.trim_start_matches(|c: char| c == '-' || c == ' ');
if !reason.is_empty() {
state.missing_info = reason.to_string();
}
state.set_feedback(format!(
"Evidence not yet sufficient: {}",
response.trim()
));
Step::Continue
}
}
Err(e) => {
warn!(error = %e, "Check LLM call failed");
state.last_feedback = "Could not evaluate sufficiency.".to_string();
Step::Continue
}
}
}
Command::Done => {
state.last_feedback = "Navigation complete.".to_string();
Step::Done
}
Command::Grep { pattern } => {
let result = tools::grep(pattern, ctx, state);
info!(doc = ctx.doc_name, pattern, feedback = %truncate_log(&result.feedback), "grep result");
state.set_feedback(result.feedback);
Step::Continue
}
Command::Head { target, lines } => {
let result = tools::head(target, *lines, ctx, state);
info!(doc = ctx.doc_name, target, lines, feedback = %truncate_log(&result.feedback), "head result");
state.set_feedback(result.feedback);
Step::Continue
}
Command::FindTree { pattern } => {
let result = tools::find_tree(pattern, ctx);
info!(doc = ctx.doc_name, pattern, feedback = %truncate_log(&result.feedback), "find_tree result");
state.set_feedback(result.feedback);
Step::Continue
}
Command::Wc { target } => {
let result = tools::wc(target, ctx, state);
info!(doc = ctx.doc_name, target, feedback = %truncate_log(&result.feedback), "wc result");
state.set_feedback(result.feedback);
Step::Continue
}
}
}
/// Truncate feedback for log output — keep first 300 chars to avoid noisy logs.
fn truncate_log(s: &str) -> std::borrow::Cow<'_, str> {
const MAX: usize = 300;
if s.len() <= MAX {
std::borrow::Cow::Borrowed(s)
} else {
std::borrow::Cow::Owned(format!(
"{}...(truncated, {} chars total)",
&s[..MAX],
s.len()
))
}
}
/// Parse the LLM output and detect parse failures.
///
/// Returns `(command, is_parse_failure)`.
pub fn parse_and_detect_failure(llm_output: &str) -> (Command, bool) {
let command = parse_command(llm_output);
let trimmed = llm_output.trim();
let is_parse_failure =
matches!(command, Command::Ls) && !trimmed.starts_with("ls") && !trimmed.is_empty();
(command, is_parse_failure)
}