@ik-firewall/core 1.0.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/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@ik-firewall/core",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "The core IK Firewall engine for semantic-driven AI optimization.",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/index.js",
12
+ "require": "./dist/index.cjs",
13
+ "types": "./dist/index.d.ts"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist",
18
+ "scripts"
19
+ ],
20
+ "scripts": {
21
+ "prepare": "npm run build",
22
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean",
23
+ "dev": "tsup src/index.ts --format cjs,esm --watch --dts",
24
+ "lint": "eslint src/**/*.ts",
25
+ "test": "jest",
26
+ "setup-ai": "node scripts/master-setup.js",
27
+ "start-ai": "node scripts/start-ai.js",
28
+ "postinstall": "node scripts/setup-runtime.js"
29
+ },
30
+ "keywords": [
31
+ "ai",
32
+ "firewall",
33
+ "semantic",
34
+ "llm",
35
+ "optimization"
36
+ ],
37
+ "author": "Stefan Vasic",
38
+ "license": "MIT",
39
+ "devDependencies": {
40
+ "@types/node": "^25.0.10",
41
+ "tsup": "^8.0.0",
42
+ "typescript": "^5.0.0"
43
+ }
44
+ }
@@ -0,0 +1,56 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import https from 'https';
4
+ import { execSync } from 'child_process';
5
+ import { fileURLToPath } from 'url';
6
+
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = path.dirname(__filename);
9
+
10
+ const LLAMA_ZIP_URL = 'https://github.com/ggerganov/llama.cpp/releases/download/b4461/llama-b4461-bin-win-avx2-x64.zip';
11
+ const BIN_DIR = path.join(__dirname, '..', '.bin');
12
+ const ZIP_PATH = path.join(BIN_DIR, 'llama-bin.zip');
13
+
14
+ async function downloadFile(url, dest) {
15
+ return new Promise((resolve, reject) => {
16
+ const file = fs.createWriteStream(dest);
17
+ https.get(url, (response) => {
18
+ if (response.statusCode === 301 || response.statusCode === 302) {
19
+ downloadFile(response.headers.location, dest).then(resolve).catch(reject);
20
+ return;
21
+ }
22
+ response.pipe(file);
23
+ file.on('finish', () => {
24
+ file.close(() => resolve());
25
+ });
26
+ }).on('error', (err) => {
27
+ fs.unlink(dest, () => {});
28
+ reject(err);
29
+ });
30
+ });
31
+ }
32
+
33
+ async function setupLlamaBin() {
34
+ if (!fs.existsSync(BIN_DIR)) fs.mkdirSync(BIN_DIR, { recursive: true });
35
+
36
+ try {
37
+ console.log('๐Ÿ“ก Downloading precompiled llama.cpp binary...');
38
+ await downloadFile(LLAMA_ZIP_URL, ZIP_PATH);
39
+ console.log('โœ… Download complete.');
40
+
41
+ // Use tar -xf (supported on Windows 10/11)
42
+ console.log('๐Ÿ“ฆ Extracting binary using tar...');
43
+ execSync(`tar -xf "${ZIP_PATH}" -C "${BIN_DIR}"`);
44
+ console.log('โœ… Extraction complete.');
45
+
46
+ console.log('๐Ÿงน Cleaning up...');
47
+ if (fs.existsSync(ZIP_PATH)) fs.unlinkSync(ZIP_PATH);
48
+
49
+ console.log('โœจ Local Llama ecosystem is ready.');
50
+ } catch (e) {
51
+ console.error('โŒ Binary setup failed:', e.message);
52
+ console.log('๐Ÿ’ก Note: If tar failed, you might need to manually unzip llama-bin.zip in the .bin folder.');
53
+ }
54
+ }
55
+
56
+ setupLlamaBin();
@@ -0,0 +1,51 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import https from 'https';
4
+ import { fileURLToPath } from 'url';
5
+
6
+ const __filename = fileURLToPath(import.meta.url);
7
+ const __dirname = path.dirname(__filename);
8
+
9
+ const MODEL_URL = 'https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf?download=true';
10
+ const BIN_DIR = path.join(__dirname, '..', '.bin');
11
+ const MODEL_PATH = path.join(BIN_DIR, 'ik-local-1b-v1.gguf');
12
+
13
+ async function downloadModel() {
14
+ if (!fs.existsSync(BIN_DIR)) {
15
+ fs.mkdirSync(BIN_DIR, { recursive: true });
16
+ }
17
+
18
+ if (fs.existsSync(MODEL_PATH) && fs.statSync(MODEL_PATH).size > 1000000) {
19
+ console.log('โœ… Model already exists, skipping download.');
20
+ return;
21
+ }
22
+
23
+ console.log('๐Ÿ“ก Downloading Llama-3.2-1B model (approx. 640MB)... This may take a few minutes.');
24
+
25
+ // Deleting placeholder if exists
26
+ if (fs.existsSync(MODEL_PATH)) fs.unlinkSync(MODEL_PATH);
27
+
28
+ const file = fs.createWriteStream(MODEL_PATH);
29
+
30
+ https.get(MODEL_URL, (response) => {
31
+ if (response.statusCode === 302 || response.statusCode === 301) {
32
+ // Handle redirect
33
+ https.get(response.headers.location, (res) => {
34
+ res.pipe(file);
35
+ res.on('end', () => {
36
+ console.log('โœ… Model download complete: ik-local-1b-v1.gguf');
37
+ });
38
+ });
39
+ } else {
40
+ response.pipe(file);
41
+ response.on('end', () => {
42
+ console.log('โœ… Model download complete: ik-local-1b-v1.gguf');
43
+ });
44
+ }
45
+ }).on('error', (err) => {
46
+ console.error('โŒ Download failed:', err.message);
47
+ fs.unlink(MODEL_PATH, () => {});
48
+ });
49
+ }
50
+
51
+ downloadModel();
@@ -0,0 +1,102 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import https from 'https';
4
+ import { execSync } from 'child_process';
5
+ import { fileURLToPath } from 'url';
6
+
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = path.dirname(__filename);
9
+
10
+ const BIN_DIR = path.join(__dirname, '..', '.bin');
11
+ const MODEL_NAME = 'ik-local-1b-v1.gguf';
12
+ const MODEL_PATH = path.join(BIN_DIR, MODEL_NAME);
13
+
14
+ // Using stable, direct URLs from known mirrors to avoid redirect hell
15
+ const CONFIG = {
16
+ modelUrl: 'https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf?download=true',
17
+ serverUrl: 'https://github.com/ggml-org/llama.cpp/releases/download/b7708/llama-b7708-bin-win-cpu-x64.zip',
18
+ serverExe: 'llama-server.exe'
19
+ };
20
+
21
+ /**
22
+ * Robust HTTPS Downloader with redirect follow
23
+ */
24
+ function download(url, dest) {
25
+ return new Promise((resolve, reject) => {
26
+ const file = fs.createWriteStream(dest);
27
+ https.get(url, (res) => {
28
+ if (res.statusCode === 301 || res.statusCode === 302) {
29
+ file.close();
30
+ download(res.headers.location, dest).then(resolve).catch(reject);
31
+ return;
32
+ }
33
+ if (res.statusCode !== 200) {
34
+ file.close();
35
+ fs.unlink(dest, () => {});
36
+ reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`));
37
+ return;
38
+ }
39
+ res.pipe(file);
40
+ file.on('finish', () => {
41
+ file.close();
42
+ resolve();
43
+ });
44
+ }).on('error', (err) => {
45
+ file.close();
46
+ fs.unlink(dest, () => {});
47
+ reject(err);
48
+ });
49
+ });
50
+ }
51
+
52
+ async function setup() {
53
+ console.log('\n๐Ÿง  IK_FIREWALL: Initiating Zero-Config AI Setup...');
54
+ console.log('------------------------------------------------');
55
+
56
+ if (!fs.existsSync(BIN_DIR)) fs.mkdirSync(BIN_DIR, { recursive: true });
57
+
58
+ // 1. Check Model
59
+ if (fs.existsSync(MODEL_PATH) && fs.statSync(MODEL_PATH).size > 100000000) {
60
+ console.log('โœ… Local Model: DETECTED');
61
+ } else {
62
+ console.log('๐Ÿ“ก Downloading 1B Model (~640MB). Please wait...');
63
+ try {
64
+ await download(CONFIG.modelUrl, MODEL_PATH);
65
+ console.log('โœ… Local Model: INSTALLED');
66
+ } catch (e) {
67
+ console.error('โŒ Failed to download model:', e.message);
68
+ }
69
+ }
70
+
71
+ // 2. Check Server
72
+ const serverPath = path.join(BIN_DIR, CONFIG.serverExe);
73
+ if (fs.existsSync(serverPath)) {
74
+ console.log('โœ… AI Server Engine: DETECTED');
75
+ } else {
76
+ console.log('๐Ÿ“ก Fetching AI Server Engine (Windows x64)...');
77
+ const zipPath = path.join(BIN_DIR, 'server.zip');
78
+ try {
79
+ await download(CONFIG.serverUrl, zipPath);
80
+ console.log('๐Ÿ“ฆ Extracting server engine...');
81
+
82
+ // Native Windows extraction via tar (faster and handle-safe)
83
+ try {
84
+ execSync(`tar -xf "${zipPath}" -C "${BIN_DIR}"`);
85
+ } catch (tarE) {
86
+ // Fallback for older Win10
87
+ execSync(`powershell -Command "Expand-Archive -Path '${zipPath}' -DestinationPath '${BIN_DIR}' -Force"`);
88
+ }
89
+
90
+ fs.unlinkSync(zipPath);
91
+ console.log('โœ… AI Server Engine: INSTALLED');
92
+ } catch (e) {
93
+ console.error('โŒ Failed to setup server:', e.message);
94
+ }
95
+ }
96
+
97
+ console.log('------------------------------------------------');
98
+ console.log('โœจ IK ARCHITECTURE IS ARMED AND READY.');
99
+ console.log('๐Ÿ’ก Run "node scripts/start-ai.js" to begin local audit.');
100
+ }
101
+
102
+ setup();
@@ -0,0 +1,67 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import https from 'https';
4
+ import { execSync } from 'child_process';
5
+ import { fileURLToPath } from 'url';
6
+
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = path.dirname(__filename);
9
+
10
+ // Tag b4461 seems stable, but let's try b7708 as it was found in latest
11
+ const LLAMA_ZIP_URL = 'https://github.com/ggml-org/llama.cpp/releases/download/b4461/llama-b4461-bin-win-avx2-x64.zip';
12
+ const BIN_DIR = path.join(__dirname, '..', '.bin');
13
+ const ZIP_PATH = path.join(BIN_DIR, 'llama-bin.zip');
14
+
15
+ async function download(url, dest) {
16
+ return new Promise((resolve, reject) => {
17
+ https.get(url, (res) => {
18
+ if (res.statusCode === 301 || res.statusCode === 302) {
19
+ console.log(`๐Ÿ“ก Redirecting to: ${res.headers.location}`);
20
+ download(res.headers.location, dest).then(resolve).catch(reject);
21
+ return;
22
+ }
23
+ if (res.statusCode !== 200) {
24
+ reject(new Error(`Server responded with ${res.statusCode}: ${res.statusMessage}`));
25
+ return;
26
+ }
27
+ const file = fs.createWriteStream(dest);
28
+ res.pipe(file);
29
+ file.on('finish', () => {
30
+ file.close();
31
+ resolve();
32
+ });
33
+ }).on('error', (err) => {
34
+ fs.unlink(dest, () => {});
35
+ reject(err);
36
+ });
37
+ });
38
+ }
39
+
40
+ async function start() {
41
+ if (!fs.existsSync(BIN_DIR)) fs.mkdirSync(BIN_DIR, { recursive: true });
42
+
43
+ try {
44
+ console.log(`๐Ÿš€ Starting robust download from: ${LLAMA_ZIP_URL}`);
45
+ await download(LLAMA_ZIP_URL, ZIP_PATH);
46
+ console.log('โœ… ZIP downloaded successfully.');
47
+
48
+ console.log('๐Ÿ“ฆ Extracting assets...');
49
+ // tar -xf is versatile and usually present in modern Windows
50
+ try {
51
+ execSync(`tar -xf "${ZIP_PATH}" -C "${BIN_DIR}"`);
52
+ console.log('โœ… Extraction complete via tar.');
53
+ } catch (tarError) {
54
+ console.log('โš ๏ธ tar failed, trying PowerShell Expand-Archive...');
55
+ execSync(`powershell -Command "Expand-Archive -Path '${ZIP_PATH}' -DestinationPath '${BIN_DIR}' -Force"`);
56
+ console.log('โœ… Extraction complete via PowerShell.');
57
+ }
58
+
59
+ fs.unlinkSync(ZIP_PATH);
60
+ console.log('โœจ Cleanup done. Local engine is ARMED.');
61
+ } catch (err) {
62
+ console.error(`โŒ FAILURE: ${err.message}`);
63
+ process.exit(1);
64
+ }
65
+ }
66
+
67
+ start();
@@ -0,0 +1,104 @@
1
+ import http from 'http';
2
+
3
+ const PORT = 8080;
4
+
5
+ /**
6
+ * IK-RUNTIME EMULATOR (V1.0.0-PROTO)
7
+ * This script simulates the local 1B model server for development and testing.
8
+ */
9
+ const server = http.createServer((req, res) => {
10
+ // Add CORS headers for local development if needed
11
+ res.setHeader('Access-Control-Allow-Origin', '*');
12
+ res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
13
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
14
+
15
+ if (req.method === 'OPTIONS') {
16
+ res.writeHead(204);
17
+ res.end();
18
+ return;
19
+ }
20
+
21
+ if (req.url === '/v1/chat/completions' && req.method === 'POST') {
22
+ let body = '';
23
+ req.on('data', chunk => { body += chunk.toString(); });
24
+ req.on('end', () => {
25
+ try {
26
+ const parsed = JSON.parse(body);
27
+ const userPrompt = parsed.messages?.[0]?.content || '';
28
+
29
+ console.log(`[IK-RUNTIME] Received Audit Request: "${userPrompt.substring(0, 50)}..."`);
30
+
31
+ // Simulated 1B Model Logic: Semantic Analysis
32
+ const length = userPrompt.length;
33
+ const isEngineering = userPrompt.toLowerCase().includes('function') || userPrompt.toLowerCase().includes('code');
34
+ const isLegal = userPrompt.toLowerCase().includes('contract') || userPrompt.toLowerCase().includes('terms');
35
+
36
+ const mockResponse = {
37
+ id: 'chatcmpl-mock-123',
38
+ object: 'chat.completion',
39
+ created: Date.now(),
40
+ model: 'ik-local-1b-v1',
41
+ choices: [{
42
+ index: 0,
43
+ message: {
44
+ role: 'assistant',
45
+ content: JSON.stringify({
46
+ metaphoricalScale: 0.15,
47
+ conceptualUnitsCount: Math.ceil(length / 20),
48
+ redundancyRatio: 0.12,
49
+ semanticProof: 0.95,
50
+ cognitiveKinetic: 0.85,
51
+ conceptualBlueprint: "SYSTEM_CORE_OPTIMIZED: Analyzing " + (isEngineering ? "Technical Structure" : "Conceptual Essence"),
52
+ noiseClusters: ["redundant", "filler", "extra"],
53
+ immutableEntities: isEngineering ? ["logic", "algorithm"] : ["intent", "value"],
54
+ intentMode: isEngineering ? "ENGINEERING" : (isLegal ? "SPECIALIZED" : "CONCEPTUAL"),
55
+ cognitiveDepth: "L2-ANALYTICAL",
56
+ activeLayers: ["L1", "L2"],
57
+ precisionRequired: isEngineering || isLegal,
58
+ engine_tuning_recommendation: "Increase precisionBias for higher dm output.",
59
+ detectedDomain: isEngineering ? "ENGINEERING" : (isLegal ? "LEGAL" : "GENERAL"),
60
+ illocutionaryPoint: "ASSERTIVE",
61
+ rhetoricalRatio: { ethos: 0.2, pathos: 0.1, logos: 0.7 },
62
+ toneVector: { abstraction: 0.2, directness: 0.7, density: 0.5 },
63
+ kft: isEngineering ? 8 : 4,
64
+ opt: 3,
65
+ approach: { category: isEngineering ? "PROBLEM_ORIENTED" : "DIRECTIVE", subtype: "analysis" }
66
+ })
67
+ },
68
+ finish_reason: 'stop'
69
+ }],
70
+ usage: {
71
+ prompt_tokens: Math.ceil(length / 4),
72
+ completion_tokens: 150,
73
+ total_tokens: Math.ceil(length / 4) + 150
74
+ }
75
+ };
76
+
77
+ res.writeHead(200, { 'Content-Type': 'application/json' });
78
+ res.end(JSON.stringify(mockResponse));
79
+ console.log(`โœ… [IK-RUNTIME] Audit Delivered (Local).`);
80
+ } catch (e) {
81
+ res.writeHead(400);
82
+ res.end(JSON.stringify({ error: "Invalid JSON" }));
83
+ }
84
+ });
85
+ } else if (req.url === '/v1/health') {
86
+ res.writeHead(200, { 'Content-Type': 'application/json' });
87
+ res.end(JSON.stringify({ status: 'ok', engine: 'IK-Emulator-v1' }));
88
+ } else {
89
+ res.writeHead(404);
90
+ res.end();
91
+ }
92
+ });
93
+
94
+ server.listen(PORT, () => {
95
+ console.log(`
96
+ IK_FIREWALL: RUNTIME EMULATOR ACTIVE
97
+ -----------------------------------
98
+ Port: ${PORT}
99
+ Mode: Local Audit Simulation (1B)
100
+ Status: Waiting for kognitive signals...
101
+ -----------------------------------
102
+ (Leave this window open for idea-analyzer to use Local Audit)
103
+ `);
104
+ });
@@ -0,0 +1,44 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'url';
4
+
5
+ const __filename = fileURLToPath(import.meta.url);
6
+ const __dirname = path.dirname(__filename);
7
+
8
+ // Constants
9
+ const BIN_DIR = path.join(__dirname, '..', '.bin');
10
+ const RUNTIME_NAME = process.platform === 'win32' ? 'ik-runtime.exe' : 'ik-runtime';
11
+ const MODEL_NAME = 'ik-local-1b-v1.gguf';
12
+
13
+ async function setup() {
14
+ if (process.env.CI || process.env.VERCEL) {
15
+ console.log('โญ๏ธ IK_FIREWALL: CI/Vercel environment detected. Skipping local runtime setup.');
16
+ return;
17
+ }
18
+ console.log('๐Ÿš€ IK_FIREWALL: Initiating Zero-Config Runtime Setup...');
19
+
20
+ // 1. Create .bin directory
21
+ if (!fs.existsSync(BIN_DIR)) {
22
+ fs.mkdirSync(BIN_DIR, { recursive: true });
23
+ console.log(`โœ… Created directory: ${BIN_DIR}`);
24
+ }
25
+
26
+ // 2. Detect OS & Architecture
27
+ const platform = process.platform;
28
+ const arch = process.arch;
29
+ console.log(`๐Ÿ” Detected environment: ${platform}-${arch}`);
30
+
31
+ // 3. Inform user about the Emulator (since binary is OS-dependent)
32
+ const emulatorPath = path.join(__dirname, 'runtime-emulator.js');
33
+ console.log(`\n๐Ÿ’ก TIP: For this prototype on Windows, use the Node.js Emulator instead of the .exe:`);
34
+ console.log(` node scripts/runtime-emulator.js`);
35
+
36
+ // Create a helper dev script in package.json context or similar
37
+ console.log('\n๐Ÿ“ฆ IK-Runtime environment prepared.');
38
+ console.log('โœจ IK Adapter is now ready for local escalation testing!');
39
+ }
40
+
41
+ setup().catch(err => {
42
+ console.error('โŒ IK_FIREWALL Setup Failed:', err.message);
43
+ process.exit(1);
44
+ });
@@ -0,0 +1,38 @@
1
+ import { spawn } from 'child_process';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'url';
4
+
5
+ const __filename = fileURLToPath(import.meta.url);
6
+ const __dirname = path.dirname(__filename);
7
+
8
+ const BIN_DIR = path.join(__dirname, '..', '.bin');
9
+ const SERVER_EXE = path.join(BIN_DIR, 'llama-server.exe');
10
+ const MODEL_FILE = path.join(BIN_DIR, 'ik-local-1b-v1.gguf');
11
+
12
+ console.log(`
13
+ IK_FIREWALL: LOCAL RUNTIME ACTIVE
14
+ -----------------------------------
15
+ Engine: llama.cpp (Real 1B Model)
16
+ Port: 8085
17
+ Context: 4096 tokens
18
+ Status: Igniting Artificial Intelligence...
19
+ -----------------------------------
20
+ `);
21
+
22
+ const llama = spawn(SERVER_EXE, [
23
+ '-m', MODEL_FILE,
24
+ '--port', '8085',
25
+ '--ctx-size', '4096',
26
+ '--n-predict', '512',
27
+ '--threads', '4',
28
+ '--no-mmap' // Safer for some Windows setups
29
+ ], { stdio: 'inherit' });
30
+
31
+ llama.on('error', (err) => {
32
+ console.error(`โŒ Failed to start AI: ${err.message}`);
33
+ console.log('๐Ÿ’ก TIP: Did you run "node scripts/master-setup.js" first?');
34
+ });
35
+
36
+ llama.on('close', (code) => {
37
+ console.log(`\n๐Ÿ›‘ AI Server shutdown (Exit code: ${code})`);
38
+ });