devai 0.5.12

Command Agent runner to accelerate production coding with genai.
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
use crate::hub::get_hub;
use crate::run::{DirContext, PathResolver, RuntimeContext};
use crate::script::lua_script::helpers::{get_value_prop_as_string, to_vec_of_strings};
use crate::support::{files, paths, AsStrsExt};
use crate::types::{FileMeta, FileRecord};
use crate::{Error, Result};
use mlua::{FromLua, IntoLua, Lua, Value};
use simple_fs::{ensure_file_dir, iter_files, list_files, ListOptions, SPath};
use std::fs::write;
use std::io::Write;

/// ## Lua Documentation
///
/// Load a File Record object with its ontent
///
/// ```lua
/// local file = utils.file.load("doc/README.md")
/// -- file.content contains the text content of the file
/// ```
///
/// ### Returns
///
///
/// ```lua
/// -- FileRecord
/// {
///   path    = "doc/README.md",
///   content = "... text content of the file ...",
///   name    = "README.md",
///   stem    = "README",
///   ext     = "md",
/// }
/// ```
///
///
pub(super) fn file_load(
	lua: &Lua,
	ctx: &RuntimeContext,
	rel_path: String,
	options: Option<Value>,
) -> mlua::Result<mlua::Value> {
	let base_path = compute_base_dir(ctx.dir_context(), options.as_ref())?;
	let rel_path = SPath::new(rel_path).map_err(Error::from)?;

	let file_record = FileRecord::load(&base_path, &rel_path)?;
	let res = file_record.into_lua(lua)?;

	Ok(res)
}

/// ## Lua Documentation
///
/// Save a File Content into a path
///
/// ```lua
/// utils.file.save("doc/README.md", "Some very cool documentation")
/// ```
///
/// ### Returns
///
/// Does not return anything
///
pub(super) fn file_save(_lua: &Lua, ctx: &RuntimeContext, rel_path: String, content: String) -> mlua::Result<()> {
	let path = ctx.dir_context().resolve_path(&rel_path, PathResolver::WorkspaceDir)?;
	ensure_file_dir(&path).map_err(Error::from)?;

	write(&path, content)?;

	get_hub().publish_sync(format!("-> Lua utils.file.save called on: {}", rel_path));

	Ok(())
}

/// ## Lua Documentation
///
/// Append content to a file at a specified path
///
/// ```lua
/// utils.file.append("doc/README.md", "Appended content to the file")
/// ```
///
/// ### Returns
///
/// Does not return anything
///
pub(super) fn file_append(_lua: &Lua, ctx: &RuntimeContext, rel_path: String, content: String) -> mlua::Result<()> {
	let path = ctx.dir_context().resolve_path(&rel_path, PathResolver::WorkspaceDir)?;
	ensure_file_dir(&path).map_err(Error::from)?;

	let mut file = std::fs::OpenOptions::new()
		.append(true)
		.create(true)
		.open(&path)
		.map_err(Error::from)?;

	file.write_all(content.as_bytes())?;

	// NOTE: Could be too many prints
	// get_hub().publish_sync(format!("-> Lua utils.file.append called on: {}", rel_path));

	Ok(())
}

/// ## Lua Documentation
///
/// Ensure a file exists at the given path, and if not create it with an optional content
///
/// ```lua
/// utils.file.ensure_exists(path, optional_content) -- FileMeta
/// ```
///
/// ### Returns
///
/// Does not return anything
///
pub(super) fn file_ensure_exists(
	lua: &Lua,
	ctx: &RuntimeContext,
	path: String,
	content: Option<String>,
	options: Option<EnsureExistsOptions>,
) -> mlua::Result<mlua::Value> {
	let options = options.unwrap_or_default();
	let rel_path = SPath::new(path).map_err(Error::from)?;
	let full_path = ctx.dir_context().resolve_path(&rel_path, PathResolver::WorkspaceDir)?;

	// if the file does not exist, create it.
	if !full_path.exists() {
		simple_fs::ensure_file_dir(&full_path).map_err(|err| Error::custom(err.to_string()))?;
		let content = content.unwrap_or_default();
		write(&full_path, content)?;
	}
	// if we have the options.content_when_empty flag, if empty
	else if options.content_when_empty && files::is_file_empty(&full_path)? {
		let content = content.unwrap_or_default();
		write(full_path, content)?;
	}

	let file_meta = FileMeta::from(rel_path);

	file_meta.into_lua(lua)
}

/// ## Lua Documentation
///
/// List a set of file reference (no content) for a given glob
///
/// ```lua
/// let all_doc_file = utils.file.list("doc/**/*.md")
/// ```
///
///
/// ### Returns
///
/// ```lua
/// -- An array/table of FileMeta
/// {
///   path    = "doc/README.md",
///   name    = "README.md",
///   stem    = "README",
///   ext     = "md"
/// }
/// ```
///
/// To get the content of files, needs iterate and load each
///
pub(super) fn file_list(
	lua: &Lua,
	ctx: &RuntimeContext,
	include_globs: Value,
	options: Option<Value>,
) -> mlua::Result<Value> {
	let (base_path, include_globs) = base_dir_and_globs(ctx, include_globs, options.as_ref())?;

	let sfiles = list_files(
		&base_path,
		Some(&include_globs.x_as_strs()),
		Some(ListOptions::from_relative_glob(true)),
	)
	.map_err(Error::from)?;

	// Now, we put back the paths found relative to base_path
	let sfiles = sfiles
		.into_iter()
		.map(|f| {
			//
			let diff = f.diff(&base_path)?;
			// if the diff goes back from base_path, then, we put the absolute path
			if diff.to_str().starts_with("..") {
				Ok(SPath::from(f))
			} else {
				Ok(diff)
			}
		})
		.collect::<simple_fs::Result<Vec<SPath>>>()
		.map_err(|err| crate::Error::cc("Cannot list files to base", err))?;

	let file_metas: Vec<FileMeta> = sfiles.into_iter().map(FileMeta::from).collect();
	let res = file_metas.into_lua(lua)?;

	Ok(res)
}

/// ## Lua Documentation
///
/// List a set of file reference (no content) for a given glob and load them
///
/// ```lua
/// let all_doc_file = utils.file.list_load("doc/**/*.md")
/// ```
///
///
/// ### Returns
///
/// ```lua
/// -- An array/table of FileRecord
/// {
///   path    = "doc/README.md",
///   name    = "README.md",
///   stem    = "README",
///   ext     = "md",
///   content = "..."
/// }
/// ```
///
/// To get the content of files, needs iterate and load each
///
pub(super) fn file_list_load(
	lua: &Lua,
	ctx: &RuntimeContext,
	include_globs: Value,
	options: Option<Value>,
) -> mlua::Result<Value> {
	let (base_path, include_globs) = base_dir_and_globs(ctx, include_globs, options.as_ref())?;

	let sfiles = list_files(
		&base_path,
		Some(&include_globs.x_as_strs()),
		Some(ListOptions::from_relative_glob(true)),
	)
	.map_err(Error::from)?;

	let file_records = sfiles
		.into_iter()
		.map(|sfile| -> Result<FileRecord> {
			//
			let diff = sfile.diff(&base_path)?;
			// if the diff goes back from base_path, then, we put the absolute path
			// TODO: need to double check this
			let (base_path, rel_path) = if diff.to_str().starts_with("..") {
				(SPath::from(""), SPath::from(sfile))
			} else {
				(base_path.clone(), diff)
			};
			let file_record = FileRecord::load(&base_path, &rel_path)?;
			Ok(file_record)
		})
		.collect::<Result<Vec<_>>>()?;

	let res = file_records.into_lua(lua)?;

	Ok(res)
}

/// ## Lua Documentation
///
/// Return the first FileMeta or Nil
///
/// ```lua
/// let first_doc_file = utils.file.first("doc/**/*.md")
/// ```
///
///
/// ### Returns
///
/// ```lua
/// -- FileMeta or Nil
/// {
///   path    = "doc/README.md",
///   name    = "README.md",
///   stem    = "README",
///   ext     = "md",
/// }
/// ```
///
/// To get the file record with .content, do
///
/// ```lua
/// let file = utils.file.load(file_meta.path)
/// ```
pub(super) fn file_first(
	lua: &Lua,
	ctx: &RuntimeContext,
	include_globs: Value,
	options: Option<Value>,
) -> mlua::Result<Value> {
	let (base_path, include_globs) = base_dir_and_globs(ctx, include_globs, options.as_ref())?;
	let mut sfiles = iter_files(
		&base_path,
		Some(&include_globs.x_as_strs()),
		Some(ListOptions::from_relative_glob(true)),
	)
	.map_err(Error::from)?;

	let Some(sfile) = sfiles.next() else {
		return Ok(Value::Nil);
	};

	let sfile = sfile
		.diff(&base_path)
		.map_err(|err| Error::cc("Cannot diff with base_path", err))?;

	let res = FileMeta::from(sfile).into_lua(lua)?;

	Ok(res)
}

// region:    --- Options
#[derive(Debug, Default)]
pub struct EnsureExistsOptions {
	/// Set the eventual provided content if the file is empty (only whitespaces)
	content_when_empty: bool,
}

impl FromLua for EnsureExistsOptions {
	fn from_lua(value: Value, _lua: &Lua) -> mlua::Result<Self> {
		let table = value
			.as_table()
			.ok_or(crate::Error::custom("EnsureExistsOptions should be a table"))?;
		let set_content_when_empty = table.get("content_when_empty")?;
		Ok(Self {
			content_when_empty: set_content_when_empty,
		})
	}
}

// endregion: --- Options

// region:    --- Support

/// return (base_path, globs)
fn base_dir_and_globs(
	ctx: &RuntimeContext,
	include_globs: Value,
	options: Option<&Value>,
) -> Result<(SPath, Vec<String>)> {
	let globs: Vec<String> = to_vec_of_strings(include_globs, "file::file_list globs argument")?;
	let base_dir = compute_base_dir(ctx.dir_context(), options)?;
	Ok((base_dir, globs))
}

fn compute_base_dir(dir_context: &DirContext, options: Option<&Value>) -> Result<SPath> {
	// the default base_path is the workspace dir.
	let workspace_path = dir_context.resolve_path("", PathResolver::WorkspaceDir)?;

	// if options, try to resolve the options.base_dir
	let base_dir = get_value_prop_as_string(options, "base_dir", "utils.file... options fail")?;

	let base_dir = match base_dir {
		Some(base_dir) => {
			if paths::is_relative(&base_dir) {
				workspace_path.join_str(&base_dir)
			} else {
				SPath::from(base_dir)
			}
		}
		None => workspace_path,
	};

	Ok(base_dir)
}

// endregion: --- Support

// region:    --- Tests

#[cfg(test)]
mod tests {
	type Result<T> = core::result::Result<T, Box<dyn std::error::Error>>; // For tests.

	use crate::_test_support::{assert_contains, eval_lua, run_reflective_agent, setup_lua, SANDBOX_01_DIR};
	use std::path::Path;
	use value_ext::JsonValueExt as _;

	#[tokio::test]
	async fn test_lua_file_load_simple_ok() -> Result<()> {
		// -- Setup & Fixtures
		let fx_path = "./agent-script/agent-hello.devai";

		// -- Exec
		let res = run_reflective_agent(&format!(r#"return utils.file.load("{fx_path}")"#), None).await?;

		// -- Check
		assert_contains(res.x_get_str("content")?, "from agent-hello.devai");
		assert_eq!(res.x_get_str("path")?, fx_path);
		assert_eq!(res.x_get_str("name")?, "agent-hello.devai");

		Ok(())
	}

	/// Note: need the multi-thread, because save do a `get_hub().publish_sync`
	///       which does a tokio blocking (requiring multi thread)
	#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
	async fn test_lua_file_save_simple_ok() -> Result<()> {
		// -- Setup & Fixtures
		let fx_dest_path = "./.tmp/test_file_save_simple_ok/agent-hello.devai";
		let fx_content = "hello from test_file_save_simple_ok";

		// -- Exec
		let _res = run_reflective_agent(
			&format!(r#"return utils.file.save("{fx_dest_path}", "{fx_content}");"#),
			None,
		)
		.await?;

		// -- Check
		let dest_path = Path::new(SANDBOX_01_DIR).join(fx_dest_path);
		let file_content = std::fs::read_to_string(dest_path)?;
		assert_eq!(file_content, fx_content);

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_file_list_glob_direct() -> Result<()> {
		// -- Fixtures
		// This is the rust Path logic
		let glob = "*.*";

		// -- Exec
		let res = run_reflective_agent(&format!(r#"return utils.file.list("{glob}");"#), None).await?;

		// -- Check
		let res_paths = to_res_paths(&res);
		assert_eq!(res_paths.len(), 2, "result length");
		assert_contains(&res_paths, "file-01.txt");
		assert_contains(&res_paths, "file-02.txt");

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_file_list_glob_deep() -> Result<()> {
		// -- Fixtures
		// This is the rust Path logic
		let glob = "sub-dir-a/**/*.*";

		// -- Exec
		let res = run_reflective_agent(&format!(r#"return utils.file.list("{glob}");"#), None).await?;

		// -- Check
		let res_paths = to_res_paths(&res);
		assert_eq!(res_paths.len(), 2, "result length");
		assert_contains(&res_paths, "sub-dir-a/sub-sub-dir/agent-hello-3.devai");
		assert_contains(&res_paths, "sub-dir-a/sub-sub-dir/agent-hello-3.devai");

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_file_list_glob_abs_with_wild() -> Result<()> {
		// -- Fixtures
		let lua = setup_lua(super::super::init_module, "file")?;
		let dir = Path::new("./tests-data/config");
		let dir = dir
			.canonicalize()
			.map_err(|err| format!("Cannot canonicalize {dir:?} cause: {err}"))?;

		// This is the rust Path logic
		let glob = format!("{}/*.*", dir.to_string_lossy());
		let code = format!(r#"return utils.file.list("{glob}");"#);

		// -- Exec
		let _res = eval_lua(&lua, &code)?;

		// -- Check
		// TODO:

		Ok(())
	}

	#[test]
	fn test_lua_file_list_glob_with_base_dir_all_nested() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(super::super::init_module, "file")?;
		let lua_code = r#"
local files = utils.file.list({"**/*.*"}, {base_dir = "sub-dir-a"})
return { files = files }
		"#;

		// -- Exec
		let res = eval_lua(&lua, lua_code)?;

		// -- Check
		let files = res
			.get("files")
			.ok_or("Should have .files")?
			.as_array()
			.ok_or("file should be array")?;

		assert_eq!(files.len(), 2, ".files.len() should be 2");
		// NOTE: Here we assume the order will be deterministic and the same across OSes (tested on Mac).
		//       This logic might need to be changed, or actually, the list might need to have a fixed order.
		assert_eq!(
			"agent-hello-2.devai",
			files.first().ok_or("Should have a least one file")?.x_get_str("name")?
		);
		assert_eq!(
			"agent-hello-3.devai",
			files.get(1).ok_or("Should have a least two file")?.x_get_str("name")?
		);

		Ok(())
	}

	#[test]
	fn test_lua_file_list_glob_with_base_dir_one_level() -> Result<()> {
		// -- Setup & Fixtures
		let lua = setup_lua(super::super::init_module, "file")?;
		let lua_code = r#"
local files = utils.file.list({"agent-hello-*.devai"}, {base_dir = "sub-dir-a"})
return { files = files }
		"#;

		// -- Exec
		let res = eval_lua(&lua, lua_code)?;

		// -- Check
		let files = res
			.get("files")
			.ok_or("Should have .files")?
			.as_array()
			.ok_or("file should be array")?;

		assert_eq!(files.len(), 1, ".files.len() should be 1");
		// NOTE: Here we assume the order will be deterministic and the same across OSes (tested on Mac).
		//       This logic might need to be changed, or actually, the list might need to have a fixed order.
		assert_eq!(
			"agent-hello-2.devai",
			files.first().ok_or("Should have a least one file")?.x_get_str("name")?
		);

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_file_first_glob_deep() -> Result<()> {
		// -- Fixtures
		// This is the rust Path logic
		let glob = "sub-dir-a/**/*-2.*";

		// -- Exec
		let res = run_reflective_agent(&format!(r#"return utils.file.first("{glob}");"#), None).await?;

		// -- Check
		// let res_paths = to_res_paths(&res);
		assert_eq!(res.x_get_str("name")?, "agent-hello-2.devai");
		assert_eq!(res.x_get_str("path")?, "sub-dir-a/agent-hello-2.devai");

		Ok(())
	}

	#[tokio::test]
	async fn test_lua_file_first_not_found() -> Result<()> {
		// -- Fixtures
		// This is the rust Path logic
		let glob = "sub-dir-a/**/*-not-a-thing.*";

		// -- Exec
		let res = run_reflective_agent(&format!(r#"return utils.file.first("{glob}")"#), None).await?;

		// -- Check
		assert_eq!(res, serde_json::Value::Null, "Should have returned null");

		Ok(())
	}

	// region:    --- Support for Tests

	fn to_res_paths(res: &serde_json::Value) -> Vec<&str> {
		res.as_array()
			.ok_or("should have array of path")
			.unwrap()
			.iter()
			.map(|v| v.x_get_as::<&str>("path").unwrap_or_default())
			.collect::<Vec<&str>>()
	}

	// endregion: --- Support for Tests
}

// endregion: --- Tests