-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenc.rs
More file actions
505 lines (464 loc) · 24.1 KB
/
enc.rs
File metadata and controls
505 lines (464 loc) · 24.1 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
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
// NOTICE: this file was automatically generated by https://github.com/khimaros/enc using the following invocation: ./enc-release src/enc.en -o src/enc.rs --context-files ./.enc.env.example:./Cargo.toml
use anyhow::{anyhow, Context, Result};
use chrono::Local;
use clap::{Arg, ArgAction, Command};
use futures::StreamExt;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command as StdCommand, Stdio};
use std::sync::Mutex;
use std::time::{Duration, Instant};
lazy_static::lazy_static! {
static ref LOG_PATH: Mutex<Option<PathBuf>> = Mutex::new(None);
}
// "enc uses a layered configuration. settings are sourced with the following precedence... flags > env > ./.enc.env > ~/.enc.env > defaults"
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Config {
pub anthropic_api_key: String,
pub gemini_api_key: String,
pub openai_api_key: String,
pub provider: String,
pub model: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_tokens: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub thinking_budget: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub seed: Option<i64>,
pub hacking_conventions: String,
pub timeout: u64,
pub context_files: String,
pub openai_api_base: String,
pub logs_path: String,
pub resources_path: String,
pub test_command: String,
pub test_iterations: i32,
#[serde(skip_serializing)]
pub input_file: String,
#[serde(skip_serializing)]
pub output_file: String,
#[serde(skip_serializing)]
pub show_config: bool,
}
#[derive(Default)]
struct Stats {
input_tokens: u64,
output_tokens: u64,
thinking_tokens: u64,
start_time: Option<Instant>,
}
#[derive(Deserialize, Clone)]
struct Pricing {
pub input_cost_per_token: f64,
pub output_cost_per_token: f64,
#[allow(dead_code)]
pub max_tokens: Option<i64>,
}
// "enc executes in this order: 1. parse arguments... 12. display summary"
#[tokio::main]
async fn main() -> Result<()> {
let mut stats = Stats { start_time: Some(Instant::now()), ..Default::default() };
let config = load_and_merge_config()?;
if config.show_config {
show_config(&config)?;
return Ok(());
}
validate_required_config(&config)?;
let log_file = init_logging(&config)?;
println!("debug log path: {}", log_file.display());
let res = run_transpilation(&config, &mut stats).await;
display_summary(&config, &stats);
if res.is_err() {
if let Err(e) = res { eprintln!("error: {}", e); }
std::process::exit(1);
}
Ok(())
}
// "command line: enc <INPUT_FILE> -o <OUTPUT_FILE> [OPTIONS] (input is positional, NOT a flag)"
fn load_and_merge_config() -> Result<Config> {
let matches = Command::new("enc")
.arg(Arg::new("INPUT_FILE").help("input file").index(1))
.arg(Arg::new("output").short('o').long("output").num_args(1))
.arg(Arg::new("provider").long("provider"))
.arg(Arg::new("model").long("model"))
.arg(Arg::new("max_tokens").long("max-tokens"))
.arg(Arg::new("thinking_budget").long("thinking-budget"))
.arg(Arg::new("seed").long("seed"))
.arg(Arg::new("hacking_conventions").long("hacking-conventions"))
.arg(Arg::new("timeout").long("timeout"))
.arg(Arg::new("context_files").long("context-files"))
.arg(Arg::new("openai_api_base").long("openai-api-base"))
.arg(Arg::new("logs_path").long("logs-path"))
.arg(Arg::new("resources_path").long("resources-path"))
.arg(Arg::new("test_command").long("test-command"))
.arg(Arg::new("test_iterations").long("test-iterations"))
.arg(Arg::new("anthropic_api_key").long("anthropic-api-key"))
.arg(Arg::new("gemini_api_key").long("gemini-api-key"))
.arg(Arg::new("openai_api_key").long("openai-api-key"))
.arg(Arg::new("show_config").long("show-config").action(ArgAction::SetTrue))
.get_matches();
let mut layers = Vec::new();
let keys = vec![
"provider", "model", "max_tokens", "thinking_budget", "seed",
"hacking_conventions", "timeout", "context_files", "openai_api_base",
"logs_path", "resources_path", "test_command", "test_iterations",
"anthropic_api_key", "gemini_api_key", "openai_api_key",
];
let mut flag_map = BTreeMap::new();
for k in &keys {
if let Some(v) = matches.get_one::<String>(k) { flag_map.insert(k.to_string(), v.to_string()); }
}
layers.push(flag_map);
let mut env_map = BTreeMap::new();
for k in &keys {
if let Ok(v) = std::env::var(k.to_uppercase()) { env_map.insert(k.to_string(), v); }
}
layers.push(env_map);
layers.push(parse_env_file(".enc.env")?);
if let Some(mut home) = dirs::home_dir() {
home.push(".enc.env");
layers.push(parse_env_file(home.to_str().unwrap_or(""))?);
}
let mut defaults = BTreeMap::new();
defaults.insert("provider".to_string(), "google".to_string());
defaults.insert("model".to_string(), "gemini-2.5-pro".to_string());
defaults.insert("hacking_conventions".to_string(), "./HACKING.md".to_string());
defaults.insert("timeout".to_string(), "1800".to_string());
defaults.insert("openai_api_base".to_string(), "https://api.openai.com/v1".to_string());
defaults.insert("logs_path".to_string(), "./log/".to_string());
defaults.insert("resources_path".to_string(), "./res/:${XDG_DATA_HOME}/enc/res/".to_string());
defaults.insert("test_iterations".to_string(), "3".to_string());
layers.push(defaults);
let mut merged = BTreeMap::new();
for layer in layers.into_iter().rev() {
for (k, v) in layer {
if !v.trim().is_empty() { merged.insert(k, v); }
}
}
let input_file = matches.get_one::<String>("INPUT_FILE").cloned().unwrap_or_default();
let output_file = matches.get_one::<String>("output").cloned().unwrap_or_default();
let show_config = matches.get_flag("show_config");
if !show_config && (input_file.is_empty() || output_file.is_empty()) {
return Err(anyhow!("input file and output file (-o) are required"));
}
Ok(Config {
anthropic_api_key: merged.get("anthropic_api_key").cloned().unwrap_or_default(),
gemini_api_key: merged.get("gemini_api_key").cloned().unwrap_or_default(),
openai_api_key: merged.get("openai_api_key").cloned().unwrap_or_default(),
provider: merged.get("provider").cloned().unwrap_or_default(),
model: merged.get("model").cloned().unwrap_or_default(),
max_tokens: merged.get("max_tokens").and_then(|v| v.parse().ok()),
thinking_budget: merged.get("thinking_budget").and_then(|v| v.parse().ok()),
seed: merged.get("seed").and_then(|v| v.parse().ok()),
hacking_conventions: merged.get("hacking_conventions").cloned().unwrap_or_default(),
timeout: merged.get("timeout").and_then(|v| v.parse().ok()).unwrap_or(1800),
context_files: merged.get("context_files").cloned().unwrap_or_default(),
openai_api_base: merged.get("openai_api_base").cloned().unwrap_or_default(),
logs_path: merged.get("logs_path").cloned().unwrap_or_default(),
resources_path: merged.get("resources_path").cloned().unwrap_or_default(),
test_command: merged.get("test_command").cloned().unwrap_or_default(),
test_iterations: merged.get("test_iterations").and_then(|v| v.parse().ok()).unwrap_or(3),
input_file, output_file, show_config,
})
}
// ".env files are read manually... WITHOUT modifying the process environment."
fn parse_env_file(path: &str) -> Result<BTreeMap<String, String>> {
let mut map = BTreeMap::new();
let content = match fs::read_to_string(path) { Ok(c) => c, Err(_) => return Ok(map) };
for line in content.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') { continue; }
if let Some((k, v)) = line.split_once('=') {
map.insert(k.trim().to_lowercase(), v.trim().trim_matches('"').trim_matches('\'').to_string());
}
}
Ok(map)
}
// "when the --show-config flag is provided... output the redacted configuration immediately."
fn show_config(config: &Config) -> Result<()> {
let mut out = serde_json::to_value(config)?;
if let Some(map) = out.as_object_mut() {
map.insert("anthropic_api_key".to_string(), json!("[REDACTED]"));
map.insert("gemini_api_key".to_string(), json!("[REDACTED]"));
map.insert("openai_api_key".to_string(), json!("[REDACTED]"));
let strings = vec!["hacking_conventions", "context_files", "openai_api_base", "test_command", "logs_path", "resources_path"];
for s in strings { if let Some(v) = map.get(s).and_then(|v| v.as_str()) { if v.is_empty() { map.remove(s); } } }
}
let sorted: BTreeMap<String, Value> = serde_json::from_value(out)?;
println!("{}", serde_json::to_string_pretty(&sorted)?);
Ok(())
}
// "check required API key for selected provider exists"
fn validate_required_config(config: &Config) -> Result<()> {
let key = match config.provider.as_str() {
"google" => &config.gemini_api_key,
"anthropic" => &config.anthropic_api_key,
"openai" => &config.openai_api_key,
_ => return Err(anyhow!("unsupported provider: {}", config.provider)),
};
if key.is_empty() { return Err(anyhow!("missing api key for provider: {}", config.provider)); }
Ok(())
}
// "initialize logging: create timestamped log file, write config"
fn init_logging(config: &Config) -> Result<PathBuf> {
let dir = PathBuf::from(&config.logs_path);
if !dir.exists() { fs::create_dir_all(&dir)?; }
let log_path = dir.join(format!("{}.log", Local::now().format("%Y%m%d_%H%M%S")));
let mut redacted = config.clone();
redacted.anthropic_api_key = "[REDACTED]".into();
redacted.gemini_api_key = "[REDACTED]".into();
redacted.openai_api_key = "[REDACTED]".into();
fs::write(&log_path, format!("config: {}\n", serde_json::to_string(&redacted)?))?;
*LOG_PATH.lock().unwrap() = Some(log_path.clone());
Ok(log_path)
}
// "run tests (if configured): execute test command, retry on failure up to TEST_ITERATIONS"
async fn run_transpilation(config: &Config, stats: &mut Stats) -> Result<()> {
let mut iteration = 0;
let mut err_ctx = String::new();
loop {
iteration += 1;
let lang = get_target_lang(config)?;
println!("transpiling '{}' to '{}' ({})", config.input_file, config.output_file, lang);
let prompt = build_prompt(config, &err_ctx)?;
log_msg(&format!("expanded prompt:\n{}", prompt))?;
let resp = call_api(config, &prompt, stats).await?;
let code = process_response(&resp)?;
if code.is_empty() { return Err(anyhow!("llm returned empty response")); }
fs::write(&config.output_file, &code)?;
if config.test_command.is_empty() {
println!("successfully transpiled '{}'", config.output_file);
return Ok(());
}
println!("executing test command (`{}`), attempt {}/{}", config.test_command, iteration, if config.test_iterations == -1 { "∞".into() } else { config.test_iterations.to_string() });
let test = run_test_command(config)?;
if test.status.success() {
println!("test command succeeded!");
println!("successfully transpiled '{}'", config.output_file);
return Ok(());
}
println!("test command failed, see log for details");
log_msg(&format!("test stdout: {}\ntest stderr: {}", test.stdout, test.stderr))?;
if config.test_iterations != -1 && iteration >= config.test_iterations {
return Err(anyhow!("tests failed after {} iterations", iteration));
}
err_ctx = format!("previously generated code:\n```\n{}\n```\ntest command: {}\nexit code: {}\nstdout:\n{}\nstderr:\n{}", code, config.test_command, test.status.code().unwrap_or(-1), test.stdout, test.stderr);
}
}
// "substitute template variables (single pass, no recursion)"
fn build_prompt(config: &Config, err_ctx: &str) -> Result<String> {
let mut gen_cmd = std::env::args().collect::<Vec<_>>().join(" ");
let lang = get_target_lang(config)?;
if vec!["xml", "html", "svg"].iter().any(|&e| lang.to_lowercase() == e) { gen_cmd = gen_cmd.replace("--", ""); }
let mut redacted = config.clone();
redacted.anthropic_api_key = "[REDACTED]".into();
redacted.gemini_api_key = "[REDACTED]".into();
redacted.openai_api_key = "[REDACTED]".into();
let vars = [
("generation_command", redact_paths(&gen_cmd)),
("generation_config", serde_json::to_string(&redacted)?),
("target_language", lang),
("output_path", redact_paths(&config.output_file)),
("english_content", fs::read_to_string(&config.input_file)?),
("hacking_conventions", if config.hacking_conventions.is_empty() { "".into() } else { fs::read_to_string(&config.hacking_conventions).unwrap_or_default() }),
("context_files", build_contexts(&config.context_files)?),
("error_context", err_ctx.to_string()),
];
let mut p = load_resource(config, "prompt.tmpl")?;
for (k, v) in vars { p = p.replace(&format!("{{{{{}}}}}", k), &v); }
Ok(p)
}
fn build_contexts(files: &str) -> Result<String> {
let mut c = String::new();
for f in files.split(':').filter(|s| !s.is_empty()) {
let content = fs::read_to_string(f).context(format!("could not read context file: {}", f))?;
c.push_str(&format!("### {}\n\n```\n{}\n```\n\n", f, content));
}
Ok(c)
}
// "call API: send request to selected provider, handle streaming if applicable"
async fn call_api(config: &Config, prompt: &str, stats: &mut Stats) -> Result<String> {
println!("calling api (provider: {}, model: {})...", config.provider, config.model);
let start = Instant::now();
let client = reqwest::Client::builder().timeout(Duration::from_secs(config.timeout)).build()?;
let (status, body) = match config.provider.as_str() {
"anthropic" => call_anthropic(&client, config, prompt, stats).await?,
"google" => call_google(&client, config, prompt, stats).await?,
"openai" => call_openai(&client, config, prompt, stats).await?,
_ => unreachable!(),
};
println!("api call completed with response code {} after {:.2}s", status, start.elapsed().as_secs_f64());
if status != 200 { return Err(anyhow!("{} error: {}", config.provider, body)); }
Ok(body)
}
// "anthropic streaming (SSE)... estimates thinking tokens (character count / 4)"
async fn call_anthropic(client: &reqwest::Client, config: &Config, prompt: &str, stats: &mut Stats) -> Result<(u16, String)> {
let mut payload = json!({"model": config.model, "messages": [{"role": "user", "content": prompt}], "stream": true, "max_tokens": config.max_tokens.unwrap_or(8192)});
if let Some(b) = config.thinking_budget {
if b > 0 {
payload["thinking"] = json!({"type": "enabled", "budget_tokens": b});
payload["temperature"] = json!(1);
} else if config.seed.is_some() { payload["temperature"] = json!(0); }
} else if config.seed.is_some() { payload["temperature"] = json!(0); }
let res = client.post("https://api.anthropic.com/v1/messages")
.header("anthropic-version", "2023-06-01").header("x-api-key", &config.anthropic_api_key).json(&payload).send().await?;
let status = res.status().as_u16();
let mut stream = res.bytes_stream();
let mut full = String::new();
let mut raw = String::new();
let mut buffer = String::new();
while let Some(chunk_res) = stream.next().await {
let chunk = chunk_res?;
let text = String::from_utf8_lossy(&chunk).into_owned();
raw.push_str(&text);
buffer.push_str(&text);
while let Some(pos) = buffer.find('\n') {
let line = buffer[..pos].trim().to_string();
buffer = buffer[pos + 1..].to_string();
if line.starts_with("data: ") {
if let Ok(val) = serde_json::from_str::<Value>(&line[6..]) {
match val["type"].as_str() {
Some("message_start") => stats.input_tokens += val["message"]["usage"]["input_tokens"].as_u64().unwrap_or(0),
Some("content_block_delta") => {
if let Some(t) = val["delta"]["text"].as_str() { full.push_str(t); log_msg(t)?; }
if let Some(th) = val["delta"]["thinking"].as_str() { stats.thinking_tokens += (th.len() as u64) / 4; log_msg(th)?; }
}
Some("message_delta") => stats.output_tokens += val["usage"]["output_tokens"].as_u64().unwrap_or(0),
_ => {}
}
}
}
}
}
if status != 200 { return Ok((status, raw)); }
Ok((status, full))
}
// "google provider... thinking tokens: check usageMetadata.thinkingTokenCount, or calculate"
async fn call_google(client: &reqwest::Client, config: &Config, prompt: &str, stats: &mut Stats) -> Result<(u16, String)> {
let url = format!("https://generativelanguage.googleapis.com/v1beta/models/{}:generateContent?key={}", config.model, config.gemini_api_key);
let mut payload = json!({"contents": [{"parts": [{"text": prompt}]}]});
if config.seed.is_some() { payload["generationConfig"] = json!({"temperature": 0}); }
let res = client.post(url).json(&payload).send().await?;
let status = res.status().as_u16();
let body = res.text().await?;
if status != 200 { return Ok((status, body)); }
let val: Value = serde_json::from_str(&body)?;
let mut content = String::new();
if let Some(parts) = val["candidates"][0]["content"]["parts"].as_array() {
for p in parts { if let Some(t) = p["text"].as_str() { content.push_str(t); } }
}
let usage = &val["usageMetadata"];
let i = usage["promptTokenCount"].as_u64().unwrap_or(0);
let o = usage["candidatesTokenCount"].as_u64().unwrap_or(0);
let mut t = usage["thinkingTokenCount"].as_u64().unwrap_or(0);
let tot = usage["totalTokenCount"].as_u64().unwrap_or(0);
if t == 0 && tot > (i + o) { t = tot - i - o; }
stats.input_tokens += i; stats.output_tokens += o; stats.thinking_tokens += t;
log_msg(&content)?;
Ok((status, content))
}
// "openai-specific behavior... check usage.completion_tokens_details.reasoning_tokens"
async fn call_openai(client: &reqwest::Client, config: &Config, prompt: &str, stats: &mut Stats) -> Result<(u16, String)> {
let mut payload = json!({"model": config.model, "messages": [{"role": "user", "content": prompt}]});
if config.openai_api_base.contains("api.openai.com") { if let Some(m) = config.max_tokens { payload["max_completion_tokens"] = json!(m); } }
else if let Some(m) = config.max_tokens { payload["max_tokens"] = json!(m); }
if let Some(s) = config.seed { payload["seed"] = json!(s); }
let res = client.post(format!("{}/chat/completions", config.openai_api_base)).header("Authorization", format!("Bearer {}", config.openai_api_key)).json(&payload).send().await?;
let status = res.status().as_u16();
let body = res.text().await?;
if status != 200 { return Ok((status, body)); }
let val: Value = serde_json::from_str(&body)?;
let content = val["choices"][0]["message"]["content"].as_str().unwrap_or_default().to_string();
let usage = &val["usage"];
stats.input_tokens += usage["prompt_tokens"].as_u64().unwrap_or(0);
let o = usage["completion_tokens"].as_u64().unwrap_or(0);
stats.output_tokens += o;
let t = usage["completion_tokens_details"]["reasoning_tokens"].as_u64()
.or(usage["reasoning_tokens"].as_u64()).or(usage["thinking_tokens"].as_u64()).unwrap_or(0);
stats.thinking_tokens += t;
log_msg(&content)?;
Ok((status, content))
}
// "strip markdown code fences from first/last lines only (```language or ```)"
fn process_response(resp: &str) -> Result<String> {
let re = Regex::new(r"(?s)^[ \t]*```[a-zA-Z]*\n?(.*?)\n?```[ \t]*$")?;
Ok(if let Some(caps) = re.captures(resp) { caps[1].trim().to_string() } else { resp.trim().to_string() })
}
// "test command is executed with a restricted environment. only these variables are preserved..."
struct TestResult { status: std::process::ExitStatus, stdout: String, stderr: String }
fn run_test_command(config: &Config) -> Result<TestResult> {
let mut cmd = StdCommand::new("sh");
cmd.arg("-c").arg(&config.test_command).env_clear().stdout(Stdio::piped()).stderr(Stdio::piped());
for v in ["PATH", "RUSTUP_HOME", "CARGO_HOME"] { if let Ok(val) = std::env::var(v) { cmd.env(v, val); } }
let out = cmd.spawn()?.wait_with_output()?;
Ok(TestResult { status: out.status, stdout: String::from_utf8_lossy(&out.stdout).to_string(), stderr: String::from_utf8_lossy(&out.stderr).to_string() })
}
// "at the end of invocation, display accumulated totals"
fn display_summary(config: &Config, stats: &Stats) {
println!("\n--- api request summary ---");
let mut line = format!("tokens: {} input, {} output", stats.input_tokens, stats.output_tokens);
if stats.thinking_tokens > 0 { line.push_str(&format!(", {} thinking", stats.thinking_tokens)); }
println!("{}", line);
if let Ok(pricing) = load_pricing(config) {
println!("estimated cost:");
let i = stats.input_tokens as f64 * pricing.input_cost_per_token;
let o = stats.output_tokens as f64 * pricing.output_cost_per_token;
println!(" - input: ${:.6}\n - output: ${:.6}", i, o);
let mut total = i + o;
if stats.thinking_tokens > 0 {
let t = stats.thinking_tokens as f64 * pricing.output_cost_per_token;
println!(" - thinking: ${:.6}", t);
total += t;
}
println!("total: ${:.6}", total);
} else { println!("warning: pricing data unavailable, eliding cost data"); }
if let Some(s) = stats.start_time { println!("elapsed time: {:.2}s", s.elapsed().as_secs_f64()); }
}
// "language detection... lookup order: 1. file extension... 2. base filename... 3. lookup key"
fn get_target_lang(config: &Config) -> Result<String> {
let p = Path::new(&config.output_file);
let ext = p.extension().and_then(|e| e.to_str()).map(|e| format!(".{}", e));
let name = p.file_name().and_then(|n| n.to_str());
let res = load_resource(config, "languages.json")?;
let map: BTreeMap<String, String> = serde_json::from_str(&res)?;
if let Some(ref e) = ext { if let Some(l) = map.get(e) { return Ok(l.clone()); } }
if let Some(n) = name { if let Some(l) = map.get(n) { return Ok(l.clone()); } }
Ok(ext.or(name.map(|n| n.to_string())).unwrap_or_else(|| "unknown".into()))
}
// "enc searches for resource files in order: 1. path in RESOURCES_PATH... 2. embedded fallbacks"
fn load_resource(config: &Config, name: &str) -> Result<String> {
let xdg = std::env::var("XDG_DATA_HOME").unwrap_or_else(|_| {
let mut h = dirs::home_dir().unwrap_or_default(); h.push(".local/share");
h.to_str().unwrap_or_default().to_string()
});
for p in config.resources_path.replace("${XDG_DATA_HOME}", &xdg).split(':').filter(|s| !s.is_empty()) {
let path = PathBuf::from(p).join(name);
if path.exists() { return Ok(fs::read_to_string(path)?); }
}
match name {
"prompt.tmpl" => Ok(include_str!("../res/prompt.tmpl").to_string()),
"languages.json" => Ok(include_str!("../res/languages.json").to_string()),
"pricing.json" => Ok(include_str!("../res/pricing.json").to_string()),
_ => Err(anyhow!("resource not found: {}", name)),
}
}
fn load_pricing(config: &Config) -> Result<Pricing> {
let map: BTreeMap<String, Pricing> = serde_json::from_str(&load_resource(config, "pricing.json")?)?;
let key = format!("{}/{}", config.provider, config.model);
map.get(&key).cloned().ok_or_else(|| anyhow!("no pricing for {}", key))
}
fn log_msg(msg: &str) -> Result<()> {
if let Some(path) = LOG_PATH.lock().unwrap().as_ref() {
let mut f = fs::OpenOptions::new().append(true).open(path)?;
writeln!(f, "{}", msg)?;
}
Ok(())
}
fn redact_paths(s: &str) -> String {
Regex::new(r"/\S+/\S+").unwrap().replace_all(s, "[REDACTED_PATH]").to_string()
}