hyntx 0.0.1 → 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.js CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync, existsSync, mkdirSync, writeFileSync } from 'fs';
2
+ import chalk3 from 'chalk';
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,9 +263,24 @@ ${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");
275
+ try {
276
+ chmodSync(configFile, 384);
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
+ );
283
+ }
134
284
  return {
135
285
  success: true,
136
286
  shellFile: configFile,
@@ -169,6 +319,7 @@ function getManualInstructions(config) {
169
319
  }
170
320
  var init_shell_config = __esm({
171
321
  "src/utils/shell-config.ts"() {
322
+ init_logger();
172
323
  }
173
324
  });
174
325
 
@@ -340,6 +491,7 @@ function validateLogEntry(entry) {
340
491
  }
341
492
 
342
493
  // src/core/log-reader.ts
494
+ init_logger();
343
495
  function claudeProjectsExist() {
344
496
  return existsSync(CLAUDE_PROJECTS_DIR);
345
497
  }
@@ -383,18 +535,25 @@ function extractDate(timestamp) {
383
535
  return "unknown";
384
536
  }
385
537
  }
386
- function parseLine(line) {
538
+ function parseLine(line, lineNumber, filePath) {
387
539
  if (!line.trim()) {
388
540
  return null;
389
541
  }
542
+ const context = lineNumber !== void 0 && filePath ? `${filePath}:${String(lineNumber)}` : void 0;
390
543
  try {
391
544
  const parsed = JSON.parse(line);
392
545
  const validation = validateLogEntry(parsed);
393
546
  if (!validation.isValid) {
547
+ logger.debug(
548
+ `Schema validation failed: ${validation.warning ?? "Unknown format"}`,
549
+ context
550
+ );
394
551
  return null;
395
552
  }
396
553
  return parsed;
397
- } catch {
554
+ } catch (error) {
555
+ const errorMessage = error instanceof Error ? error.message : "Parse error";
556
+ logger.debug(`JSON parse failed: ${errorMessage}`, context);
398
557
  return null;
399
558
  }
400
559
  }
@@ -415,12 +574,14 @@ async function readJsonlFile(filePath) {
415
574
  try {
416
575
  const content = await readFile(filePath, "utf-8");
417
576
  const lines = content.split("\n");
577
+ let skippedLines = 0;
418
578
  for (let i = 0; i < lines.length; i++) {
419
579
  const line = lines[i] ?? "";
420
- const message = parseLine(line);
580
+ const lineNumber = i + 1;
581
+ const message = parseLine(line, lineNumber, filePath);
421
582
  if (message === null) {
422
583
  if (line.trim()) {
423
- warnings.push(`Skipped invalid line ${String(i + 1)} in ${filePath}`);
584
+ skippedLines++;
424
585
  }
425
586
  continue;
426
587
  }
@@ -439,9 +600,16 @@ async function readJsonlFile(filePath) {
439
600
  date: extractDate(message.timestamp)
440
601
  });
441
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
+ }
442
608
  } catch (error) {
443
609
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
444
- warnings.push(`Failed to read ${filePath}: ${errorMessage}`);
610
+ const warning = `Failed to read ${filePath}: ${errorMessage}`;
611
+ warnings.push(warning);
612
+ logger.error(warning, "log-reader");
445
613
  }
446
614
  return { prompts: prompts2, warnings };
447
615
  }
@@ -473,7 +641,9 @@ function filterByProject(prompts2, projectName) {
473
641
  );
474
642
  }
475
643
  async function readLogs(options) {
644
+ logger.debug(`Scanning ${CLAUDE_PROJECTS_DIR}`, "log-reader");
476
645
  if (!claudeProjectsExist()) {
646
+ logger.debug("Claude projects directory not found", "log-reader");
477
647
  return {
478
648
  prompts: [],
479
649
  warnings: [
@@ -483,6 +653,7 @@ async function readLogs(options) {
483
653
  }
484
654
  const pattern = `${CLAUDE_PROJECTS_DIR}/**/*.jsonl`;
485
655
  const files = await glob(pattern);
656
+ logger.debug(`Found ${String(files.length)} JSONL files`, "log-reader");
486
657
  if (files.length === 0) {
487
658
  return {
488
659
  prompts: [],
@@ -496,6 +667,10 @@ async function readLogs(options) {
496
667
  allPrompts.push(...prompts2);
497
668
  allWarnings.push(...warnings);
498
669
  }
670
+ logger.debug(
671
+ `Parsed ${String(allPrompts.length)} total prompts from all files`,
672
+ "log-reader"
673
+ );
499
674
  let filteredPrompts = allPrompts;
500
675
  if (options) {
501
676
  if (options.from && options.to) {
@@ -535,6 +710,15 @@ async function readLogs(options) {
535
710
  filteredPrompts = filterByProject(filteredPrompts, options.project);
536
711
  }
537
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
+ }
538
722
  const sortedPrompts = filteredPrompts.sort((a, b) => {
539
723
  try {
540
724
  const dateA = parseISO(a.timestamp);
@@ -544,6 +728,10 @@ async function readLogs(options) {
544
728
  return 0;
545
729
  }
546
730
  });
731
+ logger.debug(
732
+ `Returning ${String(sortedPrompts.length)} prompts for analysis`,
733
+ "log-reader"
734
+ );
547
735
  return {
548
736
  prompts: sortedPrompts,
549
737
  warnings: allWarnings
@@ -732,6 +920,7 @@ async function runSetup() {
732
920
  }
733
921
 
734
922
  // src/core/sanitizer.ts
923
+ init_logger();
735
924
  function redactOpenAIKeys(text) {
736
925
  return text.replace(/sk-[a-zA-Z0-9]{48,}/g, "[REDACTED_OPENAI_KEY]");
737
926
  }
@@ -822,7 +1011,12 @@ function redactUKNINO(text) {
822
1011
  );
823
1012
  }
824
1013
  function redactChileanRUN(text) {
825
- return text.replace(/\b\d{7,8}-?[0-9K]\b/gi, "[REDACTED_CHILEAN_RUN]");
1014
+ return text.replace(
1015
+ /\b(?:RUN|RUT)[\s:]*([0-9]{7,8}-[0-9K]|[0-9]{8}[0-9K])\b/gi,
1016
+ (match, run) => {
1017
+ return match.replace(run, "[REDACTED_CHILEAN_RUN]");
1018
+ }
1019
+ );
826
1020
  }
827
1021
  function redactArgentineDNI(text) {
828
1022
  return text.replace(
@@ -913,9 +1107,9 @@ function sanitize(text) {
913
1107
  sanitized = redactURLCredentials(sanitized);
914
1108
  sanitized = redactPEMKeys(sanitized);
915
1109
  sanitized = redactEmails(sanitized);
916
- sanitized = redactPhoneNumbers(sanitized);
917
1110
  sanitized = redactCreditCards(sanitized);
918
- sanitized = redactSSN(sanitized);
1111
+ sanitized = redactPassportNumbers(sanitized);
1112
+ sanitized = redactDriverLicenseNumbers(sanitized);
919
1113
  sanitized = redactSpanishDNI(sanitized);
920
1114
  sanitized = redactSpanishNIE(sanitized);
921
1115
  sanitized = redactMexicanCURP(sanitized);
@@ -923,14 +1117,14 @@ function sanitize(text) {
923
1117
  sanitized = redactUKNINO(sanitized);
924
1118
  sanitized = redactChileanRUN(sanitized);
925
1119
  sanitized = redactArgentineDNI(sanitized);
926
- sanitized = redactIPv4(sanitized);
927
- sanitized = redactIPv6(sanitized);
928
- sanitized = redactMACAddresses(sanitized);
929
- sanitized = redactPassportNumbers(sanitized);
930
- sanitized = redactDriverLicenseNumbers(sanitized);
931
1120
  sanitized = redactAddresses(sanitized);
932
1121
  sanitized = redactBirthDates(sanitized);
933
1122
  sanitized = redactNames(sanitized);
1123
+ sanitized = redactSSN(sanitized);
1124
+ sanitized = redactPhoneNumbers(sanitized);
1125
+ sanitized = redactIPv4(sanitized);
1126
+ sanitized = redactIPv6(sanitized);
1127
+ sanitized = redactMACAddresses(sanitized);
934
1128
  const redacted = countRedactions(text, sanitized);
935
1129
  return {
936
1130
  text: sanitized,
@@ -941,6 +1135,10 @@ function sanitizePrompts(prompts2) {
941
1135
  if (prompts2.length === 0) {
942
1136
  return { prompts: [], totalRedacted: 0 };
943
1137
  }
1138
+ logger.debug(
1139
+ `Sanitizing ${String(prompts2.length)} prompts for secrets`,
1140
+ "sanitizer"
1141
+ );
944
1142
  const sanitizedPrompts = [];
945
1143
  let totalRedacted = 0;
946
1144
  for (const prompt of prompts2) {
@@ -948,6 +1146,14 @@ function sanitizePrompts(prompts2) {
948
1146
  sanitizedPrompts.push(result.text);
949
1147
  totalRedacted += result.redacted;
950
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
+ }
951
1157
  return {
952
1158
  prompts: sanitizedPrompts,
953
1159
  totalRedacted
@@ -955,6 +1161,7 @@ function sanitizePrompts(prompts2) {
955
1161
  }
956
1162
 
957
1163
  // src/core/analyzer.ts
1164
+ init_logger();
958
1165
  var SYSTEM_OVERHEAD_TOKENS = 2e3;
959
1166
  var SEVERITY_RANK = {
960
1167
  high: 3,
@@ -1135,18 +1342,36 @@ function mergeBatchResults(options) {
1135
1342
  };
1136
1343
  }
1137
1344
  async function analyzePrompts(options) {
1138
- 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
+ );
1139
1350
  if (prompts2.length === 0) {
1140
1351
  throw new Error("Cannot analyze empty prompts array");
1141
1352
  }
1142
- 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
+ }
1143
1360
  const providerType = inferProviderType(provider.name);
1144
1361
  const limits = PROVIDER_LIMITS[providerType];
1362
+ logger.debug(
1363
+ `Using provider type: ${providerType} (limit: ${String(limits.maxTokensPerBatch)} tokens/batch)`,
1364
+ "analyzer"
1365
+ );
1145
1366
  const batches = batchPrompts({
1146
1367
  prompts: sanitizedPrompts,
1147
1368
  maxTokensPerBatch: limits.maxTokensPerBatch,
1148
1369
  prioritization: limits.prioritization
1149
1370
  });
1371
+ logger.debug(
1372
+ `Created ${String(batches.length)} batch(es) for analysis`,
1373
+ "analyzer"
1374
+ );
1150
1375
  if (batches.length === 1) {
1151
1376
  const batch = batches[0];
1152
1377
  if (!batch) {
@@ -1155,10 +1380,21 @@ async function analyzePrompts(options) {
1155
1380
  if (onProgress) {
1156
1381
  onProgress(0, 1);
1157
1382
  }
1158
- const result = await provider.analyze(batch.prompts, date);
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");
1159
1391
  if (onProgress) {
1160
1392
  onProgress(1, 1);
1161
1393
  }
1394
+ logger.debug(
1395
+ `Analysis complete: ${String(result.patterns.length)} patterns found`,
1396
+ "analyzer"
1397
+ );
1162
1398
  return result;
1163
1399
  }
1164
1400
  const results = [];
@@ -1169,13 +1405,29 @@ async function analyzePrompts(options) {
1169
1405
  if (onProgress) {
1170
1406
  onProgress(i, totalBatches);
1171
1407
  }
1172
- const result = await provider.analyze(batch.prompts, date);
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);
1173
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
+ );
1174
1420
  }
1175
1421
  if (onProgress) {
1176
1422
  onProgress(totalBatches, totalBatches);
1177
1423
  }
1178
- return mergeBatchResults({ results, date });
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;
1179
1431
  }
1180
1432
  function severityIcon(severity) {
1181
1433
  const icons = {
@@ -1334,6 +1586,15 @@ function printReport(result, options) {
1334
1586
  output.push(chalk3.dim(`Analysis Date: ${result.date}`));
1335
1587
  console.log(output.join("\n"));
1336
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();
1337
1598
 
1338
1599
  // src/providers/base.ts
1339
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.
@@ -1371,14 +1632,43 @@ Guidelines:
1371
1632
  - topSuggestion should be the most impactful single change
1372
1633
  - If no issues found, return empty patterns array with score 100
1373
1634
  - Be constructive and specific in suggestions`;
1374
- function buildUserPrompt(prompts2, date) {
1635
+ function buildUserPrompt(prompts2, date, context) {
1375
1636
  if (prompts2.length === 0) {
1376
1637
  throw new Error("Cannot build prompt from empty array");
1377
1638
  }
1378
1639
  const promptsList = prompts2.map((prompt, index) => `${String(index + 1)}. ${prompt}`).join("\n\n");
1379
1640
  const count = String(prompts2.length);
1380
1641
  const plural = prompts2.length === 1 ? "" : "s";
1381
- return `Analyze the following ${count} prompt${plural} from ${date}:
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}
1382
1672
 
1383
1673
  ${promptsList}
1384
1674
 
@@ -1478,6 +1768,7 @@ var OllamaProvider = class {
1478
1768
  * @returns Promise that resolves to true if available, false otherwise
1479
1769
  */
1480
1770
  async isAvailable() {
1771
+ logger.debug(`Connecting to Ollama at ${this.config.host}`, "ollama");
1481
1772
  try {
1482
1773
  const controller = new AbortController();
1483
1774
  const timeoutId = setTimeout(() => {
@@ -1488,16 +1779,34 @@ var OllamaProvider = class {
1488
1779
  });
1489
1780
  clearTimeout(timeoutId);
1490
1781
  if (!response.ok) {
1782
+ logger.debug(
1783
+ `Ollama API returned ${String(response.status)}`,
1784
+ "ollama"
1785
+ );
1491
1786
  return false;
1492
1787
  }
1493
1788
  const data = await response.json();
1494
1789
  if (!data.models || !Array.isArray(data.models)) {
1790
+ logger.debug("Ollama returned invalid model list", "ollama");
1495
1791
  return false;
1496
1792
  }
1497
- return data.models.some(
1793
+ const modelAvailable = data.models.some(
1498
1794
  (model) => model.name.includes(this.config.model)
1499
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;
1500
1808
  } catch {
1809
+ logger.debug("Ollama connection failed", "ollama");
1501
1810
  return false;
1502
1811
  }
1503
1812
  }
@@ -1507,14 +1816,15 @@ var OllamaProvider = class {
1507
1816
  *
1508
1817
  * @param prompts - Array of prompt strings to analyze
1509
1818
  * @param date - Date context for the analysis
1819
+ * @param context - Optional project context for analysis
1510
1820
  * @returns Promise resolving to AnalysisResult
1511
1821
  * @throws Error if analysis fails after retries or if response is invalid
1512
1822
  */
1513
- async analyze(prompts2, date) {
1823
+ async analyze(prompts2, date, context) {
1514
1824
  if (prompts2.length === 0) {
1515
1825
  throw new Error("Cannot analyze empty prompts array");
1516
1826
  }
1517
- const userPrompt = buildUserPrompt(prompts2, date);
1827
+ const userPrompt = buildUserPrompt(prompts2, date, context);
1518
1828
  let lastError;
1519
1829
  for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
1520
1830
  try {
@@ -1559,6 +1869,10 @@ var OllamaProvider = class {
1559
1869
  break;
1560
1870
  }
1561
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
+ );
1562
1876
  await sleep(delay);
1563
1877
  }
1564
1878
  }
@@ -1572,6 +1886,781 @@ function sleep(ms) {
1572
1886
  return new Promise((resolve) => setTimeout(resolve, ms));
1573
1887
  }
1574
1888
 
1889
+ // src/providers/anthropic.ts
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;
1973
+ var AVAILABILITY_TIMEOUT_MS2 = 5e3;
1974
+ var ANALYSIS_TIMEOUT_MS2 = 6e4;
1975
+ var BASE_DELAY_MS = 1e3;
1976
+ var MAX_DELAY_MS = 3e4;
1977
+ var API_BASE_URL = "https://api.anthropic.com";
1978
+ var API_VERSION = "2023-06-01";
1979
+ var MAX_TOKENS = 4096;
1980
+ var AnthropicProvider = class {
1981
+ name = "Anthropic";
1982
+ config;
1983
+ rateLimiter;
1984
+ /**
1985
+ * Creates a new AnthropicProvider instance.
1986
+ *
1987
+ * @param config - Anthropic configuration with model and API key
1988
+ */
1989
+ constructor(config) {
1990
+ this.config = config;
1991
+ this.rateLimiter = createRateLimiter({
1992
+ requestsPerMinute: DEFAULT_RATE_LIMITS.anthropic
1993
+ });
1994
+ }
1995
+ /**
1996
+ * Checks if the Anthropic API is available by validating the API key.
1997
+ * Makes a minimal request to verify the key is valid.
1998
+ *
1999
+ * @returns Promise that resolves to true if available, false otherwise
2000
+ */
2001
+ async isAvailable() {
2002
+ if (!this.config.apiKey) {
2003
+ logger.debug("No API key configured", "anthropic");
2004
+ return false;
2005
+ }
2006
+ logger.debug(
2007
+ `Validating API key with model ${this.config.model}`,
2008
+ "anthropic"
2009
+ );
2010
+ try {
2011
+ const controller = new AbortController();
2012
+ const timeoutId = setTimeout(() => {
2013
+ controller.abort();
2014
+ }, AVAILABILITY_TIMEOUT_MS2);
2015
+ const response = await fetch(`${API_BASE_URL}/v1/messages`, {
2016
+ method: "POST",
2017
+ headers: {
2018
+ "Content-Type": "application/json",
2019
+ "x-api-key": this.config.apiKey,
2020
+ "anthropic-version": API_VERSION
2021
+ },
2022
+ body: JSON.stringify({
2023
+ model: this.config.model,
2024
+ max_tokens: 1,
2025
+ messages: [{ role: "user", content: "Hi" }]
2026
+ }),
2027
+ signal: controller.signal
2028
+ });
2029
+ clearTimeout(timeoutId);
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;
2036
+ } catch {
2037
+ logger.debug("Connection failed", "anthropic");
2038
+ return false;
2039
+ }
2040
+ }
2041
+ /**
2042
+ * Analyzes prompts using the Anthropic Claude API.
2043
+ * Implements retry logic with exponential backoff for network errors.
2044
+ * Rate limited to prevent 429 errors during batch processing.
2045
+ *
2046
+ * @param prompts - Array of prompt strings to analyze
2047
+ * @param date - Date context for the analysis
2048
+ * @param context - Optional project context for analysis
2049
+ * @returns Promise resolving to AnalysisResult
2050
+ * @throws Error if analysis fails after retries or if response is invalid
2051
+ */
2052
+ async analyze(prompts2, date, context) {
2053
+ if (prompts2.length === 0) {
2054
+ throw new Error("Cannot analyze empty prompts array");
2055
+ }
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
2104
+ }
2105
+ )
2106
+ );
2107
+ }
2108
+ };
2109
+
2110
+ // src/providers/google.ts
2111
+ init_logger();
2112
+ var MAX_RETRIES3 = 3;
2113
+ var AVAILABILITY_TIMEOUT_MS3 = 5e3;
2114
+ var ANALYSIS_TIMEOUT_MS3 = 6e4;
2115
+ var BASE_DELAY_MS2 = 1e3;
2116
+ var MAX_DELAY_MS2 = 3e4;
2117
+ var API_BASE_URL2 = "https://generativelanguage.googleapis.com/v1beta";
2118
+ var GoogleProvider = class {
2119
+ name = "Google";
2120
+ config;
2121
+ rateLimiter;
2122
+ /**
2123
+ * Creates a new GoogleProvider instance.
2124
+ *
2125
+ * @param config - Google configuration with model and API key
2126
+ */
2127
+ constructor(config) {
2128
+ this.config = config;
2129
+ this.rateLimiter = createRateLimiter({
2130
+ requestsPerMinute: DEFAULT_RATE_LIMITS.google
2131
+ });
2132
+ }
2133
+ /**
2134
+ * Checks if the Google Gemini API is available by validating the API key.
2135
+ * Makes a minimal request to verify the key is valid.
2136
+ *
2137
+ * @returns Promise that resolves to true if available, false otherwise
2138
+ */
2139
+ async isAvailable() {
2140
+ if (!this.config.apiKey) {
2141
+ logger.debug("No API key configured", "google");
2142
+ return false;
2143
+ }
2144
+ logger.debug(
2145
+ `Validating API key with model ${this.config.model}`,
2146
+ "google"
2147
+ );
2148
+ try {
2149
+ const controller = new AbortController();
2150
+ const timeoutId = setTimeout(() => {
2151
+ controller.abort();
2152
+ }, AVAILABILITY_TIMEOUT_MS3);
2153
+ const url = `${API_BASE_URL2}/models/${this.config.model}:generateContent?key=${this.config.apiKey}`;
2154
+ const response = await fetch(url, {
2155
+ method: "POST",
2156
+ headers: {
2157
+ "Content-Type": "application/json"
2158
+ },
2159
+ body: JSON.stringify({
2160
+ contents: [
2161
+ {
2162
+ role: "user",
2163
+ parts: [{ text: "Hi" }]
2164
+ }
2165
+ ],
2166
+ generationConfig: {
2167
+ maxOutputTokens: 1
2168
+ }
2169
+ }),
2170
+ signal: controller.signal
2171
+ });
2172
+ clearTimeout(timeoutId);
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;
2179
+ } catch {
2180
+ logger.debug("Connection failed", "google");
2181
+ return false;
2182
+ }
2183
+ }
2184
+ /**
2185
+ * Analyzes prompts using the Google Gemini API.
2186
+ * Implements retry logic with exponential backoff for network errors.
2187
+ * Rate limited to prevent 429 errors during batch processing.
2188
+ *
2189
+ * @param prompts - Array of prompt strings to analyze
2190
+ * @param date - Date context for the analysis
2191
+ * @param context - Optional project context for analysis
2192
+ * @returns Promise resolving to AnalysisResult
2193
+ * @throws Error if analysis fails after retries or if response is invalid
2194
+ */
2195
+ async analyze(prompts2, date, context) {
2196
+ if (prompts2.length === 0) {
2197
+ throw new Error("Cannot analyze empty prompts array");
2198
+ }
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
+ );
2236
+ }
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
2252
+ }
2253
+ )
2254
+ );
2255
+ }
2256
+ };
2257
+
2258
+ // src/providers/index.ts
2259
+ function createProvider(type, config) {
2260
+ switch (type) {
2261
+ case "ollama":
2262
+ return new OllamaProvider(config.ollama);
2263
+ case "anthropic":
2264
+ return new AnthropicProvider(config.anthropic);
2265
+ case "google":
2266
+ return new GoogleProvider(config.google);
2267
+ }
2268
+ }
2269
+ async function getAvailableProvider(config, onFallback) {
2270
+ if (config.services.length === 0) {
2271
+ throw new Error(
2272
+ "No providers configured. Please run hyntx setup to configure providers."
2273
+ );
2274
+ }
2275
+ logger.debug(
2276
+ `Checking ${String(config.services.length)} configured provider(s): ${config.services.join(", ")}`,
2277
+ "provider"
2278
+ );
2279
+ let firstProvider;
2280
+ for (const type of config.services) {
2281
+ const provider = createProvider(type, config);
2282
+ firstProvider ??= provider;
2283
+ logger.debug(`Checking availability of ${provider.name}...`, "provider");
2284
+ try {
2285
+ const isAvailable = await provider.isAvailable();
2286
+ if (isAvailable) {
2287
+ logger.debug(`${provider.name} is available`, "provider");
2288
+ if (onFallback && provider !== firstProvider) {
2289
+ onFallback(firstProvider.name, provider.name);
2290
+ }
2291
+ return provider;
2292
+ } else {
2293
+ logger.debug(`${provider.name} is not available`, "provider");
2294
+ }
2295
+ } catch {
2296
+ logger.debug(`${provider.name} availability check failed`, "provider");
2297
+ continue;
2298
+ }
2299
+ }
2300
+ throw new Error(
2301
+ "No providers are currently available. Please check your provider configurations."
2302
+ );
2303
+ }
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
+
1575
2664
  // src/index.ts
1576
2665
  var currentDir = dirname(fileURLToPath(import.meta.url));
1577
2666
  var packageJson = JSON.parse(
@@ -1586,6 +2675,23 @@ function parseArguments() {
1586
2675
  type: "string",
1587
2676
  default: "today"
1588
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
+ },
1589
2695
  help: {
1590
2696
  type: "boolean",
1591
2697
  short: "h",
@@ -1602,7 +2708,11 @@ function parseArguments() {
1602
2708
  return {
1603
2709
  date: values.date || "today",
1604
2710
  help: values.help || false,
1605
- 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
1606
2716
  };
1607
2717
  } catch (error) {
1608
2718
  const errorMessage = error instanceof Error ? error.message : String(error);
@@ -1614,9 +2724,13 @@ function showHelp() {
1614
2724
  ${chalk3.bold("Usage:")} hyntx [options]
1615
2725
 
1616
2726
  ${chalk3.bold("Options:")}
1617
- --date <date> Date to analyze (today, yesterday, YYYY-MM-DD) [default: today]
1618
- -h, --help Show help
1619
- --version Show version
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
1620
2734
 
1621
2735
  ${chalk3.bold("Exit codes:")}
1622
2736
  ${String(EXIT_CODES.SUCCESS)} - Success
@@ -1625,9 +2739,11 @@ ${chalk3.bold("Exit codes:")}
1625
2739
  ${String(EXIT_CODES.PROVIDER_UNAVAILABLE)} - Provider unavailable
1626
2740
 
1627
2741
  ${chalk3.bold("Examples:")}
1628
- hyntx # Analyze today's prompts
1629
- hyntx --date yesterday # Analyze yesterday
1630
- hyntx --date 2025-01-20 # Specific date
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
1631
2747
  `;
1632
2748
  console.log(helpText);
1633
2749
  process.exit(EXIT_CODES.SUCCESS);
@@ -1636,136 +2752,244 @@ function showVersion() {
1636
2752
  console.log(`hyntx v${VERSION}`);
1637
2753
  process.exit(EXIT_CODES.SUCCESS);
1638
2754
  }
1639
- async function checkAndRunSetup() {
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) {
1640
2769
  if (isFirstRun()) {
1641
- const spinner = ora("Running first-time setup...").start();
1642
- spinner.stop();
2770
+ if (!isJsonMode) {
2771
+ const spinner = ora("Running first-time setup...").start();
2772
+ spinner.stop();
2773
+ }
1643
2774
  await runSetup();
1644
2775
  }
1645
2776
  }
1646
- async function readLogsWithSpinner(date) {
2777
+ async function readLogsWithSpinner(date, isJsonMode) {
1647
2778
  if (!claudeProjectsExist()) {
1648
- console.error(chalk3.red("Error: Claude Code logs directory not found"));
1649
- console.error(chalk3.dim(`Expected location: ${CLAUDE_PROJECTS_DIR}`));
1650
- console.error(
1651
- chalk3.dim(
1652
- "\nMake sure Claude Code is installed and has been used at least once."
1653
- )
1654
- );
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
+ }
1655
2797
  process.exit(EXIT_CODES.NO_DATA);
1656
2798
  }
1657
- const spinner = ora(`Reading Claude Code logs for ${date}...`).start();
2799
+ const spinner = isJsonMode ? null : ora(`Reading Claude Code logs for ${date}...`).start();
1658
2800
  try {
1659
2801
  const result = await readLogs({ date });
1660
2802
  if (result.prompts.length === 0) {
1661
- spinner.fail(chalk3.yellow(`No prompts found for ${date}`));
1662
- console.error(
1663
- chalk3.dim(
1664
- "\nTry a different date or check that Claude Code has been used recently."
1665
- )
1666
- );
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
+ }
1667
2817
  process.exit(EXIT_CODES.NO_DATA);
1668
2818
  }
1669
- spinner.succeed(
1670
- chalk3.green(`Found ${String(result.prompts.length)} prompts for ${date}`)
1671
- );
1672
- if (result.warnings.length > 0) {
1673
- for (const warning of result.warnings) {
1674
- console.warn(chalk3.yellow(`Warning: ${warning}`));
1675
- }
2819
+ if (!isJsonMode) {
2820
+ spinner?.succeed(
2821
+ chalk3.green(
2822
+ `Found ${String(result.prompts.length)} prompts for ${date}`
2823
+ )
2824
+ );
1676
2825
  }
1677
2826
  return result.prompts.map((p) => p.content);
1678
2827
  } catch (error) {
1679
2828
  const errorMessage = error instanceof Error ? error.message : String(error);
1680
- spinner.fail(chalk3.red(`Failed to read logs: ${errorMessage}`));
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
+ }
1681
2838
  process.exit(EXIT_CODES.ERROR);
1682
2839
  }
1683
2840
  }
1684
- async function connectProviderWithSpinner() {
2841
+ async function connectProviderWithSpinner(isJsonMode) {
1685
2842
  const config = getEnvConfig();
1686
- if (!config.services.includes("ollama")) {
1687
- console.error(chalk3.red("Error: Ollama provider not configured"));
1688
- console.error(
1689
- chalk3.dim("\nRun setup again to configure Ollama as a provider.")
1690
- );
2843
+ if (config.services.length === 0) {
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
+ }
1691
2856
  process.exit(EXIT_CODES.PROVIDER_UNAVAILABLE);
1692
2857
  }
1693
- const spinner = ora("Connecting to Ollama...").start();
2858
+ const spinner = isJsonMode ? null : ora("Connecting to provider...").start();
1694
2859
  try {
1695
- const provider = new OllamaProvider(config.ollama);
1696
- const isAvailable = await provider.isAvailable();
1697
- if (!isAvailable) {
1698
- spinner.fail(chalk3.red("Ollama service not available"));
1699
- console.error(
1700
- chalk3.dim(
1701
- `
1702
- Make sure Ollama is running: ${chalk3.bold("ollama serve")}`
1703
- )
1704
- );
1705
- console.error(
1706
- chalk3.dim(
1707
- `And the model "${config.ollama.model}" is installed: ${chalk3.bold(`ollama pull ${config.ollama.model}`)}`
1708
- )
2860
+ const provider = await getAvailableProvider(config, (from, to) => {
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"
1709
2869
  );
1710
- process.exit(EXIT_CODES.PROVIDER_UNAVAILABLE);
2870
+ });
2871
+ if (!isJsonMode) {
2872
+ spinner?.succeed(chalk3.green(`Connected to ${provider.name}`));
1711
2873
  }
1712
- spinner.succeed(
1713
- chalk3.green(`Connected to Ollama (${config.ollama.model})`)
1714
- );
1715
2874
  return provider;
1716
2875
  } catch (error) {
1717
2876
  const errorMessage = error instanceof Error ? error.message : String(error);
1718
- spinner.fail(chalk3.red(`Failed to connect: ${errorMessage}`));
1719
- process.exit(EXIT_CODES.ERROR);
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
+ }
2894
+ process.exit(EXIT_CODES.PROVIDER_UNAVAILABLE);
1720
2895
  }
1721
2896
  }
1722
- async function analyzeWithProgress(provider, prompts2, date) {
1723
- 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();
1724
2899
  try {
1725
2900
  const result = await analyzePrompts({
1726
2901
  provider,
1727
2902
  prompts: prompts2,
1728
2903
  date,
2904
+ context,
1729
2905
  onProgress: (current, total) => {
1730
- if (total > 1) {
2906
+ if (!isJsonMode && spinner && total > 1) {
1731
2907
  spinner.text = `Analyzing ${String(prompts2.length)} prompts (batch ${String(current + 1)}/${String(total)})...`;
1732
2908
  }
1733
2909
  }
1734
2910
  });
1735
- spinner.succeed(chalk3.green("Analysis complete"));
2911
+ if (!isJsonMode) {
2912
+ spinner?.succeed(chalk3.green("Analysis complete"));
2913
+ }
1736
2914
  return result;
1737
2915
  } catch (error) {
1738
2916
  const errorMessage = error instanceof Error ? error.message : String(error);
1739
- spinner.fail(chalk3.red(`Analysis failed: ${errorMessage}`));
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
+ }
1740
2926
  process.exit(EXIT_CODES.ERROR);
1741
2927
  }
1742
2928
  }
1743
- function displayResults(result) {
1744
- console.log("");
1745
- printReport(result);
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
+ }
1746
2936
  }
1747
- function handleError(error) {
1748
- console.error(chalk3.red(`
1749
- Error: ${error.message}`));
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
+ }
1750
2947
  process.exit(EXIT_CODES.ERROR);
1751
2948
  }
1752
2949
  async function main() {
2950
+ let isJsonMode = false;
1753
2951
  try {
1754
2952
  const args = parseArguments();
2953
+ isJsonMode = args.format === "json";
2954
+ if (args.verbose) {
2955
+ logger.setVerbose(true);
2956
+ logger.debug("Verbose mode enabled");
2957
+ }
1755
2958
  if (args.help) {
1756
2959
  showHelp();
1757
2960
  }
1758
2961
  if (args.version) {
1759
2962
  showVersion();
1760
2963
  }
1761
- await checkAndRunSetup();
1762
- const prompts2 = await readLogsWithSpinner(args.date);
1763
- const provider = await connectProviderWithSpinner();
1764
- const result = await analyzeWithProgress(provider, prompts2, args.date);
1765
- displayResults(result);
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
+ }
1766
2984
  process.exit(EXIT_CODES.SUCCESS);
1767
2985
  } catch (error) {
1768
- handleError(error instanceof Error ? error : new Error(String(error)));
2986
+ if (!isJsonMode) {
2987
+ logger.reportWarnings();
2988
+ }
2989
+ handleError(
2990
+ error instanceof Error ? error : new Error(String(error)),
2991
+ isJsonMode
2992
+ );
1769
2993
  }
1770
2994
  }
1771
2995
  var isMainModule = process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];
@@ -1773,6 +2997,6 @@ if (isMainModule) {
1773
2997
  void main();
1774
2998
  }
1775
2999
 
1776
- export { analyzeWithProgress, checkAndRunSetup, connectProviderWithSpinner, displayResults, handleError, main, parseArguments, readLogsWithSpinner, showHelp, showVersion };
3000
+ export { analyzeWithProgress, checkAndRunSetup, connectProviderWithSpinner, displayResults, handleError, main, parseArguments, readLogsWithSpinner, runConfigCheck, showHelp, showVersion };
1777
3001
  //# sourceMappingURL=index.js.map
1778
3002
  //# sourceMappingURL=index.js.map