blunderbuss 0.1.2

The non-toxic LLM coding harness. The major LLM coding harnesses are dark patterns all the way down. Blunderbuss is designed as if your safety and cognition actually matter.
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use std::collections::HashMap;
use anyhow::Context;
use utils::OutputExt;

mod tools;
mod utils;
mod parser;

type JsonResult = Result<serde_json::Value, String>;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
	// tracing_subscriber::fmt()
	// 	.with_env_filter(EnvFilter::new("genai=debug"))
	// 	// .with_max_level(tracing::Level::DEBUG)
	// 	.init();

	tokio::select! {
		result = tokio::signal::ctrl_c() => {
			println!("ctrl+c received, popping the temp git checkpoint commit if there is one");
			let _ = hard_reset_and_pop_checkpoint_commit().await;
			result?
		},
		result = chat_loop() => {
			match result {
				Ok(()) => {
					// nothing to do in this case, everything succeeded, let's go home
				},
				Err(err) => {
					println!("some error encountered, popping the temp git checkpoint commit if there is one");
					let _ = hard_reset_and_pop_checkpoint_commit().await;
					return Err(err);
				},
			}
		},
	}

	Ok(())
}

#[derive(Debug)]
struct ChatParams {
	model: String,
	maxturns: usize,
	min_retry_delay: u64,
	max_retry_delay: u64,
	max_retry_times: usize,
	shell_tools: HashMap<String, tools::ShellTool>,
	check_command: Option<String>,
	ready_command: Option<String>,
	path_env: utils::PathEnv,
}

async fn create_new_chat(
	log_writer: &LogWriter,
) -> anyhow::Result<(ChatParams, genai::chat::ChatRequest, genai::Client)> {
	let UserConfig {
		default_model, default_maxturns, default_min_retry_delay, default_max_retry_delay, default_max_retry_times,
		tools: default_tools, api_keys,
	} = try_blunderbuss_config().await?;
	let instructions = tokio::fs::read_to_string("blunderbuss.local.md").await
		// TODO allow piping stdin at some point
		.map_err(|e| anyhow::anyhow!("couldn't read the blunderbuss.local.md file, which is the whole way blunderbuss works!: {e}"))?;

	let (
		parser::RawParams {
			tools: instruction_tools, model, maxturns, min_retry_delay, max_retry_delay, max_retry_times,
			allow: _, disallow: _, check: check_command, ready: ready_command,
		},
		text,
	) = parser::parse_instructions(&instructions)
		.map_err(|e| anyhow::anyhow!(e))?;

	let model = model
		.or(default_model)
		.ok_or_else(|| anyhow::anyhow!("you don't have a model specified! you have to either provide one using the `model` frontmatter param in blunderbuss.local.md or `default_model` in ~/.blunderbuss.config.yml"))?;

	const DEFAULT_MAXTURNS: usize = 100;
	let maxturns = maxturns
		.or(default_maxturns)
		.unwrap_or(DEFAULT_MAXTURNS);

	const DEFAULT_MAX_TIMES: usize = 10;
  let max_retry_times = max_retry_times
  	.or(default_max_retry_times)
  	.unwrap_or(DEFAULT_MAX_TIMES);
	const DEFAULT_MIN_DELAY: u64 = 5;
	let min_retry_delay = min_retry_delay
		.or(default_min_retry_delay)
		.unwrap_or(DEFAULT_MIN_DELAY);
	const DEFAULT_MAX_DELAY: u64 = 60;
	let max_retry_delay = max_retry_delay
		.or(default_max_retry_delay)
		.unwrap_or(DEFAULT_MAX_DELAY);

	// TODO add allow and disallow
	let path_env = utils::PathEnv::new()?;

	let (shell_tools, chat_shell_tools) = default_tools.unwrap_or_default().into_iter().chain(instruction_tools.unwrap_or_default().into_iter())
		.map(|m| tools::tool_general_shell(m))
		.collect::<Result<(HashMap<_, _>, Vec<_>), _>>()
		.map_err(|e| anyhow::anyhow!(e))?;

	let mut all_tools = [
		// tool_tree(),
		tools::tool_grep(),
		tools::tool_read_file(),
		tools::tool_write_file(),
		tools::tool_replace_span(),
		tools::tool_replace_section(),
	].into_iter()
		.chain(chat_shell_tools)
		.collect::<Vec<_>>();

	if let Some(check_command) = &check_command {
		all_tools.push(tools::tool_check_command(check_command));
	}

	let mut chat_req = genai::chat::ChatRequest::default()
		.with_system(include_str!("./system.md"))
		.with_tools(all_tools);

	log_writer.log_serde(chat_req.tools.as_deref().unwrap_or_default());

	let msg = genai::chat::ChatMessage::user(text);
	log_writer.log_serde(&msg);
	chat_req = chat_req.append_message(msg);

	println!("using model {model}");
	println!("using maxturns {maxturns}");
	println!("using max_retry_times {max_retry_times}");
	println!("using min_retry_delay {min_retry_delay}");
	println!("using max_retry_delay {max_retry_delay}");
	for shell_tool in shell_tools.keys() {
		println!("using shell tool: {shell_tool}");
	}
	if let Some(check_command) = &check_command {
		println!("using check command {check_command}");
	}
	if let Some(ready_command) = &ready_command {
		println!("using ready command {ready_command}");
	}

	let auth_resolver = genai::resolver::AuthResolver::from_resolver_fn(move |model_iden: genai::ModelIden| {
		let genai::ModelIden { adapter_kind, .. } = model_iden;

		let api_key = api_keys.zip(adapter_kind.default_key_env_name())
			.and_then(|(api_keys, k)| api_keys.get(k).map(String::to_owned));

		match api_key {
			Some(key) => Ok(Some(genai::resolver::AuthData::from_single(key))),
			// fall back to genai's default
			None => Ok(None),
		}
	});
	let client = genai::Client::builder()
		.with_auth_resolver(auth_resolver)
		.build()?;

	let instructions = ChatParams {
		 model, maxturns, max_retry_times, min_retry_delay, max_retry_delay,
		 shell_tools, check_command, path_env, ready_command,
	};
	Ok((instructions, chat_req, client))
}

#[derive(Debug, Default, serde::Deserialize)]
struct UserConfig {
	default_model: Option<String>,
	default_maxturns: Option<usize>,
	default_min_retry_delay: Option<u64>,
	default_max_retry_delay: Option<u64>,
	default_max_retry_times: Option<usize>,
	tools: Option<Vec<String>>,
	api_keys: Option<HashMap<String, String>>,
}

async fn try_blunderbuss_config() -> anyhow::Result<UserConfig> {
	let blunderbuss_config_path = std::env::home_dir().unwrap_or("~/".into()).join(".blunderbuss.config.yml");
	if !tokio::fs::try_exists(&blunderbuss_config_path).await.unwrap_or(false) {
		return Ok(UserConfig::default())
	}

	let file_contents = tokio::fs::read_to_string(blunderbuss_config_path).await
		.context("wasn't able to read .blunderbuss.config.yml even though it exists?")?;

	yaml_serde::from_str(&file_contents)
		.context("wasn't able to parse .blunderbuss.config.yml")
}

async fn chat_loop() -> anyhow::Result<()> {
	let log_writer = LogWriter::spawn_new().await?;

	let (mut p, mut chat_req, mut client) = create_new_chat(&log_writer).await?;

	let mut turn = 0;
	let mut ran_out_of_turns = false;
	push_checkpoint_commit().await?;
	loop {
		if turn >= p.maxturns {
			ran_out_of_turns = true;
			break
		}

		// execute this turn
		use backon::Retryable;
		let chat_res = (|| async { client.exec_chat(&p.model, chat_req.clone(), None).await })
			.retry(
				backon::ExponentialBuilder::default()
					.with_min_delay(std::time::Duration::from_secs(p.min_retry_delay))
					.with_max_delay(std::time::Duration::from_secs(p.max_retry_delay))
					.with_max_times(p.max_retry_times)
			)
			.when(genai_error_is_retryable)
			.notify(|err, dur| {
				log_writer.log_msg(format!("error, retrying after {dur:?}: {:?}", err).into_bytes());
				println!("error with status {:?}, retrying after {dur:?}", err.status());
			})
			.await?;

		let genai::chat::ChatResponse { content, reasoning_content, .. } = chat_res;

		let tool_calls = content.tool_calls();
		let mut tool_responses = Vec::with_capacity(tool_calls.len());
		// we execute the tool calls sequentially for now to avoid possible headaches with them interfering
		// something fancy in the future would be to divide up the tools by the things they could effect (files, whatever)
		// however that's easier said than done, since the tools the user specifies could mess things up
		for tool_call in tool_calls.into_iter() {
			let output = tools::run_tool(&tool_call, p.check_command.as_deref(), &p.shell_tools, &p.path_env).await;

			let tool_response = genai::chat::ToolResponse::from_tool_call(&tool_call, output.to_string());
			tool_responses.push(tool_response);
		}
		// append this round to the history
		let msg = genai::chat::ChatMessage::assistant(content).with_reasoning_content(reasoning_content);
		log_writer.log_serde(&msg);
		chat_req = chat_req.append_message(msg);

		// the llm is still doing things, so keep at it
		if !tool_responses.is_empty() {
			let msg: genai::chat::ChatMessage = tool_responses.into();
			log_writer.log_serde(&msg);
			chat_req = chat_req.append_message(msg);
			turn += 1;
			continue;
		}

		// there aren't any more calls (and therefore any more responses), the llm says its done
		if let Some(check_command) = &p.check_command {
			println!("blunderbuss says it's finished, running your check command {check_command}");
			let output = tokio::process::Command::new("sh").arg("-c").arg(check_command)
				.output().await.with_context(|| format!("wasn't able to call sh -c '{check_command}'"))?;

			if !output.status.success() {
				let stdout = String::from_utf8_lossy(&output.stdout);
				let stderr = String::from_utf8_lossy(&output.stderr);
				println!("check command {check_command} failed! sending the output back to blunderbuss to try again");

				let check_command_feedback = format!("the check command {check_command} failed.\nstdout:\n{stdout}\n\n\nstderr:\n{stderr}");
				let msg = genai::chat::ChatMessage::user(check_command_feedback);
				log_writer.log_serde(&msg);
				chat_req = chat_req.append_message(msg);
				turn += 1;
				continue;
			}
			println!("check command {check_command} succeeded!");
		}

		if let Some(ready_command) = &p.ready_command {
			println!("running your ready command {ready_command}");
			tokio::process::Command::new("sh").arg("-c").arg(ready_command)
				.output().await.with_context(|| format!("wasn't able to call sh -c '{ready_command}'"))?;
		}

		const LOOKS_GOOD: &'static str = "looks good (will remove the blunderbuss checkpoint commit and mix blunderbuss's changes in with yours)";
		const NOPE_REVERT: &'static str = "nope revert (will *hard* git reset and remove the blunderbuss checkpoint commit)";
		const TRY_AGAIN_ANEW: &'static str = "try again (will *hard* git reset and start a new chat from blunderbuss.local.md)";
		// const TRY_AGAIN_FROM_HERE: &'static str = "try again (continue from this existing context)";
		// let options: Vec<&str> = vec![LOOKS_GOOD, NOPE_REVERT, TRY_AGAIN_ANEW, TRY_AGAIN_FROM_HERE];
		let options: Vec<&str> = vec![LOOKS_GOOD, NOPE_REVERT, TRY_AGAIN_ANEW];
		let page_size = options.len();

		let choice = inquire::Select::new("How's that?", options)
			.with_page_size(page_size)
			.without_help_message()
			.prompt().context("there was some issue with the inquire library?")?;

		match choice {
			LOOKS_GOOD => {
				// pop the temp git commit
				pop_checkpoint_commit().await?;
				break;
			},
			NOPE_REVERT => {
				// revert and hard reset
				hard_reset_and_pop_checkpoint_commit().await?;
				// stop trying, the user doesn't want to bother
				break;
			},
			TRY_AGAIN_ANEW => {
				// this tries again and rereads blunderbuss.local.md
				hard_reset_and_pop_checkpoint_commit().await?;
				(p, chat_req, client) = create_new_chat(&log_writer).await?;
				turn = 0;
				continue;
			},
			// TRY_AGAIN_FROM_HERE => {
			// 	// this tries again with the context we already have
			// 	hard_reset_and_pop_checkpoint_commit().await?;
			// 	let msg = genai::chat::ChatMessage::user(
			// 		"I'm unsatisfied with that attempt. everything has been reverted, try again",
			// 	);
			// 	log_writer.log_serde(&msg);
			// 	chat_req = chat_req.append_message(msg);
			// 	turn = 0;
			// 	continue;
			// },
			unknown => { return Err(anyhow::anyhow!("how did you choose this? {unknown}")) }
		}
	}

	log_writer.finish().await;

	if ran_out_of_turns {
		return Err(anyhow::anyhow!("blunderbuss failed to finish within the max turns: {}", p.maxturns))
	}

	Ok(())
}

#[derive(Debug)]
struct LogWriter {
	sender: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
	handle: tokio::task::JoinHandle<()>,
}

impl LogWriter {
	async fn spawn_new() -> anyhow::Result<LogWriter> {
		let path = "blunderbuss.output.local.yml";
		let mut file = tokio::fs::OpenOptions::new().create(true).truncate(true).write(true).open(path).await?;
		let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();

		let handle = tokio::spawn(async move {
			use tokio::io::AsyncWriteExt;
			while let Some(mut msg) = receiver.recv().await {
				msg.extend_from_slice(b"\n---\n\n");

				let _ = file.write_all(&msg).await
					.inspect_err(|e| eprintln!("failed to write to blunderbuss.output.local.yml: {e}"));
				let _ = file.flush().await
					.inspect_err(|e| eprintln!("failed to flush blunderbuss.output.local.yml: {e}"));
			}
		});

		Ok(LogWriter { sender, handle })
	}

	fn log_msg(&self, msg: Vec<u8>) {
		if let Err(e) = self.sender.send(msg) {
			eprintln!("failed to log chat message: {}", String::from_utf8_lossy(&e.0));
		}
	}

	fn log_serde(&self, msg: impl serde::Serialize) {
		let msg = match yaml_serde::to_string(&msg) {
			Err(e) => { eprintln!("failed to serialize: {}", e); return; },
			Ok(msg) => { msg.into_bytes() },
		};

		self.log_msg(msg);
	}

	async fn finish(self) {
		let LogWriter { sender, handle } = self;
		drop(sender);
		let _ = handle.await;
	}
}

/// push the blunderbuss checkpoint commit if there are existing uncommitted changes
/// this is to allow the user to cleanly separate blunderbuss's changes from their existing ones
async fn push_checkpoint_commit() -> anyhow::Result<()> {
	// the if statement short circuits with a successful status code if there are no changes
	// if the git commit sequence happens the status code of that is passed through
	tokio::process::Command::new("sh").arg("-c")
		.arg(r#"if [ -n "$(git status --porcelain)" ]; then git add -A; git commit --no-verify --no-gpg-sign -m '--blunderbuss-checkpoint--'; fi"#)
		.output().await?.demand_status_success("failed to push the temporary git checkpoint commit")?;

	Ok(())
}
/// get rid of the blunderbuss checkpoint commit so that the changes made by the llm are mixed in with the ones the user had previously
/// if there isn't a blunderbuss commit the status of the commit will be unsuccessful, but that's fine
async fn pop_checkpoint_commit() -> anyhow::Result<()> {
	tokio::process::Command::new("sh").arg("-c")
		.arg(r#"if [[ $(git log -1 --pretty=%s) == "--blunderbuss-checkpoint--" ]]; then git reset HEAD~1; fi"#)
		.output().await?.demand_status_success("failed to remove blunderbuss checkpoint")?;

	Ok(())
}
/// remove all changes blunderbuss made and get rid of the blunderbuss checkpoint commit if there is one
async fn hard_reset_and_pop_checkpoint_commit() -> anyhow::Result<()> {
	tokio::process::Command::new("sh").arg("-c")
		.arg(r#"git reset --hard HEAD && git clean -fd"#)
		.output().await?.demand_status_success("failed to reset blunderbuss's changes")?;

	pop_checkpoint_commit().await?;

	Ok(())
}


fn genai_error_is_retryable(e: &genai::Error) -> bool {
	// e.headers()

	if let Some(status) = e.status() {
		return status.is_server_error()
			|| status == http::StatusCode::TOO_MANY_REQUESTS
			|| status == http::StatusCode::REQUEST_TIMEOUT
	}
	return false
}