File size: 29,110 Bytes
4b93b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecec503
 
 
4b93b4a
 
 
 
 
 
 
ecec503
 
4b93b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecec503
4b93b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecec503
4b93b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecec503
4b93b4a
ecec503
4b93b4a
 
 
ecec503
 
4b93b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecec503
 
4b93b4a
 
 
ecec503
 
 
 
 
 
 
 
 
 
4b93b4a
ecec503
 
4b93b4a
ecec503
4b93b4a
 
 
ecec503
4b93b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
ecec503
 
 
 
 
 
 
 
4b93b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecec503
4b93b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecec503
4b93b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecec503
4b93b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecec503
4b93b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecec503
4b93b4a
 
 
 
 
 
ecec503
4b93b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecec503
4b93b4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ecec503
4b93b4a
 
 
 
 
ecec503
4b93b4a
 
 
 
ecec503
4b93b4a
 
 
 
ecec503
4b93b4a
 
 
 
 
 
 
 
 
 
 
 
ecec503
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a684408b",
   "metadata": {},
   "source": [
    "# 04 - Agent Intelligence\n",
    "\n",
    "## CyberForge AI - Agentic AI Capabilities\n",
    "\n",
    "This notebook implements intelligent agent decision-making for:\n",
    "- Task prioritization and execution planning\n",
    "- Confidence-based decision scoring\n",
    "- Gemini API integration for reasoning\n",
    "- Autonomous threat response workflows\n",
    "\n",
    "### Alignment:\n",
    "- Integrates with desktop app agentic system\n",
    "- Supports backend task queue management\n",
    "- Provides explainable outputs for user transparency"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8af0eaa6",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json\n",
    "import os\n",
    "import time\n",
    "import numpy as np\n",
    "from pathlib import Path\n",
    "from typing import Dict, List, Any, Optional, Tuple\n",
    "from dataclasses import dataclass, asdict\n",
    "from enum import Enum\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "# Load configuration\n",
    "config_path = Path(\"notebook_config.json\")\n",
    "if not config_path.exists():\n",
    "    config_path = Path(\"/home/user/app/notebooks/notebook_config.json\")\n",
    "with open(config_path) as f:\n",
    "    CONFIG = json.load(f)\n",
    "\n",
    "MODELS_DIR = Path(CONFIG[\"datasets_dir\"]).parent / \"models\"\n",
    "AGENT_DIR = MODELS_DIR.parent / \"agent\"\n",
    "AGENT_DIR.mkdir(exist_ok=True)\n",
    "\n",
    "print(f\"βœ“ Configuration loaded\")\n",
    "print(f\"βœ“ Agent output: {AGENT_DIR}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bbcc7dc9",
   "metadata": {},
   "source": [
    "## 1. Agent Task Definitions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bc6eb821",
   "metadata": {},
   "outputs": [],
   "source": [
    "class TaskPriority(Enum):\n",
    "    CRITICAL = 4\n",
    "    HIGH = 3\n",
    "    MEDIUM = 2\n",
    "    LOW = 1\n",
    "    BACKGROUND = 0\n",
    "\n",
    "@dataclass\n",
    "class AgentTask:\n",
    "    \"\"\"Represents a task the agent can execute\"\"\"\n",
    "    task_id: str\n",
    "    task_type: str\n",
    "    priority: int\n",
    "    target: str\n",
    "    context: Dict\n",
    "    created_at: float\n",
    "    confidence: float = 0.0\n",
    "    status: str = \"pending\"\n",
    "    result: Dict = None\n",
    "    \n",
    "    def to_dict(self) -> Dict:\n",
    "        return asdict(self)\n",
    "\n",
    "@dataclass\n",
    "class AgentDecision:\n",
    "    \"\"\"Represents an agent decision with reasoning\"\"\"\n",
    "    action: str\n",
    "    confidence: float\n",
    "    reasoning: str\n",
    "    evidence: List[str]\n",
    "    risk_level: str\n",
    "    recommended_follow_up: List[str]\n",
    "    \n",
    "    def to_dict(self) -> Dict:\n",
    "        return asdict(self)\n",
    "\n",
    "print(\"βœ“ Task definitions loaded\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c6785168",
   "metadata": {},
   "source": [
    "## 2. Decision Scoring Engine"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0e0109ae",
   "metadata": {},
   "outputs": [],
   "source": [
    "class DecisionScoringEngine:\n",
    "    \"\"\"\n",
    "    Calculates confidence scores for agent decisions.\n",
    "    Combines model predictions with heuristic rules.\n",
    "    \"\"\"\n",
    "    \n",
    "    # Threat severity weights\n",
    "    SEVERITY_WEIGHTS = {\n",
    "        'critical': 1.0,\n",
    "        'high': 0.8,\n",
    "        'medium': 0.5,\n",
    "        'low': 0.3,\n",
    "        'info': 0.1\n",
    "    }\n",
    "    \n",
    "    # Evidence type weights\n",
    "    EVIDENCE_WEIGHTS = {\n",
    "        'model_prediction': 0.4,\n",
    "        'signature_match': 0.3,\n",
    "        'behavioral_pattern': 0.2,\n",
    "        'heuristic_rule': 0.1\n",
    "    }\n",
    "    \n",
    "    def __init__(self, confidence_threshold: float = 0.7):\n",
    "        self.confidence_threshold = confidence_threshold\n",
    "    \n",
    "    def calculate_threat_score(self, indicators: List[Dict]) -> Tuple[float, str]:\n",
    "        \"\"\"Calculate threat score from multiple indicators\"\"\"\n",
    "        if not indicators:\n",
    "            return 0.0, 'low'\n",
    "        \n",
    "        # Weighted average of indicator scores\n",
    "        total_weight = 0\n",
    "        total_score = 0\n",
    "        \n",
    "        for indicator in indicators:\n",
    "            severity = indicator.get('severity', 'low')\n",
    "            confidence = indicator.get('confidence', 0.5)\n",
    "            evidence_type = indicator.get('evidence_type', 'heuristic_rule')\n",
    "            \n",
    "            weight = self.SEVERITY_WEIGHTS.get(severity, 0.3) * \\\n",
    "                     self.EVIDENCE_WEIGHTS.get(evidence_type, 0.1)\n",
    "            \n",
    "            total_weight += weight\n",
    "            total_score += confidence * weight\n",
    "        \n",
    "        if total_weight == 0:\n",
    "            return 0.0, 'low'\n",
    "        \n",
    "        final_score = total_score / total_weight\n",
    "        \n",
    "        # Determine risk level\n",
    "        if final_score >= 0.8:\n",
    "            risk = 'critical'\n",
    "        elif final_score >= 0.6:\n",
    "            risk = 'high'\n",
    "        elif final_score >= 0.4:\n",
    "            risk = 'medium'\n",
    "        elif final_score >= 0.2:\n",
    "            risk = 'low'\n",
    "        else:\n",
    "            risk = 'info'\n",
    "        \n",
    "        return final_score, risk\n",
    "    \n",
    "    def should_act(self, score: float, task_type: str) -> bool:\n",
    "        \"\"\"Determine if agent should act based on score\"\"\"\n",
    "        # Different thresholds for different task types\n",
    "        thresholds = {\n",
    "            'block_threat': 0.85,\n",
    "            'quarantine': 0.75,\n",
    "            'alert': 0.5,\n",
    "            'scan': 0.3,\n",
    "            'monitor': 0.1\n",
    "        }\n",
    "        \n",
    "        threshold = thresholds.get(task_type, self.confidence_threshold)\n",
    "        return score >= threshold\n",
    "    \n",
    "    def prioritize_tasks(self, tasks: List[AgentTask]) -> List[AgentTask]:\n",
    "        \"\"\"Sort tasks by priority and confidence\"\"\"\n",
    "        return sorted(tasks, \n",
    "                      key=lambda t: (t.priority, t.confidence), \n",
    "                      reverse=True)\n",
    "\n",
    "scoring_engine = DecisionScoringEngine()\n",
    "print(\"βœ“ Decision Scoring Engine initialized\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "572652b4",
   "metadata": {},
   "source": [
    "## 3. Gemini API Integration for Reasoning"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e68b585e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Gemini Integration - using google-genai (same as ml-services/app/services/gemini_service.py)\n",
    "try:\n",
    "    from google import genai\n",
    "    GEMINI_AVAILABLE = True\n",
    "except ImportError:\n",
    "    import subprocess\n",
    "    subprocess.run(['pip', 'install', 'google-genai', '-q'])\n",
    "    from google import genai\n",
    "    GEMINI_AVAILABLE = True\n",
    "\n",
    "class GeminiReasoningEngine:\n",
    "    \"\"\"\n",
    "    Uses Gemini API for intelligent threat reasoning.\n",
    "    Provides explainable AI outputs.\n",
    "    \"\"\"\n",
    "    \n",
    "    SYSTEM_PROMPT = \"\"\"You are a cybersecurity AI agent analyzing security threats.\n",
    "Your role is to:\n",
    "1. Analyze security indicators and threat patterns\n",
    "2. Provide clear, actionable recommendations\n",
    "3. Explain your reasoning in a way users can understand\n",
    "4. Prioritize user safety while minimizing false positives\n",
    "\n",
    "Always respond with JSON containing:\n",
    "- action: recommended action (block, alert, monitor, allow)\n",
    "- confidence: 0.0-1.0 confidence score\n",
    "- reasoning: brief explanation\n",
    "- evidence: list of supporting evidence\n",
    "- risk_level: critical/high/medium/low/info\n",
    "- recommended_follow_up: list of next steps\"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        self.api_key = CONFIG.get('gemini_api_key', os.environ.get('GEMINI_API_KEY'))\n",
    "        self.client = None\n",
    "        self.model_name = CONFIG.get('gemini_model', os.environ.get('GEMINI_MODEL', 'gemini-2.5-flash'))\n",
    "        \n",
    "        if self.api_key:\n",
    "            try:\n",
    "                self.client = genai.Client(api_key=self.api_key)\n",
    "                # Test connection\n",
    "                test = self.client.models.generate_content(\n",
    "                    model=self.model_name,\n",
    "                    contents=\"Test. Respond with OK.\"\n",
    "                )\n",
    "                if test.text:\n",
    "                    print(f\"  βœ“ Gemini API connected (model: {self.model_name})\")\n",
    "                else:\n",
    "                    print(\"  ⚠ Gemini API responded but with empty text\")\n",
    "            except Exception as e:\n",
    "                print(f\"  ⚠ Gemini API error: {e}\")\n",
    "                self.client = None\n",
    "        else:\n",
    "            print(\"  ⚠ No Gemini API key found (will use fallback reasoning)\")\n",
    "    \n",
    "    def analyze_threat(self, threat_data: Dict) -> AgentDecision:\n",
    "        \"\"\"Analyze threat and generate decision with reasoning\"\"\"\n",
    "        if self.client:\n",
    "            return self._gemini_analyze(threat_data)\n",
    "        else:\n",
    "            return self._fallback_analyze(threat_data)\n",
    "    \n",
    "    def _gemini_analyze(self, threat_data: Dict) -> AgentDecision:\n",
    "        \"\"\"Use Gemini for threat analysis\"\"\"\n",
    "        prompt = f\"\"\"{self.SYSTEM_PROMPT}\n",
    "\n",
    "Analyze this security threat:\n",
    "{json.dumps(threat_data, indent=2)}\n",
    "\n",
    "Provide your analysis as JSON.\"\"\"\n",
    "        \n",
    "        try:\n",
    "            response = self.client.models.generate_content(\n",
    "                model=self.model_name,\n",
    "                contents=prompt,\n",
    "                config={\n",
    "                    \"temperature\": 0.3,\n",
    "                    \"max_output_tokens\": 1024,\n",
    "                }\n",
    "            )\n",
    "            \n",
    "            # Parse response\n",
    "            text = response.text\n",
    "            # Extract JSON from response\n",
    "            if '```json' in text:\n",
    "                text = text.split('```json')[1].split('```')[0]\n",
    "            elif '```' in text:\n",
    "                text = text.split('```')[1].split('```')[0]\n",
    "            \n",
    "            result = json.loads(text)\n",
    "            \n",
    "            return AgentDecision(\n",
    "                action=result.get('action', 'monitor'),\n",
    "                confidence=float(result.get('confidence', 0.5)),\n",
    "                reasoning=result.get('reasoning', 'Analysis pending'),\n",
    "                evidence=result.get('evidence', []),\n",
    "                risk_level=result.get('risk_level', 'medium'),\n",
    "                recommended_follow_up=result.get('recommended_follow_up', [])\n",
    "            )\n",
    "        except Exception as e:\n",
    "            print(f\"  ⚠ Gemini error: {e}\")\n",
    "            return self._fallback_analyze(threat_data)\n",
    "    \n",
    "    def _fallback_analyze(self, threat_data: Dict) -> AgentDecision:\n",
    "        \"\"\"Rule-based fallback when Gemini unavailable\"\"\"\n",
    "        risk_score = threat_data.get('risk_score', 0.5)\n",
    "        indicators = threat_data.get('indicators', [])\n",
    "        \n",
    "        # Determine action based on risk score\n",
    "        if risk_score >= 0.8:\n",
    "            action = 'block'\n",
    "            risk_level = 'critical'\n",
    "        elif risk_score >= 0.6:\n",
    "            action = 'alert'\n",
    "            risk_level = 'high'\n",
    "        elif risk_score >= 0.4:\n",
    "            action = 'monitor'\n",
    "            risk_level = 'medium'\n",
    "        else:\n",
    "            action = 'allow'\n",
    "            risk_level = 'low'\n",
    "        \n",
    "        return AgentDecision(\n",
    "            action=action,\n",
    "            confidence=risk_score,\n",
    "            reasoning=f\"Risk score: {risk_score:.2f}. Indicators found: {len(indicators)}\",\n",
    "            evidence=[str(i) for i in indicators[:3]],\n",
    "            risk_level=risk_level,\n",
    "            recommended_follow_up=['Continue monitoring', 'Review threat logs']\n",
    "        )\n",
    "\n",
    "reasoning_engine = GeminiReasoningEngine()\n",
    "print(\"βœ“ Gemini Reasoning Engine initialized\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a5f5a0a7",
   "metadata": {},
   "source": [
    "## 4. Task Queue Manager"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1f9ba4fe",
   "metadata": {},
   "outputs": [],
   "source": [
    "import uuid\n",
    "from collections import deque\n",
    "\n",
    "class AgentTaskQueue:\n",
    "    \"\"\"\n",
    "    Manages agent task queue for autonomous operation.\n",
    "    Supports priority-based execution and task lifecycle.\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self, max_concurrent: int = 5):\n",
    "        self.pending = deque()\n",
    "        self.active = []\n",
    "        self.completed = []\n",
    "        self.failed = []\n",
    "        self.max_concurrent = max_concurrent\n",
    "    \n",
    "    def add_task(self, task_type: str, target: str, context: Dict,\n",
    "                 priority: TaskPriority = TaskPriority.MEDIUM) -> AgentTask:\n",
    "        \"\"\"Add a new task to the queue\"\"\"\n",
    "        task = AgentTask(\n",
    "            task_id=str(uuid.uuid4())[:8],\n",
    "            task_type=task_type,\n",
    "            priority=priority.value,\n",
    "            target=target,\n",
    "            context=context,\n",
    "            created_at=time.time()\n",
    "        )\n",
    "        \n",
    "        self.pending.append(task)\n",
    "        self._reorder_queue()\n",
    "        \n",
    "        return task\n",
    "    \n",
    "    def _reorder_queue(self):\n",
    "        \"\"\"Reorder queue by priority\"\"\"\n",
    "        self.pending = deque(sorted(self.pending, \n",
    "                                    key=lambda t: (t.priority, -t.created_at),\n",
    "                                    reverse=True))\n",
    "    \n",
    "    def get_next_task(self) -> Optional[AgentTask]:\n",
    "        \"\"\"Get next task to execute\"\"\"\n",
    "        if len(self.active) >= self.max_concurrent:\n",
    "            return None\n",
    "        \n",
    "        if self.pending:\n",
    "            task = self.pending.popleft()\n",
    "            task.status = 'active'\n",
    "            self.active.append(task)\n",
    "            return task\n",
    "        \n",
    "        return None\n",
    "    \n",
    "    def complete_task(self, task_id: str, result: Dict, success: bool = True):\n",
    "        \"\"\"Mark task as completed\"\"\"\n",
    "        for i, task in enumerate(self.active):\n",
    "            if task.task_id == task_id:\n",
    "                task.status = 'completed' if success else 'failed'\n",
    "                task.result = result\n",
    "                \n",
    "                if success:\n",
    "                    self.completed.append(task)\n",
    "                else:\n",
    "                    self.failed.append(task)\n",
    "                \n",
    "                del self.active[i]\n",
    "                return\n",
    "    \n",
    "    def get_stats(self) -> Dict:\n",
    "        \"\"\"Get queue statistics\"\"\"\n",
    "        return {\n",
    "            'pending': len(self.pending),\n",
    "            'active': len(self.active),\n",
    "            'completed': len(self.completed),\n",
    "            'failed': len(self.failed),\n",
    "            'total': len(self.pending) + len(self.active) + len(self.completed) + len(self.failed)\n",
    "        }\n",
    "\n",
    "task_queue = AgentTaskQueue()\n",
    "print(\"βœ“ Task Queue Manager initialized\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1a56cbf3",
   "metadata": {},
   "source": [
    "## 5. Autonomous Agent Orchestrator"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3a79fff8",
   "metadata": {},
   "outputs": [],
   "source": [
    "class CyberForgeAgent:\n",
    "    \"\"\"\n",
    "    Main autonomous agent for CyberForge.\n",
    "    Orchestrates threat detection, analysis, and response.\n",
    "    \"\"\"\n",
    "    \n",
    "    def __init__(self):\n",
    "        self.scoring_engine = DecisionScoringEngine()\n",
    "        self.reasoning_engine = GeminiReasoningEngine()\n",
    "        self.task_queue = AgentTaskQueue()\n",
    "        self.action_history = []\n",
    "    \n",
    "    def analyze_website(self, url: str, scraped_data: Dict) -> AgentDecision:\n",
    "        \"\"\"Analyze a website for threats\"\"\"\n",
    "        # Extract indicators\n",
    "        indicators = self._extract_indicators(scraped_data)\n",
    "        \n",
    "        # Calculate threat score\n",
    "        score, risk_level = self.scoring_engine.calculate_threat_score(indicators)\n",
    "        \n",
    "        # Get AI reasoning\n",
    "        threat_data = {\n",
    "            'url': url,\n",
    "            'risk_score': score,\n",
    "            'indicators': indicators,\n",
    "            'security_report': scraped_data.get('security_report', {})\n",
    "        }\n",
    "        \n",
    "        decision = self.reasoning_engine.analyze_threat(threat_data)\n",
    "        \n",
    "        # Log decision\n",
    "        self._log_action(url, decision)\n",
    "        \n",
    "        return decision\n",
    "    \n",
    "    def _extract_indicators(self, data: Dict) -> List[Dict]:\n",
    "        \"\"\"Extract threat indicators from scraped data\"\"\"\n",
    "        indicators = []\n",
    "        \n",
    "        # Check security report\n",
    "        security = data.get('security_report', {})\n",
    "        if not security.get('is_https', True):\n",
    "            indicators.append({\n",
    "                'type': 'insecure_protocol',\n",
    "                'severity': 'medium',\n",
    "                'confidence': 0.9,\n",
    "                'evidence_type': 'signature_match'\n",
    "            })\n",
    "        \n",
    "        if security.get('mixed_content', False):\n",
    "            indicators.append({\n",
    "                'type': 'mixed_content',\n",
    "                'severity': 'medium',\n",
    "                'confidence': 0.85,\n",
    "                'evidence_type': 'signature_match'\n",
    "            })\n",
    "        \n",
    "        # Check console errors\n",
    "        console_logs = data.get('console_logs', [])\n",
    "        errors = [log for log in console_logs if log.get('level') == 'error']\n",
    "        if len(errors) > 5:\n",
    "            indicators.append({\n",
    "                'type': 'excessive_errors',\n",
    "                'severity': 'low',\n",
    "                'confidence': 0.6,\n",
    "                'evidence_type': 'behavioral_pattern'\n",
    "            })\n",
    "        \n",
    "        # Check for suspicious network requests\n",
    "        requests = data.get('network_requests', [])\n",
    "        suspicious_domains = ['malware', 'phishing', 'hack', 'tracker']\n",
    "        for req in requests:\n",
    "            url = req.get('url', '').lower()\n",
    "            if any(s in url for s in suspicious_domains):\n",
    "                indicators.append({\n",
    "                    'type': 'suspicious_request',\n",
    "                    'severity': 'high',\n",
    "                    'confidence': 0.75,\n",
    "                    'evidence_type': 'signature_match',\n",
    "                    'details': url[:100]\n",
    "                })\n",
    "        \n",
    "        return indicators\n",
    "    \n",
    "    def _log_action(self, target: str, decision: AgentDecision):\n",
    "        \"\"\"Log agent action for audit trail\"\"\"\n",
    "        self.action_history.append({\n",
    "            'timestamp': time.time(),\n",
    "            'target': target,\n",
    "            'action': decision.action,\n",
    "            'confidence': decision.confidence,\n",
    "            'risk_level': decision.risk_level\n",
    "        })\n",
    "    \n",
    "    def get_action_summary(self) -> Dict:\n",
    "        \"\"\"Get summary of agent actions\"\"\"\n",
    "        if not self.action_history:\n",
    "            return {'total_actions': 0}\n",
    "        \n",
    "        actions = [a['action'] for a in self.action_history]\n",
    "        return {\n",
    "            'total_actions': len(self.action_history),\n",
    "            'action_counts': {a: actions.count(a) for a in set(actions)},\n",
    "            'avg_confidence': np.mean([a['confidence'] for a in self.action_history])\n",
    "        }\n",
    "\n",
    "agent = CyberForgeAgent()\n",
    "print(\"βœ“ CyberForge Agent initialized\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b7ad27d",
   "metadata": {},
   "source": [
    "## 6. Test Agent Decision Making"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a377b332",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Test with sample threat data\n",
    "test_data = {\n",
    "    'url': 'https://suspicious-login.example.com/verify',\n",
    "    'security_report': {\n",
    "        'is_https': True,\n",
    "        'mixed_content': True,\n",
    "        'insecure_cookies': True\n",
    "    },\n",
    "    'console_logs': [\n",
    "        {'level': 'error', 'message': 'CORS policy violation'},\n",
    "        {'level': 'error', 'message': 'Failed to load resource'},\n",
    "    ],\n",
    "    'network_requests': [\n",
    "        {'url': 'https://tracker.malicious.com/collect', 'type': 'xhr'},\n",
    "        {'url': 'https://cdn.example.com/app.js', 'type': 'script'}\n",
    "    ]\n",
    "}\n",
    "\n",
    "print(\"Testing agent analysis...\\n\")\n",
    "decision = agent.analyze_website(test_data['url'], test_data)\n",
    "\n",
    "print(f\"Decision: {decision.action}\")\n",
    "print(f\"Confidence: {decision.confidence:.2%}\")\n",
    "print(f\"Risk Level: {decision.risk_level}\")\n",
    "print(f\"\\nReasoning: {decision.reasoning}\")\n",
    "print(f\"\\nEvidence:\")\n",
    "for e in decision.evidence[:3]:\n",
    "    print(f\"  - {e}\")\n",
    "print(f\"\\nRecommended Follow-up:\")\n",
    "for r in decision.recommended_follow_up[:3]:\n",
    "    print(f\"  - {r}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e68ef74b",
   "metadata": {},
   "source": [
    "## 7. Save Agent Configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cde8619f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Save agent configuration and modules\n",
    "agent_config = {\n",
    "    'version': '1.0.0',\n",
    "    'confidence_threshold': 0.7,\n",
    "    'max_concurrent_tasks': 5,\n",
    "    'severity_weights': DecisionScoringEngine.SEVERITY_WEIGHTS,\n",
    "    'evidence_weights': DecisionScoringEngine.EVIDENCE_WEIGHTS,\n",
    "    'task_priorities': {p.name: p.value for p in TaskPriority},\n",
    "    'gemini_model': CONFIG.get('gemini_model', 'gemini-2.5-flash')\n",
    "}\n",
    "\n",
    "config_path = AGENT_DIR / \"agent_config.json\"\n",
    "with open(config_path, 'w') as f:\n",
    "    json.dump(agent_config, f, indent=2)\n",
    "\n",
    "print(f\"βœ“ Agent config saved to: {config_path}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43b960cd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Save agent module for backend import\n",
    "agent_module = '''\n",
    "\"\"\"CyberForge Agent Intelligence Module\"\"\"\n",
    "\n",
    "import json\n",
    "import time\n",
    "import numpy as np\n",
    "from pathlib import Path\n",
    "from dataclasses import dataclass, asdict\n",
    "from typing import Dict, List, Any, Optional\n",
    "\n",
    "@dataclass\n",
    "class AgentDecision:\n",
    "    action: str\n",
    "    confidence: float\n",
    "    reasoning: str\n",
    "    evidence: List[str]\n",
    "    risk_level: str\n",
    "    recommended_follow_up: List[str]\n",
    "    \n",
    "    def to_dict(self):\n",
    "        return asdict(self)\n",
    "\n",
    "class DecisionEngine:\n",
    "    SEVERITY_WEIGHTS = {\"critical\": 1.0, \"high\": 0.8, \"medium\": 0.5, \"low\": 0.3, \"info\": 0.1}\n",
    "    \n",
    "    def calculate_threat_score(self, indicators: List[Dict]) -> tuple:\n",
    "        if not indicators:\n",
    "            return 0.0, \"low\"\n",
    "        scores = [i.get(\"confidence\", 0.5) * self.SEVERITY_WEIGHTS.get(i.get(\"severity\", \"low\"), 0.3) \n",
    "                  for i in indicators]\n",
    "        score = sum(scores) / len(scores) if scores else 0\n",
    "        risk = \"critical\" if score >= 0.8 else \"high\" if score >= 0.6 else \"medium\" if score >= 0.4 else \"low\"\n",
    "        return score, risk\n",
    "\n",
    "class CyberForgeAgent:\n",
    "    def __init__(self):\n",
    "        self.engine = DecisionEngine()\n",
    "    \n",
    "    def analyze(self, url: str, data: Dict) -> Dict:\n",
    "        indicators = self._extract_indicators(data)\n",
    "        score, risk = self.engine.calculate_threat_score(indicators)\n",
    "        action = \"block\" if score >= 0.8 else \"alert\" if score >= 0.6 else \"monitor\" if score >= 0.4 else \"allow\"\n",
    "        \n",
    "        return AgentDecision(\n",
    "            action=action,\n",
    "            confidence=score,\n",
    "            reasoning=f\"Threat score: {score:.2f}. {len(indicators)} indicators found.\",\n",
    "            evidence=[str(i) for i in indicators[:3]],\n",
    "            risk_level=risk,\n",
    "            recommended_follow_up=[\"Continue monitoring\"]\n",
    "        ).to_dict()\n",
    "    \n",
    "    def _extract_indicators(self, data: Dict) -> List[Dict]:\n",
    "        indicators = []\n",
    "        sec = data.get(\"security_report\", {})\n",
    "        if not sec.get(\"is_https\", True):\n",
    "            indicators.append({\"type\": \"insecure\", \"severity\": \"medium\", \"confidence\": 0.9})\n",
    "        if sec.get(\"mixed_content\"):\n",
    "            indicators.append({\"type\": \"mixed_content\", \"severity\": \"medium\", \"confidence\": 0.85})\n",
    "        return indicators\n",
    "'''\n",
    "\n",
    "module_path = AGENT_DIR / \"cyberforge_agent.py\"\n",
    "with open(module_path, 'w') as f:\n",
    "    f.write(agent_module)\n",
    "\n",
    "print(f\"βœ“ Agent module saved to: {module_path}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31978536",
   "metadata": {},
   "source": [
    "## 8. Summary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d6e9505c",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(\"\\n\" + \"=\" * 60)\n",
    "print(\"AGENT INTELLIGENCE COMPLETE\")\n",
    "print(\"=\" * 60)\n",
    "\n",
    "print(f\"\"\"\n",
    "πŸ€– Agent Capabilities:\n",
    "   - Decision Scoring: Weighted threat assessment\n",
    "   - Gemini Integration: AI-powered reasoning\n",
    "   - Task Queue: Priority-based execution\n",
    "   - Action History: Full audit trail\n",
    "\n",
    "πŸ“Š Test Results:\n",
    "   - Action: {decision.action}\n",
    "   - Confidence: {decision.confidence:.2%}\n",
    "   - Risk Level: {decision.risk_level}\n",
    "\n",
    "πŸ“ Output Files:\n",
    "   - Config: {AGENT_DIR}/agent_config.json\n",
    "   - Module: {AGENT_DIR}/cyberforge_agent.py\n",
    "\n",
    "Next step:\n",
    "  β†’ 05_model_validation.ipynb\n",
    "\"\"\")\n",
    "print(\"=\" * 60)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}