hyntx 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +39 -8
- package/dist/index.js +1130 -214
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import chalk3 from 'chalk';
|
|
2
3
|
import { readFileSync, existsSync, mkdirSync, writeFileSync, chmodSync } from 'fs';
|
|
3
4
|
import { homedir } from 'os';
|
|
4
5
|
import { join, dirname, basename } from 'path';
|
|
5
6
|
import { parseArgs } from 'util';
|
|
6
7
|
import { fileURLToPath } from 'url';
|
|
7
|
-
import chalk3 from 'chalk';
|
|
8
8
|
import ora from 'ora';
|
|
9
9
|
import { readFile } from 'fs/promises';
|
|
10
10
|
import { glob } from 'glob';
|
|
@@ -13,6 +13,7 @@ import prompts from 'prompts';
|
|
|
13
13
|
import boxen2 from 'boxen';
|
|
14
14
|
import Table from 'cli-table3';
|
|
15
15
|
import figlet from 'figlet';
|
|
16
|
+
import { z } from 'zod';
|
|
16
17
|
|
|
17
18
|
var __defProp = Object.defineProperty;
|
|
18
19
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
@@ -23,6 +24,140 @@ var __export = (target, all) => {
|
|
|
23
24
|
for (var name in all)
|
|
24
25
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
25
26
|
};
|
|
27
|
+
var Logger, logger;
|
|
28
|
+
var init_logger = __esm({
|
|
29
|
+
"src/utils/logger.ts"() {
|
|
30
|
+
Logger = class {
|
|
31
|
+
warnings = [];
|
|
32
|
+
verboseEnabled = false;
|
|
33
|
+
/**
|
|
34
|
+
* Enables or disables verbose (debug) mode.
|
|
35
|
+
*
|
|
36
|
+
* @param enabled - Whether to enable verbose mode
|
|
37
|
+
*/
|
|
38
|
+
setVerbose(enabled) {
|
|
39
|
+
this.verboseEnabled = enabled;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Returns whether verbose mode is enabled.
|
|
43
|
+
*
|
|
44
|
+
* @returns true if verbose mode is enabled
|
|
45
|
+
*/
|
|
46
|
+
isVerbose() {
|
|
47
|
+
return this.verboseEnabled;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Logs an error message to stderr.
|
|
51
|
+
*
|
|
52
|
+
* @param message - Error message
|
|
53
|
+
* @param context - Optional context (e.g., file name, operation)
|
|
54
|
+
*/
|
|
55
|
+
error(message, context) {
|
|
56
|
+
const prefix = context ? `[${context}] ` : "";
|
|
57
|
+
process.stderr.write(chalk3.red(`ERROR: ${prefix}${message}
|
|
58
|
+
`));
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Logs a warning message to stderr.
|
|
62
|
+
*
|
|
63
|
+
* @param message - Warning message
|
|
64
|
+
* @param context - Optional context (e.g., file name, operation)
|
|
65
|
+
*/
|
|
66
|
+
warn(message, context) {
|
|
67
|
+
const prefix = context ? `[${context}] ` : "";
|
|
68
|
+
process.stderr.write(chalk3.yellow(`WARN: ${prefix}${message}
|
|
69
|
+
`));
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Logs an info message to stderr.
|
|
73
|
+
*
|
|
74
|
+
* @param message - Info message
|
|
75
|
+
*/
|
|
76
|
+
info(message) {
|
|
77
|
+
process.stderr.write(chalk3.blue(`INFO: ${message}
|
|
78
|
+
`));
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Logs a debug message to stderr (only when verbose mode is enabled).
|
|
82
|
+
*
|
|
83
|
+
* @param message - Debug message
|
|
84
|
+
* @param context - Optional context
|
|
85
|
+
*/
|
|
86
|
+
debug(message, context) {
|
|
87
|
+
if (this.verboseEnabled) {
|
|
88
|
+
const prefix = context ? `[${context}] ` : "";
|
|
89
|
+
process.stderr.write(chalk3.gray(`[DEBUG] ${prefix}${message}
|
|
90
|
+
`));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Collects a warning for later reporting.
|
|
95
|
+
* Use this for non-fatal issues that should be displayed at the end of execution.
|
|
96
|
+
*
|
|
97
|
+
* @param message - Warning message
|
|
98
|
+
* @param context - Optional context (e.g., file name, operation)
|
|
99
|
+
*/
|
|
100
|
+
collectWarning(message, context) {
|
|
101
|
+
this.warnings.push({ message, context });
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Returns all collected warnings.
|
|
105
|
+
*
|
|
106
|
+
* @returns Array of collected warnings
|
|
107
|
+
*/
|
|
108
|
+
getWarnings() {
|
|
109
|
+
return [...this.warnings];
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Returns the number of collected warnings.
|
|
113
|
+
*
|
|
114
|
+
* @returns Warning count
|
|
115
|
+
*/
|
|
116
|
+
getWarningCount() {
|
|
117
|
+
return this.warnings.length;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* Clears all collected warnings.
|
|
121
|
+
*/
|
|
122
|
+
clearWarnings() {
|
|
123
|
+
this.warnings = [];
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Reports all collected warnings to stderr and clears them.
|
|
127
|
+
* Does nothing if there are no warnings.
|
|
128
|
+
*/
|
|
129
|
+
reportWarnings() {
|
|
130
|
+
if (this.warnings.length === 0) {
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
process.stderr.write(
|
|
134
|
+
chalk3.yellow(`
|
|
135
|
+
\u26A0\uFE0F ${String(this.warnings.length)} warning(s):
|
|
136
|
+
`)
|
|
137
|
+
);
|
|
138
|
+
for (const warning of this.warnings) {
|
|
139
|
+
const prefix = warning.context ? `[${warning.context}] ` : "";
|
|
140
|
+
process.stderr.write(chalk3.yellow(` - ${prefix}${warning.message}
|
|
141
|
+
`));
|
|
142
|
+
}
|
|
143
|
+
this.clearWarnings();
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Formats collected warnings as plain text (without ANSI colors).
|
|
147
|
+
* Useful for JSON output or testing.
|
|
148
|
+
*
|
|
149
|
+
* @returns Array of formatted warning strings
|
|
150
|
+
*/
|
|
151
|
+
formatWarnings() {
|
|
152
|
+
return this.warnings.map((w) => {
|
|
153
|
+
const prefix = w.context ? `[${w.context}] ` : "";
|
|
154
|
+
return `${prefix}${w.message}`;
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
logger = new Logger();
|
|
159
|
+
}
|
|
160
|
+
});
|
|
26
161
|
|
|
27
162
|
// src/utils/shell-config.ts
|
|
28
163
|
var shell_config_exports = {};
|
|
@@ -128,12 +263,23 @@ ${configBlock}${after}`.trim() + "\n";
|
|
|
128
263
|
}
|
|
129
264
|
try {
|
|
130
265
|
mkdirSync(dirname(configFile), { recursive: true });
|
|
131
|
-
} catch {
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (error instanceof Error && !error.message.includes("EEXIST") && !error.code?.includes("EEXIST")) {
|
|
268
|
+
logger.debug(
|
|
269
|
+
`Directory creation note: ${error.message}`,
|
|
270
|
+
"shell-config"
|
|
271
|
+
);
|
|
272
|
+
}
|
|
132
273
|
}
|
|
133
274
|
writeFileSync(configFile, content, "utf-8");
|
|
134
275
|
try {
|
|
135
276
|
chmodSync(configFile, 384);
|
|
136
|
-
} catch {
|
|
277
|
+
} catch (error) {
|
|
278
|
+
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
279
|
+
logger.collectWarning(
|
|
280
|
+
`Could not set restrictive permissions on ${configFile}: ${errorMessage}`,
|
|
281
|
+
"shell-config"
|
|
282
|
+
);
|
|
137
283
|
}
|
|
138
284
|
return {
|
|
139
285
|
success: true,
|
|
@@ -173,6 +319,7 @@ function getManualInstructions(config) {
|
|
|
173
319
|
}
|
|
174
320
|
var init_shell_config = __esm({
|
|
175
321
|
"src/utils/shell-config.ts"() {
|
|
322
|
+
init_logger();
|
|
176
323
|
}
|
|
177
324
|
});
|
|
178
325
|
|
|
@@ -344,6 +491,7 @@ function validateLogEntry(entry) {
|
|
|
344
491
|
}
|
|
345
492
|
|
|
346
493
|
// src/core/log-reader.ts
|
|
494
|
+
init_logger();
|
|
347
495
|
function claudeProjectsExist() {
|
|
348
496
|
return existsSync(CLAUDE_PROJECTS_DIR);
|
|
349
497
|
}
|
|
@@ -387,18 +535,25 @@ function extractDate(timestamp) {
|
|
|
387
535
|
return "unknown";
|
|
388
536
|
}
|
|
389
537
|
}
|
|
390
|
-
function parseLine(line) {
|
|
538
|
+
function parseLine(line, lineNumber, filePath) {
|
|
391
539
|
if (!line.trim()) {
|
|
392
540
|
return null;
|
|
393
541
|
}
|
|
542
|
+
const context = lineNumber !== void 0 && filePath ? `${filePath}:${String(lineNumber)}` : void 0;
|
|
394
543
|
try {
|
|
395
544
|
const parsed = JSON.parse(line);
|
|
396
545
|
const validation = validateLogEntry(parsed);
|
|
397
546
|
if (!validation.isValid) {
|
|
547
|
+
logger.debug(
|
|
548
|
+
`Schema validation failed: ${validation.warning ?? "Unknown format"}`,
|
|
549
|
+
context
|
|
550
|
+
);
|
|
398
551
|
return null;
|
|
399
552
|
}
|
|
400
553
|
return parsed;
|
|
401
|
-
} catch {
|
|
554
|
+
} catch (error) {
|
|
555
|
+
const errorMessage = error instanceof Error ? error.message : "Parse error";
|
|
556
|
+
logger.debug(`JSON parse failed: ${errorMessage}`, context);
|
|
402
557
|
return null;
|
|
403
558
|
}
|
|
404
559
|
}
|
|
@@ -419,12 +574,14 @@ async function readJsonlFile(filePath) {
|
|
|
419
574
|
try {
|
|
420
575
|
const content = await readFile(filePath, "utf-8");
|
|
421
576
|
const lines = content.split("\n");
|
|
577
|
+
let skippedLines = 0;
|
|
422
578
|
for (let i = 0; i < lines.length; i++) {
|
|
423
579
|
const line = lines[i] ?? "";
|
|
424
|
-
const
|
|
580
|
+
const lineNumber = i + 1;
|
|
581
|
+
const message = parseLine(line, lineNumber, filePath);
|
|
425
582
|
if (message === null) {
|
|
426
583
|
if (line.trim()) {
|
|
427
|
-
|
|
584
|
+
skippedLines++;
|
|
428
585
|
}
|
|
429
586
|
continue;
|
|
430
587
|
}
|
|
@@ -443,9 +600,16 @@ async function readJsonlFile(filePath) {
|
|
|
443
600
|
date: extractDate(message.timestamp)
|
|
444
601
|
});
|
|
445
602
|
}
|
|
603
|
+
if (skippedLines > 0) {
|
|
604
|
+
const warning = `Skipped ${String(skippedLines)} invalid line(s) in ${filePath}`;
|
|
605
|
+
warnings.push(warning);
|
|
606
|
+
logger.collectWarning(warning, "log-reader");
|
|
607
|
+
}
|
|
446
608
|
} catch (error) {
|
|
447
609
|
const errorMessage = error instanceof Error ? error.message : "Unknown error";
|
|
448
|
-
|
|
610
|
+
const warning = `Failed to read ${filePath}: ${errorMessage}`;
|
|
611
|
+
warnings.push(warning);
|
|
612
|
+
logger.error(warning, "log-reader");
|
|
449
613
|
}
|
|
450
614
|
return { prompts: prompts2, warnings };
|
|
451
615
|
}
|
|
@@ -477,7 +641,9 @@ function filterByProject(prompts2, projectName) {
|
|
|
477
641
|
);
|
|
478
642
|
}
|
|
479
643
|
async function readLogs(options) {
|
|
644
|
+
logger.debug(`Scanning ${CLAUDE_PROJECTS_DIR}`, "log-reader");
|
|
480
645
|
if (!claudeProjectsExist()) {
|
|
646
|
+
logger.debug("Claude projects directory not found", "log-reader");
|
|
481
647
|
return {
|
|
482
648
|
prompts: [],
|
|
483
649
|
warnings: [
|
|
@@ -487,6 +653,7 @@ async function readLogs(options) {
|
|
|
487
653
|
}
|
|
488
654
|
const pattern = `${CLAUDE_PROJECTS_DIR}/**/*.jsonl`;
|
|
489
655
|
const files = await glob(pattern);
|
|
656
|
+
logger.debug(`Found ${String(files.length)} JSONL files`, "log-reader");
|
|
490
657
|
if (files.length === 0) {
|
|
491
658
|
return {
|
|
492
659
|
prompts: [],
|
|
@@ -500,6 +667,10 @@ async function readLogs(options) {
|
|
|
500
667
|
allPrompts.push(...prompts2);
|
|
501
668
|
allWarnings.push(...warnings);
|
|
502
669
|
}
|
|
670
|
+
logger.debug(
|
|
671
|
+
`Parsed ${String(allPrompts.length)} total prompts from all files`,
|
|
672
|
+
"log-reader"
|
|
673
|
+
);
|
|
503
674
|
let filteredPrompts = allPrompts;
|
|
504
675
|
if (options) {
|
|
505
676
|
if (options.from && options.to) {
|
|
@@ -539,6 +710,15 @@ async function readLogs(options) {
|
|
|
539
710
|
filteredPrompts = filterByProject(filteredPrompts, options.project);
|
|
540
711
|
}
|
|
541
712
|
}
|
|
713
|
+
if (options) {
|
|
714
|
+
const filtered = allPrompts.length - filteredPrompts.length;
|
|
715
|
+
if (filtered > 0) {
|
|
716
|
+
logger.debug(
|
|
717
|
+
`Filtered ${String(filtered)} prompts (${String(filteredPrompts.length)} remaining)`,
|
|
718
|
+
"log-reader"
|
|
719
|
+
);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
542
722
|
const sortedPrompts = filteredPrompts.sort((a, b) => {
|
|
543
723
|
try {
|
|
544
724
|
const dateA = parseISO(a.timestamp);
|
|
@@ -548,6 +728,10 @@ async function readLogs(options) {
|
|
|
548
728
|
return 0;
|
|
549
729
|
}
|
|
550
730
|
});
|
|
731
|
+
logger.debug(
|
|
732
|
+
`Returning ${String(sortedPrompts.length)} prompts for analysis`,
|
|
733
|
+
"log-reader"
|
|
734
|
+
);
|
|
551
735
|
return {
|
|
552
736
|
prompts: sortedPrompts,
|
|
553
737
|
warnings: allWarnings
|
|
@@ -736,6 +920,7 @@ async function runSetup() {
|
|
|
736
920
|
}
|
|
737
921
|
|
|
738
922
|
// src/core/sanitizer.ts
|
|
923
|
+
init_logger();
|
|
739
924
|
function redactOpenAIKeys(text) {
|
|
740
925
|
return text.replace(/sk-[a-zA-Z0-9]{48,}/g, "[REDACTED_OPENAI_KEY]");
|
|
741
926
|
}
|
|
@@ -950,6 +1135,10 @@ function sanitizePrompts(prompts2) {
|
|
|
950
1135
|
if (prompts2.length === 0) {
|
|
951
1136
|
return { prompts: [], totalRedacted: 0 };
|
|
952
1137
|
}
|
|
1138
|
+
logger.debug(
|
|
1139
|
+
`Sanitizing ${String(prompts2.length)} prompts for secrets`,
|
|
1140
|
+
"sanitizer"
|
|
1141
|
+
);
|
|
953
1142
|
const sanitizedPrompts = [];
|
|
954
1143
|
let totalRedacted = 0;
|
|
955
1144
|
for (const prompt of prompts2) {
|
|
@@ -957,6 +1146,14 @@ function sanitizePrompts(prompts2) {
|
|
|
957
1146
|
sanitizedPrompts.push(result.text);
|
|
958
1147
|
totalRedacted += result.redacted;
|
|
959
1148
|
}
|
|
1149
|
+
if (totalRedacted > 0) {
|
|
1150
|
+
logger.debug(
|
|
1151
|
+
`Redacted ${String(totalRedacted)} secret(s) from prompts`,
|
|
1152
|
+
"sanitizer"
|
|
1153
|
+
);
|
|
1154
|
+
} else {
|
|
1155
|
+
logger.debug("No secrets found to redact", "sanitizer");
|
|
1156
|
+
}
|
|
960
1157
|
return {
|
|
961
1158
|
prompts: sanitizedPrompts,
|
|
962
1159
|
totalRedacted
|
|
@@ -964,6 +1161,7 @@ function sanitizePrompts(prompts2) {
|
|
|
964
1161
|
}
|
|
965
1162
|
|
|
966
1163
|
// src/core/analyzer.ts
|
|
1164
|
+
init_logger();
|
|
967
1165
|
var SYSTEM_OVERHEAD_TOKENS = 2e3;
|
|
968
1166
|
var SEVERITY_RANK = {
|
|
969
1167
|
high: 3,
|
|
@@ -1144,18 +1342,36 @@ function mergeBatchResults(options) {
|
|
|
1144
1342
|
};
|
|
1145
1343
|
}
|
|
1146
1344
|
async function analyzePrompts(options) {
|
|
1147
|
-
const { provider, prompts: prompts2, date, onProgress } = options;
|
|
1345
|
+
const { provider, prompts: prompts2, date, context, onProgress } = options;
|
|
1346
|
+
logger.debug(
|
|
1347
|
+
`Starting analysis of ${String(prompts2.length)} prompts for ${date}`,
|
|
1348
|
+
"analyzer"
|
|
1349
|
+
);
|
|
1148
1350
|
if (prompts2.length === 0) {
|
|
1149
1351
|
throw new Error("Cannot analyze empty prompts array");
|
|
1150
1352
|
}
|
|
1151
|
-
const { prompts: sanitizedPrompts } = sanitizePrompts(prompts2);
|
|
1353
|
+
const { prompts: sanitizedPrompts, totalRedacted } = sanitizePrompts(prompts2);
|
|
1354
|
+
if (totalRedacted > 0) {
|
|
1355
|
+
logger.debug(
|
|
1356
|
+
`Sanitizer redacted ${String(totalRedacted)} secrets`,
|
|
1357
|
+
"analyzer"
|
|
1358
|
+
);
|
|
1359
|
+
}
|
|
1152
1360
|
const providerType = inferProviderType(provider.name);
|
|
1153
1361
|
const limits = PROVIDER_LIMITS[providerType];
|
|
1362
|
+
logger.debug(
|
|
1363
|
+
`Using provider type: ${providerType} (limit: ${String(limits.maxTokensPerBatch)} tokens/batch)`,
|
|
1364
|
+
"analyzer"
|
|
1365
|
+
);
|
|
1154
1366
|
const batches = batchPrompts({
|
|
1155
1367
|
prompts: sanitizedPrompts,
|
|
1156
1368
|
maxTokensPerBatch: limits.maxTokensPerBatch,
|
|
1157
1369
|
prioritization: limits.prioritization
|
|
1158
1370
|
});
|
|
1371
|
+
logger.debug(
|
|
1372
|
+
`Created ${String(batches.length)} batch(es) for analysis`,
|
|
1373
|
+
"analyzer"
|
|
1374
|
+
);
|
|
1159
1375
|
if (batches.length === 1) {
|
|
1160
1376
|
const batch = batches[0];
|
|
1161
1377
|
if (!batch) {
|
|
@@ -1164,10 +1380,21 @@ async function analyzePrompts(options) {
|
|
|
1164
1380
|
if (onProgress) {
|
|
1165
1381
|
onProgress(0, 1);
|
|
1166
1382
|
}
|
|
1167
|
-
|
|
1383
|
+
logger.debug(
|
|
1384
|
+
`Processing single batch (${String(batch.tokens)} tokens)`,
|
|
1385
|
+
"analyzer"
|
|
1386
|
+
);
|
|
1387
|
+
const startTime = Date.now();
|
|
1388
|
+
const result = await provider.analyze(batch.prompts, date, context);
|
|
1389
|
+
const elapsed = Date.now() - startTime;
|
|
1390
|
+
logger.debug(`Batch completed in ${String(elapsed)}ms`, "analyzer");
|
|
1168
1391
|
if (onProgress) {
|
|
1169
1392
|
onProgress(1, 1);
|
|
1170
1393
|
}
|
|
1394
|
+
logger.debug(
|
|
1395
|
+
`Analysis complete: ${String(result.patterns.length)} patterns found`,
|
|
1396
|
+
"analyzer"
|
|
1397
|
+
);
|
|
1171
1398
|
return result;
|
|
1172
1399
|
}
|
|
1173
1400
|
const results = [];
|
|
@@ -1178,13 +1405,29 @@ async function analyzePrompts(options) {
|
|
|
1178
1405
|
if (onProgress) {
|
|
1179
1406
|
onProgress(i, totalBatches);
|
|
1180
1407
|
}
|
|
1181
|
-
|
|
1408
|
+
logger.debug(
|
|
1409
|
+
`Processing batch ${String(i + 1)}/${String(totalBatches)} (${String(batch.tokens)} tokens)`,
|
|
1410
|
+
"analyzer"
|
|
1411
|
+
);
|
|
1412
|
+
const startTime = Date.now();
|
|
1413
|
+
const result = await provider.analyze(batch.prompts, date, context);
|
|
1182
1414
|
results.push(result);
|
|
1415
|
+
const elapsed = Date.now() - startTime;
|
|
1416
|
+
logger.debug(
|
|
1417
|
+
`Batch ${String(i + 1)}/${String(totalBatches)} completed in ${String(elapsed)}ms`,
|
|
1418
|
+
"analyzer"
|
|
1419
|
+
);
|
|
1183
1420
|
}
|
|
1184
1421
|
if (onProgress) {
|
|
1185
1422
|
onProgress(totalBatches, totalBatches);
|
|
1186
1423
|
}
|
|
1187
|
-
|
|
1424
|
+
logger.debug(`Merging ${String(results.length)} batch results`, "analyzer");
|
|
1425
|
+
const mergedResult = mergeBatchResults({ results, date });
|
|
1426
|
+
logger.debug(
|
|
1427
|
+
`Analysis complete: ${String(mergedResult.patterns.length)} patterns found`,
|
|
1428
|
+
"analyzer"
|
|
1429
|
+
);
|
|
1430
|
+
return mergedResult;
|
|
1188
1431
|
}
|
|
1189
1432
|
function severityIcon(severity) {
|
|
1190
1433
|
const icons = {
|
|
@@ -1343,6 +1586,15 @@ function printReport(result, options) {
|
|
|
1343
1586
|
output.push(chalk3.dim(`Analysis Date: ${result.date}`));
|
|
1344
1587
|
console.log(output.join("\n"));
|
|
1345
1588
|
}
|
|
1589
|
+
function formatJson(result, compact = false) {
|
|
1590
|
+
return compact ? JSON.stringify(result) : JSON.stringify(result, null, 2);
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1593
|
+
// src/providers/index.ts
|
|
1594
|
+
init_logger();
|
|
1595
|
+
|
|
1596
|
+
// src/providers/ollama.ts
|
|
1597
|
+
init_logger();
|
|
1346
1598
|
|
|
1347
1599
|
// src/providers/base.ts
|
|
1348
1600
|
var SYSTEM_PROMPT = `You are an AI prompt quality analyzer. Your task is to analyze user prompts to Claude Code and identify patterns that could be improved for clarity, specificity, and effectiveness.
|
|
@@ -1380,14 +1632,43 @@ Guidelines:
|
|
|
1380
1632
|
- topSuggestion should be the most impactful single change
|
|
1381
1633
|
- If no issues found, return empty patterns array with score 100
|
|
1382
1634
|
- Be constructive and specific in suggestions`;
|
|
1383
|
-
function buildUserPrompt(prompts2, date) {
|
|
1635
|
+
function buildUserPrompt(prompts2, date, context) {
|
|
1384
1636
|
if (prompts2.length === 0) {
|
|
1385
1637
|
throw new Error("Cannot build prompt from empty array");
|
|
1386
1638
|
}
|
|
1387
1639
|
const promptsList = prompts2.map((prompt, index) => `${String(index + 1)}. ${prompt}`).join("\n\n");
|
|
1388
1640
|
const count = String(prompts2.length);
|
|
1389
1641
|
const plural = prompts2.length === 1 ? "" : "s";
|
|
1390
|
-
|
|
1642
|
+
let contextSection = "";
|
|
1643
|
+
if (context) {
|
|
1644
|
+
const contextParts = [];
|
|
1645
|
+
if (context.role) {
|
|
1646
|
+
contextParts.push(`Role: ${context.role}`);
|
|
1647
|
+
}
|
|
1648
|
+
if (context.projectType) {
|
|
1649
|
+
contextParts.push(`Project Type: ${context.projectType}`);
|
|
1650
|
+
}
|
|
1651
|
+
if (context.domain) {
|
|
1652
|
+
contextParts.push(`Domain: ${context.domain}`);
|
|
1653
|
+
}
|
|
1654
|
+
if (context.techStack && context.techStack.length > 0) {
|
|
1655
|
+
contextParts.push(`Tech Stack: ${context.techStack.join(", ")}`);
|
|
1656
|
+
}
|
|
1657
|
+
if (context.guidelines && context.guidelines.length > 0) {
|
|
1658
|
+
contextParts.push(
|
|
1659
|
+
`Guidelines:
|
|
1660
|
+
${context.guidelines.map((g) => `- ${g}`).join("\n")}`
|
|
1661
|
+
);
|
|
1662
|
+
}
|
|
1663
|
+
if (contextParts.length > 0) {
|
|
1664
|
+
contextSection = `
|
|
1665
|
+
|
|
1666
|
+
Project Context:
|
|
1667
|
+
${contextParts.join("\n")}
|
|
1668
|
+
`;
|
|
1669
|
+
}
|
|
1670
|
+
}
|
|
1671
|
+
return `Analyze the following ${count} prompt${plural} from ${date}:${contextSection}
|
|
1391
1672
|
|
|
1392
1673
|
${promptsList}
|
|
1393
1674
|
|
|
@@ -1487,6 +1768,7 @@ var OllamaProvider = class {
|
|
|
1487
1768
|
* @returns Promise that resolves to true if available, false otherwise
|
|
1488
1769
|
*/
|
|
1489
1770
|
async isAvailable() {
|
|
1771
|
+
logger.debug(`Connecting to Ollama at ${this.config.host}`, "ollama");
|
|
1490
1772
|
try {
|
|
1491
1773
|
const controller = new AbortController();
|
|
1492
1774
|
const timeoutId = setTimeout(() => {
|
|
@@ -1497,16 +1779,34 @@ var OllamaProvider = class {
|
|
|
1497
1779
|
});
|
|
1498
1780
|
clearTimeout(timeoutId);
|
|
1499
1781
|
if (!response.ok) {
|
|
1782
|
+
logger.debug(
|
|
1783
|
+
`Ollama API returned ${String(response.status)}`,
|
|
1784
|
+
"ollama"
|
|
1785
|
+
);
|
|
1500
1786
|
return false;
|
|
1501
1787
|
}
|
|
1502
1788
|
const data = await response.json();
|
|
1503
1789
|
if (!data.models || !Array.isArray(data.models)) {
|
|
1790
|
+
logger.debug("Ollama returned invalid model list", "ollama");
|
|
1504
1791
|
return false;
|
|
1505
1792
|
}
|
|
1506
|
-
|
|
1793
|
+
const modelAvailable = data.models.some(
|
|
1507
1794
|
(model) => model.name.includes(this.config.model)
|
|
1508
1795
|
);
|
|
1796
|
+
if (modelAvailable) {
|
|
1797
|
+
logger.debug(
|
|
1798
|
+
`Model ${this.config.model} available (${String(data.models.length)} models found)`,
|
|
1799
|
+
"ollama"
|
|
1800
|
+
);
|
|
1801
|
+
} else {
|
|
1802
|
+
logger.debug(
|
|
1803
|
+
`Model ${this.config.model} not found in available models`,
|
|
1804
|
+
"ollama"
|
|
1805
|
+
);
|
|
1806
|
+
}
|
|
1807
|
+
return modelAvailable;
|
|
1509
1808
|
} catch {
|
|
1809
|
+
logger.debug("Ollama connection failed", "ollama");
|
|
1510
1810
|
return false;
|
|
1511
1811
|
}
|
|
1512
1812
|
}
|
|
@@ -1516,14 +1816,15 @@ var OllamaProvider = class {
|
|
|
1516
1816
|
*
|
|
1517
1817
|
* @param prompts - Array of prompt strings to analyze
|
|
1518
1818
|
* @param date - Date context for the analysis
|
|
1819
|
+
* @param context - Optional project context for analysis
|
|
1519
1820
|
* @returns Promise resolving to AnalysisResult
|
|
1520
1821
|
* @throws Error if analysis fails after retries or if response is invalid
|
|
1521
1822
|
*/
|
|
1522
|
-
async analyze(prompts2, date) {
|
|
1823
|
+
async analyze(prompts2, date, context) {
|
|
1523
1824
|
if (prompts2.length === 0) {
|
|
1524
1825
|
throw new Error("Cannot analyze empty prompts array");
|
|
1525
1826
|
}
|
|
1526
|
-
const userPrompt = buildUserPrompt(prompts2, date);
|
|
1827
|
+
const userPrompt = buildUserPrompt(prompts2, date, context);
|
|
1527
1828
|
let lastError;
|
|
1528
1829
|
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
|
1529
1830
|
try {
|
|
@@ -1568,6 +1869,10 @@ var OllamaProvider = class {
|
|
|
1568
1869
|
break;
|
|
1569
1870
|
}
|
|
1570
1871
|
const delay = BASE_RETRY_DELAY_MS * Math.pow(2, attempt);
|
|
1872
|
+
logger.debug(
|
|
1873
|
+
`Retry attempt ${String(attempt + 1)}/${String(MAX_RETRIES)}, waiting ${String(delay)}ms`,
|
|
1874
|
+
"ollama"
|
|
1875
|
+
);
|
|
1571
1876
|
await sleep(delay);
|
|
1572
1877
|
}
|
|
1573
1878
|
}
|
|
@@ -1582,16 +1887,100 @@ function sleep(ms) {
|
|
|
1582
1887
|
}
|
|
1583
1888
|
|
|
1584
1889
|
// src/providers/anthropic.ts
|
|
1585
|
-
|
|
1890
|
+
init_logger();
|
|
1891
|
+
|
|
1892
|
+
// src/utils/rate-limiter.ts
|
|
1893
|
+
function createRateLimiter(options) {
|
|
1894
|
+
const minIntervalMs = 6e4 / options.requestsPerMinute;
|
|
1895
|
+
let lastRequestTime = 0;
|
|
1896
|
+
async function throttle(fn) {
|
|
1897
|
+
const now = Date.now();
|
|
1898
|
+
const timeSinceLastRequest = now - lastRequestTime;
|
|
1899
|
+
if (lastRequestTime > 0 && timeSinceLastRequest < minIntervalMs) {
|
|
1900
|
+
const waitTime = minIntervalMs - timeSinceLastRequest;
|
|
1901
|
+
await new Promise((resolve) => setTimeout(resolve, waitTime));
|
|
1902
|
+
}
|
|
1903
|
+
lastRequestTime = Date.now();
|
|
1904
|
+
return fn();
|
|
1905
|
+
}
|
|
1906
|
+
function reset() {
|
|
1907
|
+
lastRequestTime = 0;
|
|
1908
|
+
}
|
|
1909
|
+
return { throttle, reset };
|
|
1910
|
+
}
|
|
1911
|
+
var DEFAULT_RATE_LIMITS = {
|
|
1912
|
+
anthropic: 50,
|
|
1913
|
+
google: 50
|
|
1914
|
+
};
|
|
1915
|
+
|
|
1916
|
+
// src/utils/retry.ts
|
|
1917
|
+
var DEFAULT_OPTIONS = {
|
|
1918
|
+
maxRetries: 3,
|
|
1919
|
+
baseDelayMs: 1e3,
|
|
1920
|
+
maxDelayMs: 3e4,
|
|
1921
|
+
isRetryable: isTransientError
|
|
1922
|
+
};
|
|
1923
|
+
function isTransientError(error) {
|
|
1924
|
+
if (!(error instanceof Error)) {
|
|
1925
|
+
return false;
|
|
1926
|
+
}
|
|
1927
|
+
const message = error.message.toLowerCase();
|
|
1928
|
+
if (message.includes("network") || message.includes("timeout") || message.includes("econnreset") || message.includes("econnrefused") || message.includes("enotfound") || message.includes("abort")) {
|
|
1929
|
+
return true;
|
|
1930
|
+
}
|
|
1931
|
+
if (message.includes("500") || message.includes("502") || message.includes("503") || message.includes("504")) {
|
|
1932
|
+
return true;
|
|
1933
|
+
}
|
|
1934
|
+
if (message.includes("429")) {
|
|
1935
|
+
return true;
|
|
1936
|
+
}
|
|
1937
|
+
if (message.includes("401") || message.includes("403")) {
|
|
1938
|
+
return false;
|
|
1939
|
+
}
|
|
1940
|
+
if (message.includes("parse") || message.includes("schema")) {
|
|
1941
|
+
return false;
|
|
1942
|
+
}
|
|
1943
|
+
return false;
|
|
1944
|
+
}
|
|
1945
|
+
function sleep2(ms) {
|
|
1946
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1947
|
+
}
|
|
1948
|
+
async function withRetry(fn, options = {}) {
|
|
1949
|
+
const opts = { ...DEFAULT_OPTIONS, ...options };
|
|
1950
|
+
let lastError;
|
|
1951
|
+
for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {
|
|
1952
|
+
try {
|
|
1953
|
+
return await fn();
|
|
1954
|
+
} catch (error) {
|
|
1955
|
+
lastError = error;
|
|
1956
|
+
const isLastAttempt = attempt === opts.maxRetries;
|
|
1957
|
+
const shouldRetry = opts.isRetryable(error);
|
|
1958
|
+
if (isLastAttempt || !shouldRetry) {
|
|
1959
|
+
throw error;
|
|
1960
|
+
}
|
|
1961
|
+
const delay = Math.min(
|
|
1962
|
+
opts.baseDelayMs * Math.pow(2, attempt),
|
|
1963
|
+
opts.maxDelayMs
|
|
1964
|
+
);
|
|
1965
|
+
await sleep2(delay);
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
throw lastError;
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1971
|
+
// src/providers/anthropic.ts
|
|
1972
|
+
var MAX_RETRIES2 = 3;
|
|
1586
1973
|
var AVAILABILITY_TIMEOUT_MS2 = 5e3;
|
|
1587
1974
|
var ANALYSIS_TIMEOUT_MS2 = 6e4;
|
|
1588
|
-
var
|
|
1975
|
+
var BASE_DELAY_MS = 1e3;
|
|
1976
|
+
var MAX_DELAY_MS = 3e4;
|
|
1589
1977
|
var API_BASE_URL = "https://api.anthropic.com";
|
|
1590
1978
|
var API_VERSION = "2023-06-01";
|
|
1591
1979
|
var MAX_TOKENS = 4096;
|
|
1592
1980
|
var AnthropicProvider = class {
|
|
1593
1981
|
name = "Anthropic";
|
|
1594
1982
|
config;
|
|
1983
|
+
rateLimiter;
|
|
1595
1984
|
/**
|
|
1596
1985
|
* Creates a new AnthropicProvider instance.
|
|
1597
1986
|
*
|
|
@@ -1599,6 +1988,9 @@ var AnthropicProvider = class {
|
|
|
1599
1988
|
*/
|
|
1600
1989
|
constructor(config) {
|
|
1601
1990
|
this.config = config;
|
|
1991
|
+
this.rateLimiter = createRateLimiter({
|
|
1992
|
+
requestsPerMinute: DEFAULT_RATE_LIMITS.anthropic
|
|
1993
|
+
});
|
|
1602
1994
|
}
|
|
1603
1995
|
/**
|
|
1604
1996
|
* Checks if the Anthropic API is available by validating the API key.
|
|
@@ -1608,8 +2000,13 @@ var AnthropicProvider = class {
|
|
|
1608
2000
|
*/
|
|
1609
2001
|
async isAvailable() {
|
|
1610
2002
|
if (!this.config.apiKey) {
|
|
2003
|
+
logger.debug("No API key configured", "anthropic");
|
|
1611
2004
|
return false;
|
|
1612
2005
|
}
|
|
2006
|
+
logger.debug(
|
|
2007
|
+
`Validating API key with model ${this.config.model}`,
|
|
2008
|
+
"anthropic"
|
|
2009
|
+
);
|
|
1613
2010
|
try {
|
|
1614
2011
|
const controller = new AbortController();
|
|
1615
2012
|
const timeoutId = setTimeout(() => {
|
|
@@ -1630,97 +2027,98 @@ var AnthropicProvider = class {
|
|
|
1630
2027
|
signal: controller.signal
|
|
1631
2028
|
});
|
|
1632
2029
|
clearTimeout(timeoutId);
|
|
1633
|
-
|
|
2030
|
+
const isAvailable = response.ok || response.status === 429 || response.status === 400;
|
|
2031
|
+
logger.debug(
|
|
2032
|
+
`API responded with status ${String(response.status)} (available: ${String(isAvailable)})`,
|
|
2033
|
+
"anthropic"
|
|
2034
|
+
);
|
|
2035
|
+
return isAvailable;
|
|
1634
2036
|
} catch {
|
|
2037
|
+
logger.debug("Connection failed", "anthropic");
|
|
1635
2038
|
return false;
|
|
1636
2039
|
}
|
|
1637
2040
|
}
|
|
1638
2041
|
/**
|
|
1639
2042
|
* Analyzes prompts using the Anthropic Claude API.
|
|
1640
2043
|
* Implements retry logic with exponential backoff for network errors.
|
|
2044
|
+
* Rate limited to prevent 429 errors during batch processing.
|
|
1641
2045
|
*
|
|
1642
2046
|
* @param prompts - Array of prompt strings to analyze
|
|
1643
2047
|
* @param date - Date context for the analysis
|
|
2048
|
+
* @param context - Optional project context for analysis
|
|
1644
2049
|
* @returns Promise resolving to AnalysisResult
|
|
1645
2050
|
* @throws Error if analysis fails after retries or if response is invalid
|
|
1646
2051
|
*/
|
|
1647
|
-
async analyze(prompts2, date) {
|
|
2052
|
+
async analyze(prompts2, date, context) {
|
|
1648
2053
|
if (prompts2.length === 0) {
|
|
1649
2054
|
throw new Error("Cannot analyze empty prompts array");
|
|
1650
2055
|
}
|
|
1651
|
-
const userPrompt = buildUserPrompt(prompts2, date);
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
break;
|
|
2056
|
+
const userPrompt = buildUserPrompt(prompts2, date, context);
|
|
2057
|
+
return this.rateLimiter.throttle(
|
|
2058
|
+
() => withRetry(
|
|
2059
|
+
async () => {
|
|
2060
|
+
const controller = new AbortController();
|
|
2061
|
+
const timeoutId = setTimeout(() => {
|
|
2062
|
+
controller.abort();
|
|
2063
|
+
}, ANALYSIS_TIMEOUT_MS2);
|
|
2064
|
+
try {
|
|
2065
|
+
const response = await fetch(`${API_BASE_URL}/v1/messages`, {
|
|
2066
|
+
method: "POST",
|
|
2067
|
+
headers: {
|
|
2068
|
+
"Content-Type": "application/json",
|
|
2069
|
+
"x-api-key": this.config.apiKey,
|
|
2070
|
+
"anthropic-version": API_VERSION
|
|
2071
|
+
},
|
|
2072
|
+
body: JSON.stringify({
|
|
2073
|
+
model: this.config.model,
|
|
2074
|
+
max_tokens: MAX_TOKENS,
|
|
2075
|
+
system: SYSTEM_PROMPT,
|
|
2076
|
+
messages: [{ role: "user", content: userPrompt }]
|
|
2077
|
+
}),
|
|
2078
|
+
signal: controller.signal
|
|
2079
|
+
});
|
|
2080
|
+
if (!response.ok) {
|
|
2081
|
+
const status = String(response.status);
|
|
2082
|
+
const errorBody = await response.text();
|
|
2083
|
+
throw new Error(
|
|
2084
|
+
`Anthropic API request failed: ${status} ${response.statusText} - ${errorBody}`
|
|
2085
|
+
);
|
|
2086
|
+
}
|
|
2087
|
+
const data = await response.json();
|
|
2088
|
+
const textContent = data.content?.find(
|
|
2089
|
+
(block) => block.type === "text"
|
|
2090
|
+
);
|
|
2091
|
+
if (!textContent?.text) {
|
|
2092
|
+
throw new Error("Invalid response format from Anthropic API");
|
|
2093
|
+
}
|
|
2094
|
+
return parseResponse(textContent.text, date);
|
|
2095
|
+
} finally {
|
|
2096
|
+
clearTimeout(timeoutId);
|
|
2097
|
+
}
|
|
2098
|
+
},
|
|
2099
|
+
{
|
|
2100
|
+
maxRetries: MAX_RETRIES2,
|
|
2101
|
+
baseDelayMs: BASE_DELAY_MS,
|
|
2102
|
+
maxDelayMs: MAX_DELAY_MS,
|
|
2103
|
+
isRetryable: isTransientError
|
|
1700
2104
|
}
|
|
1701
|
-
|
|
1702
|
-
await sleep2(delay);
|
|
1703
|
-
}
|
|
1704
|
-
}
|
|
1705
|
-
const attempts = String(MAX_RETRIES2 + 1);
|
|
1706
|
-
throw new Error(
|
|
1707
|
-
`Anthropic analysis failed after ${attempts} attempts: ${lastError?.message ?? "Unknown error"}`
|
|
2105
|
+
)
|
|
1708
2106
|
);
|
|
1709
2107
|
}
|
|
1710
2108
|
};
|
|
1711
|
-
function sleep2(ms) {
|
|
1712
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1713
|
-
}
|
|
1714
2109
|
|
|
1715
2110
|
// src/providers/google.ts
|
|
1716
|
-
|
|
2111
|
+
init_logger();
|
|
2112
|
+
var MAX_RETRIES3 = 3;
|
|
1717
2113
|
var AVAILABILITY_TIMEOUT_MS3 = 5e3;
|
|
1718
2114
|
var ANALYSIS_TIMEOUT_MS3 = 6e4;
|
|
1719
|
-
var
|
|
2115
|
+
var BASE_DELAY_MS2 = 1e3;
|
|
2116
|
+
var MAX_DELAY_MS2 = 3e4;
|
|
1720
2117
|
var API_BASE_URL2 = "https://generativelanguage.googleapis.com/v1beta";
|
|
1721
2118
|
var GoogleProvider = class {
|
|
1722
2119
|
name = "Google";
|
|
1723
2120
|
config;
|
|
2121
|
+
rateLimiter;
|
|
1724
2122
|
/**
|
|
1725
2123
|
* Creates a new GoogleProvider instance.
|
|
1726
2124
|
*
|
|
@@ -1728,6 +2126,9 @@ var GoogleProvider = class {
|
|
|
1728
2126
|
*/
|
|
1729
2127
|
constructor(config) {
|
|
1730
2128
|
this.config = config;
|
|
2129
|
+
this.rateLimiter = createRateLimiter({
|
|
2130
|
+
requestsPerMinute: DEFAULT_RATE_LIMITS.google
|
|
2131
|
+
});
|
|
1731
2132
|
}
|
|
1732
2133
|
/**
|
|
1733
2134
|
* Checks if the Google Gemini API is available by validating the API key.
|
|
@@ -1737,8 +2138,13 @@ var GoogleProvider = class {
|
|
|
1737
2138
|
*/
|
|
1738
2139
|
async isAvailable() {
|
|
1739
2140
|
if (!this.config.apiKey) {
|
|
2141
|
+
logger.debug("No API key configured", "google");
|
|
1740
2142
|
return false;
|
|
1741
2143
|
}
|
|
2144
|
+
logger.debug(
|
|
2145
|
+
`Validating API key with model ${this.config.model}`,
|
|
2146
|
+
"google"
|
|
2147
|
+
);
|
|
1742
2148
|
try {
|
|
1743
2149
|
const controller = new AbortController();
|
|
1744
2150
|
const timeoutId = setTimeout(() => {
|
|
@@ -1764,92 +2170,90 @@ var GoogleProvider = class {
|
|
|
1764
2170
|
signal: controller.signal
|
|
1765
2171
|
});
|
|
1766
2172
|
clearTimeout(timeoutId);
|
|
1767
|
-
|
|
2173
|
+
const isAvailable = response.ok || response.status === 429 || response.status === 400;
|
|
2174
|
+
logger.debug(
|
|
2175
|
+
`API responded with status ${String(response.status)} (available: ${String(isAvailable)})`,
|
|
2176
|
+
"google"
|
|
2177
|
+
);
|
|
2178
|
+
return isAvailable;
|
|
1768
2179
|
} catch {
|
|
2180
|
+
logger.debug("Connection failed", "google");
|
|
1769
2181
|
return false;
|
|
1770
2182
|
}
|
|
1771
2183
|
}
|
|
1772
2184
|
/**
|
|
1773
2185
|
* Analyzes prompts using the Google Gemini API.
|
|
1774
2186
|
* Implements retry logic with exponential backoff for network errors.
|
|
2187
|
+
* Rate limited to prevent 429 errors during batch processing.
|
|
1775
2188
|
*
|
|
1776
2189
|
* @param prompts - Array of prompt strings to analyze
|
|
1777
2190
|
* @param date - Date context for the analysis
|
|
2191
|
+
* @param context - Optional project context for analysis
|
|
1778
2192
|
* @returns Promise resolving to AnalysisResult
|
|
1779
2193
|
* @throws Error if analysis fails after retries or if response is invalid
|
|
1780
2194
|
*/
|
|
1781
|
-
async analyze(prompts2, date) {
|
|
2195
|
+
async analyze(prompts2, date, context) {
|
|
1782
2196
|
if (prompts2.length === 0) {
|
|
1783
2197
|
throw new Error("Cannot analyze empty prompts array");
|
|
1784
2198
|
}
|
|
1785
|
-
const userPrompt = buildUserPrompt(prompts2, date);
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
2199
|
+
const userPrompt = buildUserPrompt(prompts2, date, context);
|
|
2200
|
+
return this.rateLimiter.throttle(
|
|
2201
|
+
() => withRetry(
|
|
2202
|
+
async () => {
|
|
2203
|
+
const controller = new AbortController();
|
|
2204
|
+
const timeoutId = setTimeout(() => {
|
|
2205
|
+
controller.abort();
|
|
2206
|
+
}, ANALYSIS_TIMEOUT_MS3);
|
|
2207
|
+
try {
|
|
2208
|
+
const url = `${API_BASE_URL2}/models/${this.config.model}:generateContent?key=${this.config.apiKey}`;
|
|
2209
|
+
const response = await fetch(url, {
|
|
2210
|
+
method: "POST",
|
|
2211
|
+
headers: {
|
|
2212
|
+
"Content-Type": "application/json"
|
|
2213
|
+
},
|
|
2214
|
+
body: JSON.stringify({
|
|
2215
|
+
contents: [
|
|
2216
|
+
{
|
|
2217
|
+
role: "user",
|
|
2218
|
+
parts: [{ text: userPrompt }]
|
|
2219
|
+
}
|
|
2220
|
+
],
|
|
2221
|
+
systemInstruction: {
|
|
2222
|
+
parts: [{ text: SYSTEM_PROMPT }]
|
|
2223
|
+
},
|
|
2224
|
+
generationConfig: {
|
|
2225
|
+
responseMimeType: "application/json"
|
|
2226
|
+
}
|
|
2227
|
+
}),
|
|
2228
|
+
signal: controller.signal
|
|
2229
|
+
});
|
|
2230
|
+
if (!response.ok) {
|
|
2231
|
+
const status = String(response.status);
|
|
2232
|
+
const errorBody = await response.text();
|
|
2233
|
+
throw new Error(
|
|
2234
|
+
`Google API request failed: ${status} ${response.statusText} - ${errorBody}`
|
|
2235
|
+
);
|
|
1811
2236
|
}
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
}
|
|
1828
|
-
return parseResponse(textContent, date);
|
|
1829
|
-
} catch (error) {
|
|
1830
|
-
lastError = error instanceof Error ? error : new Error(String(error));
|
|
1831
|
-
if (lastError.message.includes("parse") || lastError.message.includes("schema")) {
|
|
1832
|
-
throw lastError;
|
|
1833
|
-
}
|
|
1834
|
-
if (lastError.message.includes("401") || lastError.message.includes("403")) {
|
|
1835
|
-
throw lastError;
|
|
1836
|
-
}
|
|
1837
|
-
if (attempt === MAX_RETRIES3) {
|
|
1838
|
-
break;
|
|
2237
|
+
const data = await response.json();
|
|
2238
|
+
const textContent = data.candidates?.[0]?.content?.parts?.[0]?.text;
|
|
2239
|
+
if (!textContent) {
|
|
2240
|
+
throw new Error("Invalid response format from Google API");
|
|
2241
|
+
}
|
|
2242
|
+
return parseResponse(textContent, date);
|
|
2243
|
+
} finally {
|
|
2244
|
+
clearTimeout(timeoutId);
|
|
2245
|
+
}
|
|
2246
|
+
},
|
|
2247
|
+
{
|
|
2248
|
+
maxRetries: MAX_RETRIES3,
|
|
2249
|
+
baseDelayMs: BASE_DELAY_MS2,
|
|
2250
|
+
maxDelayMs: MAX_DELAY_MS2,
|
|
2251
|
+
isRetryable: isTransientError
|
|
1839
2252
|
}
|
|
1840
|
-
|
|
1841
|
-
await sleep3(delay);
|
|
1842
|
-
}
|
|
1843
|
-
}
|
|
1844
|
-
const attempts = String(MAX_RETRIES3 + 1);
|
|
1845
|
-
throw new Error(
|
|
1846
|
-
`Google analysis failed after ${attempts} attempts: ${lastError?.message ?? "Unknown error"}`
|
|
2253
|
+
)
|
|
1847
2254
|
);
|
|
1848
2255
|
}
|
|
1849
2256
|
};
|
|
1850
|
-
function sleep3(ms) {
|
|
1851
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1852
|
-
}
|
|
1853
2257
|
|
|
1854
2258
|
// src/providers/index.ts
|
|
1855
2259
|
function createProvider(type, config) {
|
|
@@ -1868,19 +2272,28 @@ async function getAvailableProvider(config, onFallback) {
|
|
|
1868
2272
|
"No providers configured. Please run hyntx setup to configure providers."
|
|
1869
2273
|
);
|
|
1870
2274
|
}
|
|
2275
|
+
logger.debug(
|
|
2276
|
+
`Checking ${String(config.services.length)} configured provider(s): ${config.services.join(", ")}`,
|
|
2277
|
+
"provider"
|
|
2278
|
+
);
|
|
1871
2279
|
let firstProvider;
|
|
1872
2280
|
for (const type of config.services) {
|
|
1873
2281
|
const provider = createProvider(type, config);
|
|
1874
2282
|
firstProvider ??= provider;
|
|
2283
|
+
logger.debug(`Checking availability of ${provider.name}...`, "provider");
|
|
1875
2284
|
try {
|
|
1876
2285
|
const isAvailable = await provider.isAvailable();
|
|
1877
2286
|
if (isAvailable) {
|
|
2287
|
+
logger.debug(`${provider.name} is available`, "provider");
|
|
1878
2288
|
if (onFallback && provider !== firstProvider) {
|
|
1879
2289
|
onFallback(firstProvider.name, provider.name);
|
|
1880
2290
|
}
|
|
1881
2291
|
return provider;
|
|
2292
|
+
} else {
|
|
2293
|
+
logger.debug(`${provider.name} is not available`, "provider");
|
|
1882
2294
|
}
|
|
1883
2295
|
} catch {
|
|
2296
|
+
logger.debug(`${provider.name} availability check failed`, "provider");
|
|
1884
2297
|
continue;
|
|
1885
2298
|
}
|
|
1886
2299
|
}
|
|
@@ -1889,6 +2302,365 @@ async function getAvailableProvider(config, onFallback) {
|
|
|
1889
2302
|
);
|
|
1890
2303
|
}
|
|
1891
2304
|
|
|
2305
|
+
// src/index.ts
|
|
2306
|
+
init_logger();
|
|
2307
|
+
|
|
2308
|
+
// src/utils/project-config.ts
|
|
2309
|
+
init_logger();
|
|
2310
|
+
var CONFIG_FILENAME = ".hyntxrc.json";
|
|
2311
|
+
var MAX_TRAVERSAL_DEPTH = 50;
|
|
2312
|
+
var PROJECT_CONTEXT_SCHEMA = z.object({
|
|
2313
|
+
role: z.string().optional(),
|
|
2314
|
+
techStack: z.array(z.string()).optional(),
|
|
2315
|
+
domain: z.string().optional(),
|
|
2316
|
+
guidelines: z.array(z.string()).optional(),
|
|
2317
|
+
projectType: z.string().optional()
|
|
2318
|
+
});
|
|
2319
|
+
var PROJECT_CONFIG_SCHEMA = z.object({
|
|
2320
|
+
context: PROJECT_CONTEXT_SCHEMA.optional()
|
|
2321
|
+
});
|
|
2322
|
+
var configCache = /* @__PURE__ */ new Map();
|
|
2323
|
+
function findProjectConfig(cwd) {
|
|
2324
|
+
let currentDir2 = cwd;
|
|
2325
|
+
const homeDirectory = homedir();
|
|
2326
|
+
let depth = 0;
|
|
2327
|
+
while (depth < MAX_TRAVERSAL_DEPTH) {
|
|
2328
|
+
const configPath = join(currentDir2, CONFIG_FILENAME);
|
|
2329
|
+
try {
|
|
2330
|
+
readFileSync(configPath, "utf-8");
|
|
2331
|
+
return configPath;
|
|
2332
|
+
} catch {
|
|
2333
|
+
}
|
|
2334
|
+
if (currentDir2 === homeDirectory || currentDir2 === "/") {
|
|
2335
|
+
break;
|
|
2336
|
+
}
|
|
2337
|
+
const parentDir = dirname(currentDir2);
|
|
2338
|
+
if (parentDir === currentDir2) {
|
|
2339
|
+
break;
|
|
2340
|
+
}
|
|
2341
|
+
currentDir2 = parentDir;
|
|
2342
|
+
depth++;
|
|
2343
|
+
}
|
|
2344
|
+
return null;
|
|
2345
|
+
}
|
|
2346
|
+
function loadProjectConfig(configPath) {
|
|
2347
|
+
try {
|
|
2348
|
+
const fileContent = readFileSync(configPath, "utf-8");
|
|
2349
|
+
let parsed;
|
|
2350
|
+
try {
|
|
2351
|
+
parsed = JSON.parse(fileContent);
|
|
2352
|
+
} catch (error) {
|
|
2353
|
+
logger.collectWarning(
|
|
2354
|
+
`Invalid JSON in ${CONFIG_FILENAME}: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
2355
|
+
"config"
|
|
2356
|
+
);
|
|
2357
|
+
return null;
|
|
2358
|
+
}
|
|
2359
|
+
const result = PROJECT_CONFIG_SCHEMA.safeParse(parsed);
|
|
2360
|
+
if (!result.success) {
|
|
2361
|
+
const errorMessages = result.error.issues.map((issue) => {
|
|
2362
|
+
const pathStr = issue.path.map(String).join(".");
|
|
2363
|
+
return `${pathStr}: ${issue.message}`;
|
|
2364
|
+
}).join(", ");
|
|
2365
|
+
logger.collectWarning(
|
|
2366
|
+
`Invalid ${CONFIG_FILENAME} schema: ${errorMessages}`,
|
|
2367
|
+
"config"
|
|
2368
|
+
);
|
|
2369
|
+
return null;
|
|
2370
|
+
}
|
|
2371
|
+
return result.data;
|
|
2372
|
+
} catch (error) {
|
|
2373
|
+
logger.collectWarning(
|
|
2374
|
+
`Failed to read ${CONFIG_FILENAME}: ${error instanceof Error ? error.message : "Unknown error"}`,
|
|
2375
|
+
"config"
|
|
2376
|
+
);
|
|
2377
|
+
return null;
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
function mergeConfigs(envConfig, projectConfig) {
|
|
2381
|
+
if (!projectConfig?.context) {
|
|
2382
|
+
return envConfig;
|
|
2383
|
+
}
|
|
2384
|
+
const existingEnvConfig = envConfig;
|
|
2385
|
+
if (existingEnvConfig.context) {
|
|
2386
|
+
return existingEnvConfig;
|
|
2387
|
+
}
|
|
2388
|
+
return {
|
|
2389
|
+
...envConfig,
|
|
2390
|
+
context: projectConfig.context
|
|
2391
|
+
};
|
|
2392
|
+
}
|
|
2393
|
+
function loadProjectConfigForCwd(cwd) {
|
|
2394
|
+
if (configCache.has(cwd)) {
|
|
2395
|
+
return configCache.get(cwd) ?? null;
|
|
2396
|
+
}
|
|
2397
|
+
const configPath = findProjectConfig(cwd);
|
|
2398
|
+
if (!configPath) {
|
|
2399
|
+
configCache.set(cwd, null);
|
|
2400
|
+
return null;
|
|
2401
|
+
}
|
|
2402
|
+
const config = loadProjectConfig(configPath);
|
|
2403
|
+
configCache.set(cwd, config);
|
|
2404
|
+
return config;
|
|
2405
|
+
}
|
|
2406
|
+
init_logger();
|
|
2407
|
+
function isValidUrl(url) {
|
|
2408
|
+
try {
|
|
2409
|
+
new URL(url);
|
|
2410
|
+
return true;
|
|
2411
|
+
} catch {
|
|
2412
|
+
return false;
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
function isValidApiKeyFormat(apiKey) {
|
|
2416
|
+
if (!apiKey || apiKey.trim() === "") {
|
|
2417
|
+
return false;
|
|
2418
|
+
}
|
|
2419
|
+
return apiKey.length >= 10 && !/\s/.test(apiKey);
|
|
2420
|
+
}
|
|
2421
|
+
async function validateOllama(config) {
|
|
2422
|
+
const checks = [];
|
|
2423
|
+
const { ollama } = config;
|
|
2424
|
+
checks.push({
|
|
2425
|
+
name: "Model",
|
|
2426
|
+
status: ollama.model ? "pass" : "fail",
|
|
2427
|
+
message: ollama.model || "Not configured"
|
|
2428
|
+
});
|
|
2429
|
+
const hostValid = isValidUrl(ollama.host);
|
|
2430
|
+
checks.push({
|
|
2431
|
+
name: "Host",
|
|
2432
|
+
status: hostValid ? "pass" : "fail",
|
|
2433
|
+
message: hostValid ? ollama.host : `Invalid URL: ${ollama.host}`
|
|
2434
|
+
});
|
|
2435
|
+
if (hostValid) {
|
|
2436
|
+
try {
|
|
2437
|
+
const provider = createProvider("ollama", config);
|
|
2438
|
+
const isAvailable = await provider.isAvailable();
|
|
2439
|
+
checks.push({
|
|
2440
|
+
name: "Connection",
|
|
2441
|
+
status: isAvailable ? "pass" : "fail",
|
|
2442
|
+
message: isAvailable ? "Reachable" : "Cannot connect"
|
|
2443
|
+
});
|
|
2444
|
+
if (isAvailable) {
|
|
2445
|
+
checks.push({
|
|
2446
|
+
name: "Model available",
|
|
2447
|
+
status: "pass",
|
|
2448
|
+
message: "Yes"
|
|
2449
|
+
});
|
|
2450
|
+
} else {
|
|
2451
|
+
checks.push({
|
|
2452
|
+
name: "Model available",
|
|
2453
|
+
status: "warn",
|
|
2454
|
+
message: "Cannot verify (connection failed)"
|
|
2455
|
+
});
|
|
2456
|
+
}
|
|
2457
|
+
} catch (error) {
|
|
2458
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2459
|
+
checks.push({
|
|
2460
|
+
name: "Connection",
|
|
2461
|
+
status: "fail",
|
|
2462
|
+
message: `Error: ${message}`
|
|
2463
|
+
});
|
|
2464
|
+
}
|
|
2465
|
+
} else {
|
|
2466
|
+
checks.push({
|
|
2467
|
+
name: "Connection",
|
|
2468
|
+
status: "warn",
|
|
2469
|
+
message: "Cannot test (invalid host URL)"
|
|
2470
|
+
});
|
|
2471
|
+
}
|
|
2472
|
+
const allPass = checks.every((c) => c.status === "pass");
|
|
2473
|
+
return {
|
|
2474
|
+
provider: "ollama",
|
|
2475
|
+
displayName: "Ollama",
|
|
2476
|
+
valid: allPass,
|
|
2477
|
+
checks
|
|
2478
|
+
};
|
|
2479
|
+
}
|
|
2480
|
+
async function validateAnthropic(config) {
|
|
2481
|
+
const checks = [];
|
|
2482
|
+
const { anthropic } = config;
|
|
2483
|
+
checks.push({
|
|
2484
|
+
name: "Model",
|
|
2485
|
+
status: anthropic.model ? "pass" : "fail",
|
|
2486
|
+
message: anthropic.model || "Not configured"
|
|
2487
|
+
});
|
|
2488
|
+
const apiKeyValid = isValidApiKeyFormat(anthropic.apiKey);
|
|
2489
|
+
checks.push({
|
|
2490
|
+
name: "API Key",
|
|
2491
|
+
status: apiKeyValid ? "pass" : "fail",
|
|
2492
|
+
message: apiKeyValid ? "Configured" : "Missing or invalid"
|
|
2493
|
+
});
|
|
2494
|
+
if (apiKeyValid) {
|
|
2495
|
+
try {
|
|
2496
|
+
const provider = createProvider("anthropic", config);
|
|
2497
|
+
const isAvailable = await provider.isAvailable();
|
|
2498
|
+
checks.push({
|
|
2499
|
+
name: "Connection",
|
|
2500
|
+
status: isAvailable ? "pass" : "fail",
|
|
2501
|
+
message: isAvailable ? "API key valid" : "API key invalid or connection failed"
|
|
2502
|
+
});
|
|
2503
|
+
} catch (error) {
|
|
2504
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2505
|
+
checks.push({
|
|
2506
|
+
name: "Connection",
|
|
2507
|
+
status: "fail",
|
|
2508
|
+
message: `Error: ${message}`
|
|
2509
|
+
});
|
|
2510
|
+
}
|
|
2511
|
+
} else {
|
|
2512
|
+
checks.push({
|
|
2513
|
+
name: "Connection",
|
|
2514
|
+
status: "warn",
|
|
2515
|
+
message: "Cannot test (invalid API key)"
|
|
2516
|
+
});
|
|
2517
|
+
}
|
|
2518
|
+
const allPass = checks.every((c) => c.status === "pass");
|
|
2519
|
+
return {
|
|
2520
|
+
provider: "anthropic",
|
|
2521
|
+
displayName: "Anthropic",
|
|
2522
|
+
valid: allPass,
|
|
2523
|
+
checks
|
|
2524
|
+
};
|
|
2525
|
+
}
|
|
2526
|
+
async function validateGoogle(config) {
|
|
2527
|
+
const checks = [];
|
|
2528
|
+
const { google } = config;
|
|
2529
|
+
checks.push({
|
|
2530
|
+
name: "Model",
|
|
2531
|
+
status: google.model ? "pass" : "fail",
|
|
2532
|
+
message: google.model || "Not configured"
|
|
2533
|
+
});
|
|
2534
|
+
const apiKeyValid = isValidApiKeyFormat(google.apiKey);
|
|
2535
|
+
checks.push({
|
|
2536
|
+
name: "API Key",
|
|
2537
|
+
status: apiKeyValid ? "pass" : "fail",
|
|
2538
|
+
message: apiKeyValid ? "Configured" : "Missing or invalid"
|
|
2539
|
+
});
|
|
2540
|
+
if (apiKeyValid) {
|
|
2541
|
+
try {
|
|
2542
|
+
const provider = createProvider("google", config);
|
|
2543
|
+
const isAvailable = await provider.isAvailable();
|
|
2544
|
+
checks.push({
|
|
2545
|
+
name: "Connection",
|
|
2546
|
+
status: isAvailable ? "pass" : "fail",
|
|
2547
|
+
message: isAvailable ? "API key valid" : "API key invalid or connection failed"
|
|
2548
|
+
});
|
|
2549
|
+
} catch (error) {
|
|
2550
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2551
|
+
checks.push({
|
|
2552
|
+
name: "Connection",
|
|
2553
|
+
status: "fail",
|
|
2554
|
+
message: `Error: ${message}`
|
|
2555
|
+
});
|
|
2556
|
+
}
|
|
2557
|
+
} else {
|
|
2558
|
+
checks.push({
|
|
2559
|
+
name: "Connection",
|
|
2560
|
+
status: "warn",
|
|
2561
|
+
message: "Cannot test (invalid API key)"
|
|
2562
|
+
});
|
|
2563
|
+
}
|
|
2564
|
+
const allPass = checks.every((c) => c.status === "pass");
|
|
2565
|
+
return {
|
|
2566
|
+
provider: "google",
|
|
2567
|
+
displayName: "Google",
|
|
2568
|
+
valid: allPass,
|
|
2569
|
+
checks
|
|
2570
|
+
};
|
|
2571
|
+
}
|
|
2572
|
+
async function validateProvider(type, config) {
|
|
2573
|
+
switch (type) {
|
|
2574
|
+
case "ollama":
|
|
2575
|
+
return validateOllama(config);
|
|
2576
|
+
case "anthropic":
|
|
2577
|
+
return validateAnthropic(config);
|
|
2578
|
+
case "google":
|
|
2579
|
+
return validateGoogle(config);
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
2582
|
+
async function validateAllProviders(config) {
|
|
2583
|
+
const results = [];
|
|
2584
|
+
for (const type of config.services) {
|
|
2585
|
+
logger.debug(`Validating ${type} provider...`, "health-check");
|
|
2586
|
+
const result = await validateProvider(type, config);
|
|
2587
|
+
results.push(result);
|
|
2588
|
+
}
|
|
2589
|
+
const availableCount = results.filter((r) => r.valid).length;
|
|
2590
|
+
const unavailableCount = results.filter((r) => !r.valid).length;
|
|
2591
|
+
return {
|
|
2592
|
+
providers: results,
|
|
2593
|
+
summary: {
|
|
2594
|
+
availableCount,
|
|
2595
|
+
unavailableCount,
|
|
2596
|
+
totalConfigured: config.services.length
|
|
2597
|
+
},
|
|
2598
|
+
allValid: unavailableCount === 0 && config.services.length > 0
|
|
2599
|
+
};
|
|
2600
|
+
}
|
|
2601
|
+
function formatStatusIcon(status) {
|
|
2602
|
+
switch (status) {
|
|
2603
|
+
case "pass":
|
|
2604
|
+
return chalk3.green("\u2705");
|
|
2605
|
+
case "fail":
|
|
2606
|
+
return chalk3.red("\u274C");
|
|
2607
|
+
case "warn":
|
|
2608
|
+
return chalk3.yellow("\u26A0\uFE0F");
|
|
2609
|
+
}
|
|
2610
|
+
}
|
|
2611
|
+
function printHealthCheckResult(result, config) {
|
|
2612
|
+
console.log("");
|
|
2613
|
+
console.log(chalk3.bold("\u{1F50D} Configuration Health Check"));
|
|
2614
|
+
console.log(chalk3.dim("\u2550".repeat(43)));
|
|
2615
|
+
console.log("");
|
|
2616
|
+
console.log(chalk3.bold("Configuration:"));
|
|
2617
|
+
if (config.services.length === 0) {
|
|
2618
|
+
console.log(chalk3.dim(" No providers configured"));
|
|
2619
|
+
} else {
|
|
2620
|
+
console.log(` Services: ${config.services.join(", ")}`);
|
|
2621
|
+
}
|
|
2622
|
+
console.log(` Reminder: ${config.reminder}`);
|
|
2623
|
+
console.log("");
|
|
2624
|
+
for (const provider of result.providers) {
|
|
2625
|
+
console.log(chalk3.bold(`${provider.displayName} Provider:`));
|
|
2626
|
+
for (const check of provider.checks) {
|
|
2627
|
+
const icon = formatStatusIcon(check.status);
|
|
2628
|
+
const message = check.message ? `: ${check.message}` : "";
|
|
2629
|
+
console.log(` ${icon} ${check.name}${message}`);
|
|
2630
|
+
}
|
|
2631
|
+
console.log("");
|
|
2632
|
+
}
|
|
2633
|
+
console.log(chalk3.bold("Summary:"));
|
|
2634
|
+
if (config.services.length === 0) {
|
|
2635
|
+
console.log(chalk3.yellow(" \u26A0\uFE0F No providers configured"));
|
|
2636
|
+
console.log(chalk3.dim(" Run hyntx setup to configure providers"));
|
|
2637
|
+
} else if (result.allValid) {
|
|
2638
|
+
console.log(
|
|
2639
|
+
chalk3.green(
|
|
2640
|
+
` \u2705 All ${String(result.summary.totalConfigured)} provider(s) ready to use`
|
|
2641
|
+
)
|
|
2642
|
+
);
|
|
2643
|
+
} else {
|
|
2644
|
+
if (result.summary.unavailableCount > 0) {
|
|
2645
|
+
console.log(
|
|
2646
|
+
chalk3.yellow(
|
|
2647
|
+
` \u26A0\uFE0F ${String(result.summary.unavailableCount)} provider(s) configured but unavailable`
|
|
2648
|
+
)
|
|
2649
|
+
);
|
|
2650
|
+
}
|
|
2651
|
+
if (result.summary.availableCount > 0) {
|
|
2652
|
+
console.log(
|
|
2653
|
+
chalk3.green(
|
|
2654
|
+
` \u2705 ${String(result.summary.availableCount)} provider(s) ready to use`
|
|
2655
|
+
)
|
|
2656
|
+
);
|
|
2657
|
+
} else {
|
|
2658
|
+
console.log(chalk3.red(" \u274C No providers available"));
|
|
2659
|
+
}
|
|
2660
|
+
}
|
|
2661
|
+
console.log("");
|
|
2662
|
+
}
|
|
2663
|
+
|
|
1892
2664
|
// src/index.ts
|
|
1893
2665
|
var currentDir = dirname(fileURLToPath(import.meta.url));
|
|
1894
2666
|
var packageJson = JSON.parse(
|
|
@@ -1903,6 +2675,23 @@ function parseArguments() {
|
|
|
1903
2675
|
type: "string",
|
|
1904
2676
|
default: "today"
|
|
1905
2677
|
},
|
|
2678
|
+
format: {
|
|
2679
|
+
type: "string",
|
|
2680
|
+
default: "terminal"
|
|
2681
|
+
},
|
|
2682
|
+
compact: {
|
|
2683
|
+
type: "boolean",
|
|
2684
|
+
default: false
|
|
2685
|
+
},
|
|
2686
|
+
verbose: {
|
|
2687
|
+
type: "boolean",
|
|
2688
|
+
short: "v",
|
|
2689
|
+
default: false
|
|
2690
|
+
},
|
|
2691
|
+
"check-config": {
|
|
2692
|
+
type: "boolean",
|
|
2693
|
+
default: false
|
|
2694
|
+
},
|
|
1906
2695
|
help: {
|
|
1907
2696
|
type: "boolean",
|
|
1908
2697
|
short: "h",
|
|
@@ -1919,7 +2708,11 @@ function parseArguments() {
|
|
|
1919
2708
|
return {
|
|
1920
2709
|
date: values.date || "today",
|
|
1921
2710
|
help: values.help || false,
|
|
1922
|
-
version: values.version || false
|
|
2711
|
+
version: values.version || false,
|
|
2712
|
+
verbose: values.verbose || false,
|
|
2713
|
+
checkConfig: values["check-config"] || false,
|
|
2714
|
+
format: values.format || "terminal",
|
|
2715
|
+
compact: values.compact || false
|
|
1923
2716
|
};
|
|
1924
2717
|
} catch (error) {
|
|
1925
2718
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
@@ -1931,9 +2724,13 @@ function showHelp() {
|
|
|
1931
2724
|
${chalk3.bold("Usage:")} hyntx [options]
|
|
1932
2725
|
|
|
1933
2726
|
${chalk3.bold("Options:")}
|
|
1934
|
-
--date <date>
|
|
1935
|
-
|
|
1936
|
-
--
|
|
2727
|
+
--date <date> Date to analyze (today, yesterday, YYYY-MM-DD) [default: today]
|
|
2728
|
+
--format <type> Output format: terminal, json [default: terminal]
|
|
2729
|
+
--compact Compact JSON output (only with --format json)
|
|
2730
|
+
-v, --verbose Enable debug output to stderr
|
|
2731
|
+
--check-config Validate configuration and test provider connectivity
|
|
2732
|
+
-h, --help Show help
|
|
2733
|
+
--version Show version
|
|
1937
2734
|
|
|
1938
2735
|
${chalk3.bold("Exit codes:")}
|
|
1939
2736
|
${String(EXIT_CODES.SUCCESS)} - Success
|
|
@@ -1942,9 +2739,11 @@ ${chalk3.bold("Exit codes:")}
|
|
|
1942
2739
|
${String(EXIT_CODES.PROVIDER_UNAVAILABLE)} - Provider unavailable
|
|
1943
2740
|
|
|
1944
2741
|
${chalk3.bold("Examples:")}
|
|
1945
|
-
hyntx
|
|
1946
|
-
hyntx --date yesterday
|
|
1947
|
-
hyntx --date 2025-01-20
|
|
2742
|
+
hyntx # Analyze today's prompts (terminal format)
|
|
2743
|
+
hyntx --date yesterday # Analyze yesterday
|
|
2744
|
+
hyntx --date 2025-01-20 # Specific date
|
|
2745
|
+
hyntx --format json # Output as formatted JSON
|
|
2746
|
+
hyntx --format json --compact # Output as compact JSON
|
|
1948
2747
|
`;
|
|
1949
2748
|
console.log(helpText);
|
|
1950
2749
|
process.exit(EXIT_CODES.SUCCESS);
|
|
@@ -1953,127 +2752,244 @@ function showVersion() {
|
|
|
1953
2752
|
console.log(`hyntx v${VERSION}`);
|
|
1954
2753
|
process.exit(EXIT_CODES.SUCCESS);
|
|
1955
2754
|
}
|
|
1956
|
-
async function
|
|
2755
|
+
async function runConfigCheck() {
|
|
2756
|
+
const config = getEnvConfig();
|
|
2757
|
+
logger.debug("Running configuration health check", "cli");
|
|
2758
|
+
const result = await validateAllProviders(config);
|
|
2759
|
+
printHealthCheckResult(result, config);
|
|
2760
|
+
if (result.allValid) {
|
|
2761
|
+
process.exit(EXIT_CODES.SUCCESS);
|
|
2762
|
+
} else if (result.summary.availableCount > 0) {
|
|
2763
|
+
process.exit(EXIT_CODES.SUCCESS);
|
|
2764
|
+
} else {
|
|
2765
|
+
process.exit(EXIT_CODES.PROVIDER_UNAVAILABLE);
|
|
2766
|
+
}
|
|
2767
|
+
}
|
|
2768
|
+
async function checkAndRunSetup(isJsonMode) {
|
|
1957
2769
|
if (isFirstRun()) {
|
|
1958
|
-
|
|
1959
|
-
|
|
2770
|
+
if (!isJsonMode) {
|
|
2771
|
+
const spinner = ora("Running first-time setup...").start();
|
|
2772
|
+
spinner.stop();
|
|
2773
|
+
}
|
|
1960
2774
|
await runSetup();
|
|
1961
2775
|
}
|
|
1962
2776
|
}
|
|
1963
|
-
async function readLogsWithSpinner(date) {
|
|
2777
|
+
async function readLogsWithSpinner(date, isJsonMode) {
|
|
1964
2778
|
if (!claudeProjectsExist()) {
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
)
|
|
1971
|
-
|
|
2779
|
+
if (isJsonMode) {
|
|
2780
|
+
const errorResponse = {
|
|
2781
|
+
error: "Claude Code logs directory not found",
|
|
2782
|
+
code: "NO_DATA"
|
|
2783
|
+
};
|
|
2784
|
+
console.log(JSON.stringify(errorResponse));
|
|
2785
|
+
} else {
|
|
2786
|
+
logger.error("Claude Code logs directory not found");
|
|
2787
|
+
process.stderr.write(
|
|
2788
|
+
chalk3.dim(`Expected location: ${CLAUDE_PROJECTS_DIR}
|
|
2789
|
+
`)
|
|
2790
|
+
);
|
|
2791
|
+
process.stderr.write(
|
|
2792
|
+
chalk3.dim(
|
|
2793
|
+
"\nMake sure Claude Code is installed and has been used at least once.\n"
|
|
2794
|
+
)
|
|
2795
|
+
);
|
|
2796
|
+
}
|
|
1972
2797
|
process.exit(EXIT_CODES.NO_DATA);
|
|
1973
2798
|
}
|
|
1974
|
-
const spinner = ora(`Reading Claude Code logs for ${date}...`).start();
|
|
2799
|
+
const spinner = isJsonMode ? null : ora(`Reading Claude Code logs for ${date}...`).start();
|
|
1975
2800
|
try {
|
|
1976
2801
|
const result = await readLogs({ date });
|
|
1977
2802
|
if (result.prompts.length === 0) {
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
2803
|
+
if (isJsonMode) {
|
|
2804
|
+
const errorResponse = {
|
|
2805
|
+
error: `No prompts found for ${date}`,
|
|
2806
|
+
code: "NO_DATA"
|
|
2807
|
+
};
|
|
2808
|
+
console.log(JSON.stringify(errorResponse));
|
|
2809
|
+
} else {
|
|
2810
|
+
spinner?.fail(chalk3.yellow(`No prompts found for ${date}`));
|
|
2811
|
+
process.stderr.write(
|
|
2812
|
+
chalk3.dim(
|
|
2813
|
+
"\nTry a different date or check that Claude Code has been used recently.\n"
|
|
2814
|
+
)
|
|
2815
|
+
);
|
|
2816
|
+
}
|
|
1984
2817
|
process.exit(EXIT_CODES.NO_DATA);
|
|
1985
2818
|
}
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
}
|
|
2819
|
+
if (!isJsonMode) {
|
|
2820
|
+
spinner?.succeed(
|
|
2821
|
+
chalk3.green(
|
|
2822
|
+
`Found ${String(result.prompts.length)} prompts for ${date}`
|
|
2823
|
+
)
|
|
2824
|
+
);
|
|
1993
2825
|
}
|
|
1994
2826
|
return result.prompts.map((p) => p.content);
|
|
1995
2827
|
} catch (error) {
|
|
1996
2828
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
1997
|
-
|
|
2829
|
+
if (isJsonMode) {
|
|
2830
|
+
const errorResponse = {
|
|
2831
|
+
error: `Failed to read logs: ${errorMessage}`,
|
|
2832
|
+
code: "ERROR"
|
|
2833
|
+
};
|
|
2834
|
+
console.log(JSON.stringify(errorResponse));
|
|
2835
|
+
} else {
|
|
2836
|
+
spinner?.fail(chalk3.red(`Failed to read logs: ${errorMessage}`));
|
|
2837
|
+
}
|
|
1998
2838
|
process.exit(EXIT_CODES.ERROR);
|
|
1999
2839
|
}
|
|
2000
2840
|
}
|
|
2001
|
-
async function connectProviderWithSpinner() {
|
|
2841
|
+
async function connectProviderWithSpinner(isJsonMode) {
|
|
2002
2842
|
const config = getEnvConfig();
|
|
2003
2843
|
if (config.services.length === 0) {
|
|
2004
|
-
|
|
2005
|
-
|
|
2844
|
+
if (isJsonMode) {
|
|
2845
|
+
const errorResponse = {
|
|
2846
|
+
error: "No providers configured",
|
|
2847
|
+
code: "PROVIDER_UNAVAILABLE"
|
|
2848
|
+
};
|
|
2849
|
+
console.log(JSON.stringify(errorResponse));
|
|
2850
|
+
} else {
|
|
2851
|
+
logger.error("No providers configured");
|
|
2852
|
+
process.stderr.write(
|
|
2853
|
+
chalk3.dim("\nRun setup to configure at least one provider.\n")
|
|
2854
|
+
);
|
|
2855
|
+
}
|
|
2006
2856
|
process.exit(EXIT_CODES.PROVIDER_UNAVAILABLE);
|
|
2007
2857
|
}
|
|
2008
|
-
const spinner = ora("Connecting to provider...").start();
|
|
2858
|
+
const spinner = isJsonMode ? null : ora("Connecting to provider...").start();
|
|
2009
2859
|
try {
|
|
2010
2860
|
const provider = await getAvailableProvider(config, (from, to) => {
|
|
2011
|
-
spinner
|
|
2012
|
-
|
|
2861
|
+
if (!isJsonMode && spinner) {
|
|
2862
|
+
spinner.text = chalk3.yellow(
|
|
2863
|
+
`Primary provider ${from} unavailable, falling back to ${to}...`
|
|
2864
|
+
);
|
|
2865
|
+
}
|
|
2866
|
+
logger.collectWarning(
|
|
2867
|
+
`Provider ${from} unavailable, fell back to ${to}`,
|
|
2868
|
+
"provider"
|
|
2013
2869
|
);
|
|
2014
2870
|
});
|
|
2015
|
-
|
|
2871
|
+
if (!isJsonMode) {
|
|
2872
|
+
spinner?.succeed(chalk3.green(`Connected to ${provider.name}`));
|
|
2873
|
+
}
|
|
2016
2874
|
return provider;
|
|
2017
2875
|
} catch (error) {
|
|
2018
2876
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2877
|
+
if (isJsonMode) {
|
|
2878
|
+
const errorResponse = {
|
|
2879
|
+
error: errorMessage,
|
|
2880
|
+
code: "PROVIDER_UNAVAILABLE"
|
|
2881
|
+
};
|
|
2882
|
+
console.log(JSON.stringify(errorResponse));
|
|
2883
|
+
} else {
|
|
2884
|
+
spinner?.fail(chalk3.red("No providers available"));
|
|
2885
|
+
process.stderr.write(chalk3.dim(`
|
|
2886
|
+
${errorMessage}
|
|
2887
|
+
`));
|
|
2888
|
+
process.stderr.write(
|
|
2889
|
+
chalk3.dim(
|
|
2890
|
+
"\nCheck your provider configuration and ensure at least one provider is running.\n"
|
|
2891
|
+
)
|
|
2892
|
+
);
|
|
2893
|
+
}
|
|
2027
2894
|
process.exit(EXIT_CODES.PROVIDER_UNAVAILABLE);
|
|
2028
2895
|
}
|
|
2029
2896
|
}
|
|
2030
|
-
async function analyzeWithProgress(provider, prompts2, date) {
|
|
2031
|
-
const spinner = ora(`Analyzing ${String(prompts2.length)} prompts...`).start();
|
|
2897
|
+
async function analyzeWithProgress(provider, prompts2, date, context, isJsonMode) {
|
|
2898
|
+
const spinner = isJsonMode ? null : ora(`Analyzing ${String(prompts2.length)} prompts...`).start();
|
|
2032
2899
|
try {
|
|
2033
2900
|
const result = await analyzePrompts({
|
|
2034
2901
|
provider,
|
|
2035
2902
|
prompts: prompts2,
|
|
2036
2903
|
date,
|
|
2904
|
+
context,
|
|
2037
2905
|
onProgress: (current, total) => {
|
|
2038
|
-
if (total > 1) {
|
|
2906
|
+
if (!isJsonMode && spinner && total > 1) {
|
|
2039
2907
|
spinner.text = `Analyzing ${String(prompts2.length)} prompts (batch ${String(current + 1)}/${String(total)})...`;
|
|
2040
2908
|
}
|
|
2041
2909
|
}
|
|
2042
2910
|
});
|
|
2043
|
-
|
|
2911
|
+
if (!isJsonMode) {
|
|
2912
|
+
spinner?.succeed(chalk3.green("Analysis complete"));
|
|
2913
|
+
}
|
|
2044
2914
|
return result;
|
|
2045
2915
|
} catch (error) {
|
|
2046
2916
|
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
2047
|
-
|
|
2917
|
+
if (isJsonMode) {
|
|
2918
|
+
const errorResponse = {
|
|
2919
|
+
error: `Analysis failed: ${errorMessage}`,
|
|
2920
|
+
code: "ERROR"
|
|
2921
|
+
};
|
|
2922
|
+
console.log(JSON.stringify(errorResponse));
|
|
2923
|
+
} else {
|
|
2924
|
+
spinner?.fail(chalk3.red(`Analysis failed: ${errorMessage}`));
|
|
2925
|
+
}
|
|
2048
2926
|
process.exit(EXIT_CODES.ERROR);
|
|
2049
2927
|
}
|
|
2050
2928
|
}
|
|
2051
|
-
function displayResults(result) {
|
|
2052
|
-
|
|
2053
|
-
|
|
2929
|
+
function displayResults(result, format, compact) {
|
|
2930
|
+
if (format === "json") {
|
|
2931
|
+
console.log(formatJson(result, compact));
|
|
2932
|
+
} else {
|
|
2933
|
+
console.log("");
|
|
2934
|
+
printReport(result);
|
|
2935
|
+
}
|
|
2054
2936
|
}
|
|
2055
|
-
function handleError(error) {
|
|
2056
|
-
|
|
2057
|
-
|
|
2937
|
+
function handleError(error, isJsonMode) {
|
|
2938
|
+
if (isJsonMode) {
|
|
2939
|
+
const errorResponse = {
|
|
2940
|
+
error: error.message,
|
|
2941
|
+
code: "ERROR"
|
|
2942
|
+
};
|
|
2943
|
+
console.log(JSON.stringify(errorResponse));
|
|
2944
|
+
} else {
|
|
2945
|
+
logger.error(error.message);
|
|
2946
|
+
}
|
|
2058
2947
|
process.exit(EXIT_CODES.ERROR);
|
|
2059
2948
|
}
|
|
2060
2949
|
async function main() {
|
|
2950
|
+
let isJsonMode = false;
|
|
2061
2951
|
try {
|
|
2062
2952
|
const args = parseArguments();
|
|
2953
|
+
isJsonMode = args.format === "json";
|
|
2954
|
+
if (args.verbose) {
|
|
2955
|
+
logger.setVerbose(true);
|
|
2956
|
+
logger.debug("Verbose mode enabled");
|
|
2957
|
+
}
|
|
2063
2958
|
if (args.help) {
|
|
2064
2959
|
showHelp();
|
|
2065
2960
|
}
|
|
2066
2961
|
if (args.version) {
|
|
2067
2962
|
showVersion();
|
|
2068
2963
|
}
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2964
|
+
if (args.checkConfig) {
|
|
2965
|
+
await runConfigCheck();
|
|
2966
|
+
}
|
|
2967
|
+
await checkAndRunSetup(isJsonMode);
|
|
2968
|
+
const envConfig = getEnvConfig();
|
|
2969
|
+
const projectConfig = loadProjectConfigForCwd(process.cwd());
|
|
2970
|
+
const config = mergeConfigs(envConfig, projectConfig);
|
|
2971
|
+
const prompts2 = await readLogsWithSpinner(args.date, isJsonMode);
|
|
2972
|
+
const provider = await connectProviderWithSpinner(isJsonMode);
|
|
2973
|
+
const result = await analyzeWithProgress(
|
|
2974
|
+
provider,
|
|
2975
|
+
prompts2,
|
|
2976
|
+
args.date,
|
|
2977
|
+
config.context,
|
|
2978
|
+
isJsonMode
|
|
2979
|
+
);
|
|
2980
|
+
displayResults(result, args.format ?? "terminal", args.compact ?? false);
|
|
2981
|
+
if (!isJsonMode) {
|
|
2982
|
+
logger.reportWarnings();
|
|
2983
|
+
}
|
|
2074
2984
|
process.exit(EXIT_CODES.SUCCESS);
|
|
2075
2985
|
} catch (error) {
|
|
2076
|
-
|
|
2986
|
+
if (!isJsonMode) {
|
|
2987
|
+
logger.reportWarnings();
|
|
2988
|
+
}
|
|
2989
|
+
handleError(
|
|
2990
|
+
error instanceof Error ? error : new Error(String(error)),
|
|
2991
|
+
isJsonMode
|
|
2992
|
+
);
|
|
2077
2993
|
}
|
|
2078
2994
|
}
|
|
2079
2995
|
var isMainModule = process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];
|
|
@@ -2081,6 +2997,6 @@ if (isMainModule) {
|
|
|
2081
2997
|
void main();
|
|
2082
2998
|
}
|
|
2083
2999
|
|
|
2084
|
-
export { analyzeWithProgress, checkAndRunSetup, connectProviderWithSpinner, displayResults, handleError, main, parseArguments, readLogsWithSpinner, showHelp, showVersion };
|
|
3000
|
+
export { analyzeWithProgress, checkAndRunSetup, connectProviderWithSpinner, displayResults, handleError, main, parseArguments, readLogsWithSpinner, runConfigCheck, showHelp, showVersion };
|
|
2085
3001
|
//# sourceMappingURL=index.js.map
|
|
2086
3002
|
//# sourceMappingURL=index.js.map
|