-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathenc.ts
More file actions
executable file
·756 lines (632 loc) · 25 KB
/
enc.ts
File metadata and controls
executable file
·756 lines (632 loc) · 25 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
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
#!/usr/bin/env node
// notice that the file was automatically generated by https://github.com/khimaros/enc using the following invocation: ./enc-release src/enc.en -o src/enc.ts --context-files ./.enc.env.example:./package.json
// enc is a program that can be used to transpile any english language file (eg. "hello.en") into any other programming language (eg. "hello.c")
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { execSync } from 'node:child_process';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import dotenv from 'dotenv';
import axios from 'axios';
// hacking conventions: keep dependencies to a minimum and prefer standard library.
// hacking conventions: code comments and command line output should be all lowercase.
// configuration
// enc uses a layered configuration. settings are sourced with the following precedence (from highest to lowest)
interface Config {
input_file: string;
output_file: string;
provider: string;
model: string;
max_tokens?: number;
thinking_budget?: number;
seed?: number;
hacking_conventions: string;
timeout: number;
context_files: string;
gemini_api_key: string;
anthropic_api_key: string;
openai_api_key: string;
openai_api_base: string;
logs_path: string;
resources_path: string;
test_command: string;
test_iterations: number;
show_config: boolean;
debug: boolean;
}
const defaults: Partial<Config> = {
provider: 'google',
model: '', // default depends on provider
hacking_conventions: './HACKING.md',
timeout: 1800,
openai_api_base: 'https://api.openai.com/v1',
logs_path: './log/',
resources_path: './res/:${XDG_DATA_HOME}/enc/res/',
test_iterations: 3,
context_files: '',
test_command: '',
gemini_api_key: '',
anthropic_api_key: '',
openai_api_key: '',
};
// merging rules (critical)
// values from higher-precedence sources override lower-precedence sources
// empty values must not override non-empty values from lower-precedence sources
function merge_config(base: any, override: any): any {
const result = { ...base };
for (const key in override) {
const val = override[key];
if (val !== undefined && val !== null && val !== '') {
result[key] = val;
}
}
return result;
}
function parse_env_file(filepath: string): Record<string, string> {
try {
if (fs.existsSync(filepath)) {
return dotenv.parse(fs.readFileSync(filepath));
}
} catch (e) {
// ignore missing files
}
return {};
}
function get_env_config(): Record<string, any> {
const mapping: Record<string, string> = {
PROVIDER: 'provider',
MODEL: 'model',
MAX_TOKENS: 'max_tokens',
THINKING_BUDGET: 'thinking_budget',
SEED: 'seed',
HACKING_CONVENTIONS: 'hacking_conventions',
TIMEOUT: 'timeout',
CONTEXT_FILES: 'context_files',
GEMINI_API_KEY: 'gemini_api_key',
ANTHROPIC_API_KEY: 'anthropic_api_key',
OPENAI_API_KEY: 'openai_api_key',
OPENAI_API_BASE: 'openai_api_base',
LOGS_PATH: 'logs_path',
RESOURCES_PATH: 'resources_path',
TEST_COMMAND: 'test_command',
TEST_ITERATIONS: 'test_iterations',
};
const config: Record<string, any> = {};
for (const [env_key, config_key] of Object.entries(mapping)) {
if (process.env[env_key]) config[config_key] = process.env[env_key];
}
return config;
}
// command line interface
// enc <input_file> -o <output_file> [options]
async function parse_args(): Promise<Config> {
const argv = await yargs(hideBin(process.argv))
.usage('enc <input_file> -o <output_file> [options]')
.positional('input_file', { describe: 'input file path', type: 'string' })
.option('o', { alias: 'output', describe: 'output file path', type: 'string' })
.option('provider', { type: 'string' })
.option('model', { type: 'string' })
.option('max-tokens', { type: 'number' })
.option('thinking-budget', { type: 'number' })
.option('seed', { type: 'number' })
.option('hacking-conventions', { type: 'string' })
.option('timeout', { type: 'number' })
.option('context-files', { type: 'string' })
.option('gemini-api-key', { type: 'string' })
.option('anthropic-api-key', { type: 'string' })
.option('openai-api-key', { type: 'string' })
.option('openai-api-base', { type: 'string' })
.option('logs-path', { type: 'string' })
.option('resources-path', { type: 'string' })
.option('test-command', { type: 'string' })
.option('test-iterations', { type: 'number' })
.option('show-config', { type: 'boolean' })
.option('debug', { type: 'boolean' })
.help()
.argv;
// manual mapping to clean up keys
const flags: any = {};
if (argv.provider) flags.provider = argv.provider;
if (argv.model) flags.model = argv.model;
if (argv['max-tokens']) flags.max_tokens = argv['max-tokens'];
if (argv['thinking-budget']) flags.thinking_budget = argv['thinking-budget'];
if (argv.seed) flags.seed = argv.seed;
if (argv['hacking-conventions']) flags.hacking_conventions = argv['hacking-conventions'];
if (argv.timeout) flags.timeout = argv.timeout;
if (argv['context-files']) flags.context_files = argv['context-files'];
if (argv['gemini-api-key']) flags.gemini_api_key = argv['gemini-api-key'];
if (argv['anthropic-api-key']) flags.anthropic_api_key = argv['anthropic-api-key'];
if (argv['openai-api-key']) flags.openai_api_key = argv['openai-api-key'];
if (argv['openai-api-base']) flags.openai_api_base = argv['openai-api-base'];
if (argv['logs-path']) flags.logs_path = argv['logs-path'];
if (argv['resources-path']) flags.resources_path = argv['resources-path'];
if (argv['test-command']) flags.test_command = argv['test-command'];
if (argv['test-iterations']) flags.test_iterations = argv['test-iterations'];
if (argv['show-config']) flags.show_config = argv['show-config'];
if (argv.debug) flags.debug = argv.debug;
const input_file = argv._[0] as string;
const output_file = argv.o as string;
if (!flags.show_config) {
if (!input_file) {
console.error('error: input file is required');
process.exit(1);
}
if (!output_file) {
console.error('error: output file is required (-o)');
process.exit(1);
}
}
// layering: flags > env > ./.enc.env > ~/.enc.env > defaults
const home_env = parse_env_file(path.join(os.homedir(), '.enc.env'));
const local_env = parse_env_file(path.join(process.cwd(), '.enc.env'));
const proc_env = get_env_config();
// normalize env keys to lowercase config keys
const norm_home = Object.fromEntries(Object.entries(home_env).map(([k, v]) => [k.toLowerCase(), v]));
const norm_local = Object.fromEntries(Object.entries(local_env).map(([k, v]) => [k.toLowerCase(), v]));
let config = { ...defaults } as Config;
config = merge_config(config, norm_home);
config = merge_config(config, norm_local);
config = merge_config(config, proc_env);
config = merge_config(config, flags);
config.input_file = input_file;
config.output_file = output_file;
// ensure numeric types for config values coming from env/files
if (config.max_tokens !== undefined) config.max_tokens = Number(config.max_tokens);
if (config.thinking_budget !== undefined) config.thinking_budget = parseInt(String(config.thinking_budget), 10);
if (config.seed !== undefined) config.seed = Number(config.seed);
if (config.timeout !== undefined) config.timeout = Number(config.timeout);
if (config.test_iterations !== undefined) config.test_iterations = Number(config.test_iterations);
return config;
}
// show-config
// when the --show-config flag is provided, enc first loads all sources of configuration and then writes the redacted config
function redact_config(config: Config): Record<string, any> {
const out: any = {};
const keys = Object.keys(config).sort();
for (const k of keys) {
const key = k as keyof Config;
const val = config[key];
// always redact api keys
if (key.includes('api_key')) {
out[key] = '[REDACTED]';
continue;
}
// numeric fields: omit if not explicitly set (undefined/null)
if (['max_tokens', 'seed', 'thinking_budget'].includes(key)) {
if (val !== undefined && val !== null) out[key] = val;
continue;
}
// string fields: omit only if empty
if (['hacking_conventions', 'context_files', 'openai_api_base', 'test_command', 'logs_path', 'resources_path'].includes(key)) {
if (val !== '') out[key] = val;
continue;
}
// integer fields with defaults: always include
if (['test_iterations', 'timeout'].includes(key)) {
out[key] = val;
continue;
}
// others
if (key !== 'input_file' && key !== 'output_file' && key !== 'show_config' && key !== 'debug') {
if (val !== undefined) out[key] = val;
}
}
return out;
}
// resources
// enc searches for resource files in order
function load_resource(config: Config, filename: string): string {
const paths = config.resources_path.split(':');
for (let p of paths) {
if (p.includes('${XDG_DATA_HOME}')) {
const xdg = process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local/share');
p = p.replace('${XDG_DATA_HOME}', xdg);
}
const full_path = path.join(p, filename);
if (fs.existsSync(full_path)) {
return fs.readFileSync(full_path, 'utf8');
}
}
// hardcoded fallbacks for standalone execution
if (filename === 'languages.json') return JSON.stringify({ ".rs": "rust", ".py": "python", ".js": "javascript", ".ts": "typescript", ".c": "c", ".cpp": "c++", ".go": "go", ".java": "java" });
if (filename === 'pricing.json') return JSON.stringify({});
if (filename === 'prompt.tmpl') return `
Generate {{target_language}} code based on the following instructions.
CONTEXT:
{{context_files}}
HACKING CONVENTIONS:
{{hacking_conventions}}
INPUT CONTENT:
{{english_content}}
OBJECTIVE:
{{generation_command}}
`.trim();
throw new Error(`resource not found: ${filename}`);
}
// logging
// each invocation creates a log file in logs_path
let log_file_handle: number | null = null;
function init_logging(config: Config) {
if (!fs.existsSync(config.logs_path)) {
fs.mkdirSync(config.logs_path, { recursive: true });
}
const now = new Date();
const fmt = (n: number) => String(n).padStart(2, '0');
const timestamp = `${now.getFullYear()}${fmt(now.getMonth()+1)}${fmt(now.getDate())}_${fmt(now.getHours())}${fmt(now.getMinutes())}${fmt(now.getSeconds())}`;
let log_path = path.join(config.logs_path, `${timestamp}.log`);
// try to preserve ./ prefix if config had it, to match golden output expectations
if (config.logs_path.startsWith('./') && !log_path.startsWith('./') && !path.isAbsolute(log_path)) {
log_path = './' + log_path;
}
console.log(`debug log path: ${log_path}`);
log_file_handle = fs.openSync(log_path, 'w');
}
function log(msg: string) {
if (log_file_handle !== null) {
fs.writeSync(log_file_handle, msg + '\n');
}
}
// providers
// enc supports three llm providers
interface TokenUsage {
input: number;
output: number;
thinking: number;
}
interface ProviderResponse {
text: string;
usage: TokenUsage;
}
async function call_api(config: Config, prompt: string): Promise<ProviderResponse> {
const model = config.model ||
(config.provider === 'google' ? 'gemini-2.5-pro' :
config.provider === 'anthropic' ? 'claude-sonnet-4-20250514' :
'gpt-5-2025-08-07');
console.log(`calling api (provider: ${config.provider}, model: ${model})...`);
const start_time = Date.now();
try {
let result: ProviderResponse;
if (config.provider === 'google') {
result = await call_google(config, model, prompt);
} else if (config.provider === 'anthropic') {
result = await call_anthropic(config, model, prompt);
} else {
result = await call_openai(config, model, prompt);
}
const elapsed = (Date.now() - start_time) / 1000;
console.log(`api call completed with response code 200 after ${elapsed.toFixed(2)}s`);
return result;
} catch (e: any) {
const elapsed = (Date.now() - start_time) / 1000;
const status = e.response ? e.response.status : 'unknown';
console.log(`api call completed with response code ${status} after ${elapsed.toFixed(2)}s`);
let err_msg = '';
if (e.response && e.response.data) {
const data = e.response.data;
// if data is a stream (eg. from anthropic responseType: 'stream'), read it
if (typeof data === 'object' && (typeof data.read === 'function' || typeof data.on === 'function') && !Buffer.isBuffer(data)) {
try {
const chunks: any[] = [];
for await (const chunk of data) {
chunks.push(chunk);
}
err_msg = Buffer.concat(chunks).toString('utf8');
} catch (streamErr) {
err_msg = '[Error reading response stream]';
}
} else {
try {
// safe stringify to avoid circular structure errors
err_msg = JSON.stringify(data);
} catch (jsonErr) {
err_msg = String(data);
}
}
} else {
err_msg = e.message;
}
console.error(`error: ${config.provider} error: ${err_msg}`);
log(`error: ${err_msg}`);
process.exit(1);
}
}
// google provider
// endpoint: https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent
async function call_google(config: Config, model: string, prompt: string): Promise<ProviderResponse> {
const url = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${config.gemini_api_key}`;
const body: any = {
contents: [{ parts: [{ text: prompt }] }]
};
// google-specific behavior
const generationConfig: any = {};
if (config.seed !== undefined) {
generationConfig.temperature = 0;
}
if (config.max_tokens) {
generationConfig.maxOutputTokens = config.max_tokens;
}
if (Object.keys(generationConfig).length > 0) {
body.generationConfig = generationConfig;
}
const res = await axios.post(url, body, { timeout: config.timeout * 1000 });
log(JSON.stringify(res.data));
let text = '';
if (res.data.candidates && res.data.candidates[0].content.parts) {
text = res.data.candidates[0].content.parts.map((p: any) => p.text).join('');
}
const usage = res.data.usageMetadata || {};
let thinking = usage.thinkingTokenCount || 0;
if (!thinking && usage.totalTokenCount && usage.promptTokenCount && usage.candidatesTokenCount) {
thinking = usage.totalTokenCount - usage.promptTokenCount - usage.candidatesTokenCount;
}
return {
text,
usage: {
input: usage.promptTokenCount || 0,
output: usage.candidatesTokenCount || 0,
thinking
}
};
}
// anthropic provider
// endpoint: https://api.anthropic.com/v1/messages
async function call_anthropic(config: Config, model: string, prompt: string): Promise<ProviderResponse> {
const url = 'https://api.anthropic.com/v1/messages';
const body: any = {
model: model,
messages: [{ role: 'user', content: prompt }],
stream: true,
max_tokens: config.max_tokens || 8192
};
if (config.thinking_budget && config.thinking_budget > 0) {
body.thinking = { type: 'enabled', budget_tokens: config.thinking_budget };
body.temperature = 1;
} else if (config.seed !== undefined) {
body.temperature = 0;
}
const res = await axios.post(url, body, {
headers: {
'x-api-key': config.anthropic_api_key,
'anthropic-version': '2023-06-01',
'content-type': 'application/json'
},
responseType: 'stream',
timeout: config.timeout * 1000
});
let full_text = '';
let usage = { input: 0, output: 0, thinking: 0 };
let thinking_char_count = 0;
let buffer = '';
await new Promise<void>((resolve, reject) => {
res.data.on('data', (chunk: Buffer) => {
buffer += chunk.toString('utf8');
const lines = buffer.split('\n');
buffer = lines.pop() || ''; // Keep the last incomplete line in buffer
for (const line of lines) {
if (!line.trim() || line.startsWith(':')) continue;
if (line.startsWith('data: ')) {
const data_str = line.slice(6);
if (data_str === '[DONE]') continue;
try {
const data = JSON.parse(data_str);
log(JSON.stringify(data));
if (data.type === 'message_start') {
usage.input = data.message.usage.input_tokens;
} else if (data.type === 'content_block_delta') {
if (data.delta.type === 'text_delta') {
full_text += data.delta.text;
} else if (data.delta.type === 'thinking_delta') {
thinking_char_count += data.delta.thinking.length;
}
} else if (data.type === 'message_delta') {
if (data.usage) {
usage.output = data.usage.output_tokens;
}
} else if (data.type === 'error') {
reject(new Error(JSON.stringify(data.error)));
}
} catch (e) {
// ignore parse errors for incomplete chunks (though buffering should handle most)
}
}
}
});
res.data.on('end', resolve);
res.data.on('error', reject);
});
if (thinking_char_count > 0) usage.thinking = Math.ceil(thinking_char_count / 4);
return { text: full_text, usage };
}
// openai provider
// endpoint: /chat/completions at the configured openai_api_base
async function call_openai(config: Config, model: string, prompt: string): Promise<ProviderResponse> {
const url = `${config.openai_api_base}/chat/completions`;
const body: any = {
model: model,
messages: [{ role: 'user', content: prompt }]
};
if (config.seed !== undefined) body.seed = config.seed;
const is_official = config.openai_api_base.includes('api.openai.com');
if (config.max_tokens) {
if (is_official) body.max_completion_tokens = config.max_tokens;
else body.max_tokens = config.max_tokens;
}
const res = await axios.post(url, body, {
headers: { 'Authorization': `Bearer ${config.openai_api_key}` },
timeout: config.timeout * 1000
});
log(JSON.stringify(res.data));
const text = res.data.choices[0].message.content || '';
const u = res.data.usage || {};
let thinking = 0;
if (u.completion_tokens_details && u.completion_tokens_details.reasoning_tokens) thinking = u.completion_tokens_details.reasoning_tokens;
else if (u.reasoning_tokens) thinking = u.reasoning_tokens;
else if (u.thinking_tokens) thinking = u.thinking_tokens;
return {
text,
usage: {
input: u.prompt_tokens || 0,
output: u.completion_tokens || 0,
thinking
}
};
}
// output validation
function process_response(text: string): string {
const lines = text.split('\n');
if (lines.length > 0 && lines[0].trim().startsWith('```')) lines.shift();
if (lines.length > 0 && lines[lines.length - 1].trim().startsWith('```')) lines.pop();
return lines.join('\n');
}
// code generation
function detect_language(config: Config, languages_json: string): string {
const map = JSON.parse(languages_json);
const ext = path.extname(config.output_file);
if (map[ext]) return map[ext];
const base = path.basename(config.output_file);
if (map[base]) return map[base];
return ext.replace('.', '');
}
function expand_prompt(template: string, vars: Record<string, string>): string {
let result = template;
for (const [k, v] of Object.entries(vars)) {
result = result.replace(new RegExp(`{{${k}}}`, 'g'), () => v);
}
return result;
}
// execution flow
async function main() {
const main_start = Date.now();
const config = await parse_args();
if (config.show_config) {
console.log(JSON.stringify(redact_config(config), null, 2));
process.exit(0);
}
if (config.provider === 'google' && !config.gemini_api_key) {
console.error('error: gemini_api_key is required for google provider');
process.exit(1);
}
if (config.provider === 'anthropic' && !config.anthropic_api_key) {
console.error('error: anthropic_api_key is required for anthropic provider');
process.exit(1);
}
if (config.provider === 'openai' && !config.openai_api_key) {
if (!config.openai_api_base.includes('localhost') && !config.openai_api_key) {
console.error('error: openai_api_key is required for openai provider');
process.exit(1);
}
}
init_logging(config);
log(JSON.stringify(redact_config(config)));
const prompt_tmpl = load_resource(config, 'prompt.tmpl');
const languages_json = load_resource(config, 'languages.json');
const pricing_json = load_resource(config, 'pricing.json');
const english_content = fs.readFileSync(config.input_file, 'utf8');
let context_content = '';
if (config.context_files) {
for (const f of config.context_files.split(':')) {
if (f && fs.existsSync(f)) {
context_content += `### ${f}\n\n\`\`\`\n${fs.readFileSync(f, 'utf8')}\n\`\`\`\n\n`;
}
}
}
let hacking_conventions = '';
if (config.hacking_conventions && fs.existsSync(config.hacking_conventions)) {
hacking_conventions = fs.readFileSync(config.hacking_conventions, 'utf8');
}
const target_language = detect_language(config, languages_json);
let output_path_display = config.output_file;
if (path.isAbsolute(output_path_display)) output_path_display = '[REDACTED]';
const vars = {
generation_command: process.argv.slice(2).join(' ').replace('--', ''),
generation_config: JSON.stringify(redact_config(config)),
target_language,
output_path: output_path_display,
english_content,
hacking_conventions,
context_files: context_content
};
const full_prompt = expand_prompt(prompt_tmpl, vars);
log('--- prompt ---\n' + full_prompt);
console.log(`transpiling '${config.input_file}' to '${config.output_file}' (${target_language})`);
let attempts = 0;
const max_attempts = config.test_command ?
(config.test_iterations === -1 ? Infinity : config.test_iterations)
: 1;
let total_usage: TokenUsage = { input: 0, output: 0, thinking: 0 };
let current_prompt = full_prompt;
while (attempts < max_attempts) {
const response = await call_api(config, current_prompt);
total_usage.input += response.usage.input;
total_usage.output += response.usage.output;
total_usage.thinking += response.usage.thinking;
const code = process_response(response.text);
if (!code.trim()) {
console.error('error: received empty response from llm');
attempts++;
continue;
}
fs.writeFileSync(config.output_file, code);
if (!config.test_command) {
console.log(`successfully transpiled '${config.output_file}'`);
break;
}
attempts++;
console.log(`executing test command (\`${config.test_command}\`), attempt ${attempts}/${config.test_iterations === -1 ? 'inf' : max_attempts}`);
try {
const env: any = {
PATH: process.env.PATH,
RUSTUP_HOME: process.env.RUSTUP_HOME,
CARGO_HOME: process.env.CARGO_HOME
};
execSync(config.test_command, { env, stdio: 'pipe' });
console.log('test command succeeded!');
console.log(`successfully transpiled '${config.output_file}'`);
break;
} catch (e: any) {
console.log('test command failed, see log for details');
const output = (e.stdout || '') + (e.stderr || '');
log(`test failed:\n${output}`);
if (attempts >= max_attempts) {
console.error('error: tests failed after max iterations');
} else {
current_prompt = `The previous generation failed tests.\n\nCODE:\n${code}\n\nTEST COMMAND: ${config.test_command}\nEXIT CODE: ${e.status}\nOUTPUT:\n${output}\n\nPlease fix the code.`;
}
}
}
console.log('\n--- api request summary ---');
let thinking_str = '';
if (total_usage.thinking > 0) thinking_str = `, ${total_usage.thinking} thinking`;
console.log(`tokens: ${total_usage.input} input, ${total_usage.output} output${thinking_str}`);
try {
const pricing = JSON.parse(pricing_json);
const used_model = config.model ||
(config.provider === 'google' ? 'gemini-2.5-pro' :
config.provider === 'anthropic' ? 'claude-sonnet-4-20250514' : 'gpt-5-2025-08-07');
const price_key = Object.keys(pricing).find(k => k.endsWith(used_model));
if (price_key) {
const p = pricing[price_key];
const input_cost = total_usage.input * p.input_cost_per_token;
const output_cost = total_usage.output * p.output_cost_per_token;
const thinking_cost = total_usage.thinking * (p.thinking_cost_per_token || p.output_cost_per_token);
const total_cost = input_cost + output_cost + (total_usage.thinking > 0 ? thinking_cost : 0);
console.log('estimated cost:');
console.log(` - input: $${input_cost.toFixed(6)}`);
console.log(` - output: $${output_cost.toFixed(6)}`);
if (total_usage.thinking > 0) console.log(` - thinking: $${thinking_cost.toFixed(6)}`);
console.log(`total: $${total_cost.toFixed(6)}`);
}
} catch (e) {
// ignore pricing errors
}
const elapsed_total = (Date.now() - main_start) / 1000;
console.log(`elapsed time: ${elapsed_total.toFixed(2)}s`);
if (attempts > max_attempts && config.test_command) {
process.exit(1);
}
}
main().catch(err => {
console.error(err);
process.exit(1);
});