Spaces:
Sleeping
Sleeping
Final check:Passed
Browse filesFiles changed (9)
1 unmodified line2345671 unmodified line__pycache__/*.py[codz]*$py.class# C extensions*.so1 unmodified line23456781 unmodified line__pycache__/*.py[codz]*$py.classwandb/# C extensions*.so
1 unmodified line234567820 unmodified lines293031323334353637383919 unmodified lines5960616263646566676869707172737475767711 unmodified lines89909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251 unmodified line"""PatchHawk inference script β runs the LLM agent loop against theOpenEnv-compliant PatchHawkEnv.Environment variables:API_BASE_URL β OpenAI-compatible API endpoint (required unless DRY_RUN=1)MODEL_NAME β Model identifier (default: meta-llama/Llama-3.2-3B-Instruct)20 unmodified linesfrom patchhawk import tasks as graders# ββ Configuration ββββββββββββββββββββββββββββββββββββββββββββββββββββAPI_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/hf-inference/v1")MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-Coder-32B-Instruct")HF_TOKEN = os.getenv("HF_TOKEN", "")DRY_RUN = os.getenv("DRY_RUN", "0") == "1"SINGLE_TASK = os.getenv("TASK", "")19 unmodified lines# ββ Prompt builder βββββββββββββββββββββββββββββββββββββββββββββββββββSYSTEM_PROMPT = """\You are PatchHawk, a security agent that detects supply-chain vulnerabilitiesin Python code. You will be given a code snippet and static analysis flags.Respond with a JSON object containing:{"action_type": <int>, // 0=ANALYZE, 1=EXECUTE_SANDBOX, 2=BLOCK_PR, 3=SUBMIT_PATCH, 4=REQUEST_REVIEW"patch_content": <str|null> // required if action_type == 3}Be decisive. If the code is clearly malicious, BLOCK_PR (2). If you cangenerate a patch that removes the vulnerability, use SUBMIT_PATCH (3)."""def _build_user_prompt(obs: PatchHawkObservation, step: int) -> str:parts = [11 unmodified lines# ββ LLM caller βββββββββββββββββββββββββββββββββββββββββββββββββββββββdef _call_llm(messages: list[dict]) -> str:"""Call the OpenAI-compatible LLM and return the text content."""from openai import OpenAIclient = OpenAI(base_url=API_BASE_URL,api_key=HF_TOKEN or "no-key",)response = client.chat.completions.create(model=MODEL_NAME,messages=messages,temperature=0.2,max_tokens=512,)return response.choices[0].message.content or ""def _parse_action(text: str) -> PatchHawkAction:"""Parse LLM response text into a PatchHawkAction."""# Try to extract JSON from the responsetext = text.strip()# Handle markdown code blocksif "```json" in text:text = text.split("```json")[1].split("```")[0].strip()elif "```" in text:text = text.split("```")[1].split("```")[0].strip()data = json.loads(text)return PatchHawkAction(action_type=int(data["action_type"]),patch_content=data.get("patch_content"),)1 unmodified line234567820 unmodified lines293031323334353637383940414243444519 unmodified lines656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711 unmodified lines1291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462471 unmodified line"""PatchHawk inference script β runs the LLM agent loop against theOpenEnv-compliant PatchHawkEnv.aEnvironment variables:API_BASE_URL β OpenAI-compatible API endpoint (required unless DRY_RUN=1)MODEL_NAME β Model identifier (default: meta-llama/Llama-3.2-3B-Instruct)20 unmodified linesfrom patchhawk import tasks as graders# ββ Configuration ββββββββββββββββββββββββββββββββββββββββββββββββββββtry:from dotenv import load_dotenvload_dotenv()except ImportError:passAPI_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/hf-inference/v1")# Prefer explicit MODEL_NAME, fallback to GRPO_POLICY_MODEL from .env, then default to 32B model.MODEL_NAME = os.getenv("MODEL_NAME", os.getenv("GRPO_POLICY_MODEL", "Qwen/Qwen2.5-Coder-32B-Instruct"))HF_TOKEN = os.getenv("HF_TOKEN", "")DRY_RUN = os.getenv("DRY_RUN", "0") == "1"SINGLE_TASK = os.getenv("TASK", "")19 unmodified lines# ββ Prompt builder βββββββββββββββββββββββββββββββββββββββββββββββββββSYSTEM_PROMPT = """\You are PatchHawk, a security agent that detects supply-chain vulnerabilities in Python code.Given a code snippet and static analysis flags, you must respond **EXACTLY** with a single JSON object. No extra text, no markdown formatting.## Output JSON Schema{"reasoning": "<str>", // Mandatory: Explain what the vulnerability is, why it's dangerous, and your recommended fix (if any)."risk_score": <float>, // 0.0 (no risk) to 1.0 (critical). Be precise to two decimals."action_type": <int>, // One of: 0=ANALYZE, 1=EXECUTE_SANDBOX, 2=BLOCK_PR, 3=SUBMIT_PATCH, 4=REQUEST_REVIEW"patch_content": "<str|null>" // Full patched code if action_type=3, otherwise null. Must be valid Python.}## Action Type Guidelines- **0 ANALYZE** β No immediate threat, but needs deeper review.- **1 EXECUTE_SANDBOX** β Suspicious but not obviously malicious; run in isolated environment.- **2 BLOCK_PR** β Severely malicious, unfixable (e.g., hidden backdoor, remote shell). Reject PR.- **3 SUBMIT_PATCH** β Vulnerability can be fixed. Provide corrected code in `patch_content`.- **4 REQUEST_REVIEW** β Complex or ambiguous; require human expert.## Rules- `reasoning` must be thorough: describe the flaw, its impact (CWE if known), and stepβbyβstep how to patch.- Escape all double quotes inside strings with backslash (`\"`).- If the code is benign, set `risk_score` β€ 0.2, `action_type` = 0, and `patch_content` = null.- Never include comments or explanations outside the JSON object.**Example valid response:**{"reasoning": "Hardcoded password 'admin123' in __init__ allows credential bypass. Replace with env var.", "risk_score": 0.85, "action_type": 3, "patch_content": "import os\\nclass Malicious:\\n def __init__(self):\\n self.cache = []\\n self.password = os.getenv('DB_PASS')\\n ..."}"""# SYSTEM_PROMPT = """\# You are PatchHawk, a security agent that detects supply-chain vulnerabilities# in Python code. You will be given a code snippet and static analysis flags.# Respond EXACTLY with a JSON object containing the following keys:# {# "reasoning": "<str>", // Step-by-step explanation of what the vulnerability is, why you are blocking/patching it, and how it can be fixed.# "risk_score": <float>, // Your predicted risk score from 0.0 to 1.0 based on your analysis# "action_type": <int>, // 0=ANALYZE, 1=EXECUTE_SANDBOX, 2=BLOCK_PR, 3=SUBMIT_PATCH, 4=REQUEST_REVIEW# "patch_content": "<str|null>" // The full patched python code fixing the vulnerability# }# Be decisive. First, explain your findings thoroughly in the "reasoning" field.# If the code is malicious but you can fix the vulnerability, use SUBMIT_PATCH (3) and provide the safe, corrected code in "patch_content".# If the code is severely malicious and completely unfixable, use BLOCK_PR (2).# IMPORTANT: Ensure your output is perfectly VALID JSON. Escape all double quotes inside strings properly.# """def _build_user_prompt(obs: PatchHawkObservation, step: int) -> str:parts = [11 unmodified lines# ββ LLM caller βββββββββββββββββββββββββββββββββββββββββββββββββββββββ_local_pipeline = Nonedef _call_llm_local(messages: list[dict]) -> str:"""Call a local HuggingFace model using transformers pipeline if remote API fails."""global _local_pipelineif _local_pipeline is None:import torchfrom transformers import pipeline# User is already using this model in .env GRPO_POLICY_MODELlocal_model = os.getenv("GRPO_POLICY_MODEL", "unsloth/Qwen2.5-Coder-3B-Instruct")print(f"\n[Fallback] Loading local model: {local_model} into memory. This may take a moment...", flush=True)_local_pipeline = pipeline("text-generation",model=local_model,model_kwargs={"torch_dtype": torch.bfloat16}, # Half-precision to save VRAM natively fit on 12GBdevice_map="auto")print("[Fallback] Local model loaded successfully.\n", flush=True)# Format messages array to a standard conversational string formatprompt = _local_pipeline.tokenizer.apply_chat_template(messages,tokenize=False,add_generation_prompt=True)# Run Generationoutputs = _local_pipeline(prompt,max_new_tokens=2048,do_sample=True,temperature=0.2,)generated = outputs[0]["generated_text"]print(f"\ngenerated:{generated}\n")# Strip prompt from returned generated outputif generated.startswith(prompt):generated = generated[len(prompt):]return generated.strip()def _call_llm(messages: list[dict]) -> str:"""Call the OpenAI-compatible LLM and return the text content."""from openai import OpenAItry:client = OpenAI(base_url=API_BASE_URL,api_key=HF_TOKEN or "no-key",)response = client.chat.completions.create(model=MODEL_NAME,messages=messages,temperature=0.2,max_tokens=512,)return response.choices[0].message.content or ""except Exception as e:print(f"[LLM ERROR] Remote API failed: {e}. Initiating local Fallback...", flush=True)return _call_llm_local(messages)import redef _parse_action(text: str) -> PatchHawkAction:"""Parse LLM response text into a PatchHawkAction."""text = text.strip()if "```json" in text:text = text.split("```json")[1].split("```")[0].strip()elif "```" in text and not text.startswith("{"):text = text.split("```")[1].split("```")[0].strip()def clean_patch(p: str) -> str:if not p: return pif "```python" in p:return p.split("```python")[1].split("```")[0].strip()if "```" in p:return p.split("```")[1].split("```")[0].strip()return ptry:data = json.loads(text)except json.JSONDecodeError:action_match = re.search(r'"action_type"\s*:\s*(\d+)', text)action_type = int(action_match.group(1)) if action_match else 2risk_match = re.search(r'"risk_score"\s*:\s*([\d\.]+)', text)risk_score = float(risk_match.group(1)) if risk_match else Nonepatch_match = re.search(r'"patch_content"\s*:\s*"(.*)', text, re.DOTALL)patch_content = Noneif patch_match:raw_patch = patch_match.group(1).rsplit('"', 1)[0]raw_patch = raw_patch.replace("\\n", "\n").replace('\\"', '"').replace("\\\\", "\\")patch_content = clean_patch(raw_patch)return PatchHawkAction(action_type=action_type,reasoning="JSON Error/Truncated Output. Recovered partial data.",predicted_risk=risk_score,patch_content=patch_content)return PatchHawkAction(action_type=int(data.get("action_type", 2)),patch_content=clean_patch(data.get("patch_content")),reasoning=data.get("reasoning"),predicted_risk=data.get("risk_score"),)
307 unmodified lines308309310311312313314315307 unmodified linesif self.step_counter >= self.max_steps and not done:done = Trueif label == "malicious":reward = -5.0reason = "max steps reached on malicious scenario"self.cumulative_reward += reward307 unmodified lines308309310311312313314315316317318319320321322323307 unmodified linesif self.step_counter >= self.max_steps and not done:done = Trueif label == "malicious":reward -= 5.0reason += " | max steps reached on malicious scenario"# ββ Dynamic Risk Bonus βββββββββββββββββββββββββββββββββββpredict_risk = getattr(action, "predicted_risk", None)if predict_risk is not None:actual_risk = 1.0 if label == "malicious" else 0.0accuracy_bonus = (1.0 - abs(actual_risk - float(predict_risk))) * 2.0reward += accuracy_bonusreason += f" | AI risk accuracy bonus: +{accuracy_bonus:.2f}"self.cumulative_reward += reward
30 unmodified lines3132333435363753 unmodified lines919293949596979 unmodified lines10710810911011111211330 unmodified linestemp_dir = tempfile.mkdtemp(prefix="patchhawk_sandbox_")script_path = os.path.join(temp_dir, "script.py")with open(script_path, "w") as f:f.write(code)result: Dict[str, Any] = {53 unmodified linestemp_dir = tempfile.mkdtemp(prefix="patchhawk_syntax_")script_path = os.path.join(temp_dir, "script.py")with open(script_path, "w") as f:f.write(code)try:9 unmodified lines"--cpus","0.5","-v",f"{temp_dir}:/app:ro","patchhawk-sandbox:latest","python","-m",30 unmodified lines3132333435363753 unmodified lines919293949596979 unmodified lines10710810911011111211330 unmodified linestemp_dir = tempfile.mkdtemp(prefix="patchhawk_sandbox_")script_path = os.path.join(temp_dir, "script.py")with open(script_path, "w", encoding="utf-8") as f:f.write(code)result: Dict[str, Any] = {53 unmodified linestemp_dir = tempfile.mkdtemp(prefix="patchhawk_syntax_")script_path = os.path.join(temp_dir, "script.py")with open(script_path, "w", encoding="utf-8") as f:f.write(code)try:9 unmodified lines"--cpus","0.5","-v",f"{temp_dir}:/app:rw","patchhawk-sandbox:latest","python","-m",
180 unmodified lines18118218318418518618731 unmodified lines2192202212222232242252262 unmodified lines22923023123223323418 unmodified lines253254255256257258259260261262180 unmodified linesfinal_action_type = PatchHawkEnv.ACTION_BLOCK_PRelse:final_action_type = PatchHawkEnv.ACTION_REQUEST_REVIEWaction = PatchHawkAction(action_type=final_action_type)# Visual Hacker Terminal Effectif final_action_type == PatchHawkEnv.ACTION_SUBMIT_PATCH:31 unmodified lineswith st.expander("π€ Agent Thought Process (LLM Trace)"):st.markdown(f"```json\n{llm_thought_process}\n```")m1, m2, m3 = st.columns(3)m1.metric("Risk Score", f"{risk:.2f}")m2.metric("Decision", PatchHawkEnv.ACTION_NAMES[final_action_type])m3.metric("Reward", f"{total_reward:+.2f}")2 unmodified lines)with tab1:if final_action_type == PatchHawkEnv.ACTION_BLOCK_PR:st.markdown("<div class='info-box status-malicious'>β BLOCKED β "18 unmodified lineswith tab2:telem = obs.metadata.get("telemetry")if telem:st.json(telem)else:st.info("No sandbox execution for this path.")with tab3:if final_action_type == PatchHawkEnv.ACTION_SUBMIT_PATCH and scenario.get(180 unmodified lines18118218318418518618718818919031 unmodified lines2222232242252262272282292302312322332342 unmodified lines23723823924024124224324424524618 unmodified lines265266267268269270271272273274275276277180 unmodified linesfinal_action_type = PatchHawkEnv.ACTION_BLOCK_PRelse:final_action_type = PatchHawkEnv.ACTION_REQUEST_REVIEWaction = PatchHawkAction(action_type=final_action_type,reasoning="Static rule-based fallback decision due to high risk score.")# Visual Hacker Terminal Effectif final_action_type == PatchHawkEnv.ACTION_SUBMIT_PATCH:31 unmodified lineswith st.expander("π€ Agent Thought Process (LLM Trace)"):st.markdown(f"```json\n{llm_thought_process}\n```")# Opt for LLM's predicted risk score if availabledisplay_risk = getattr(action, "predicted_risk", None)if display_risk is None:display_risk = riskm1, m2, m3 = st.columns(3)m1.metric("Risk Score", f"{float(display_risk):.2f}")m2.metric("Decision", PatchHawkEnv.ACTION_NAMES[final_action_type])m3.metric("Reward", f"{total_reward:+.2f}")2 unmodified lines)with tab1:if hasattr(action, "reasoning") and action.reasoning:st.markdown("### π§ Agent's Reasoning")st.info(action.reasoning)if final_action_type == PatchHawkEnv.ACTION_BLOCK_PR:st.markdown("<div class='info-box status-malicious'>β BLOCKED β "18 unmodified lineswith tab2:telem = obs.metadata.get("telemetry")details = obs.metadata.get("details")if telem:st.json(telem)elif dict(details) if details else None:st.json(details)else:st.info("No sandbox telemetry generated for this action.")with tab3:if final_action_type == PatchHawkEnv.ACTION_SUBMIT_PATCH and scenario.get(
127 unmodified lines12812913013113213313413513613713813947 unmodified lines18718818919019119219311 unmodified lines2052062072082092102112129 unmodified lines222223224225226227228257 unmodified lines48648748848949049143 unmodified lines535536537538539540541127 unmodified lines# ============================================================def generate_track_b_scenarios(benign_files: list) -> list:"""Generate β₯ 50 scenarios: 25 TP, 15 FP, 15 functional."""scenarios = []# ββ True Positives (25) ββββββββββββββββββββββββββββββββββfor i in range(25):bf = random.choice(benign_files)attack_name, attack_data = random.choice(list(ATTACK_TEMPLATES.items()))malicious_code = attack_data["inject"] + bf["code"]47 unmodified lines"result = subprocess.run(['echo', 'build ok'], capture_output=True)\n\n",),]for i in range(15):bf = random.choice(benign_files)fp_name, fp_code = random.choice(fp_templates)suspicious_code = fp_code + bf["code"]11 unmodified lines})# ββ Functional / Clean (15) ββββββββββββββββββββββββββββββfor i in range(15):bf = random.choice(benign_files)test_code = auto_generate_unit_test(bf["filename"], bf["code"])scenarios.append(9 unmodified lines})return scenarios # 55 total from Track B alone# ============================================================257 unmodified linestype=str,default="patchhawk/data/scenarios.json",)parser.add_argument("--use-sdk",action="store_true",43 unmodified linesreturn# Track B (always)scenarios = generate_track_b_scenarios(benign_files)# Track A (optional)if args.use_sdk:127 unmodified lines12812913013113213313413513613713813914014114214347 unmodified lines19119219319419519619711 unmodified lines2092102112122132142152169 unmodified lines226227228229230231232257 unmodified lines49049149249349449549649749849950050143 unmodified lines545546547548549550551127 unmodified lines# ============================================================def generate_track_b_scenarios(benign_files: list, num_samples: int = 55) -> list:"""Generate proportional scenarios dynamically based on num_samples."""scenarios = []tp_count = int(num_samples * 0.45)fp_count = int(num_samples * 0.27)fn_count = num_samples - tp_count - fp_count# ββ True Positives (45%) ββββββββββββββββββββββββββββββββββfor i in range(tp_count):bf = random.choice(benign_files)attack_name, attack_data = random.choice(list(ATTACK_TEMPLATES.items()))malicious_code = attack_data["inject"] + bf["code"]47 unmodified lines"result = subprocess.run(['echo', 'build ok'], capture_output=True)\n\n",),]for i in range(fp_count):bf = random.choice(benign_files)fp_name, fp_code = random.choice(fp_templates)suspicious_code = fp_code + bf["code"]11 unmodified lines})# ββ Functional / Clean (28%) ββββββββββββββββββββββββββββββfor i in range(fn_count):bf = random.choice(benign_files)test_code = auto_generate_unit_test(bf["filename"], bf["code"])scenarios.append(9 unmodified lines})return scenarios# ============================================================257 unmodified linestype=str,default="patchhawk/data/scenarios.json",)parser.add_argument("--num-samples",type=int,default=55,help="Number of scenarios to generate with Track B (mutation engine).",)parser.add_argument("--use-sdk",action="store_true",43 unmodified linesreturn# Track B (always)scenarios = generate_track_b_scenarios(benign_files, args.num_samples)# Track A (optional)if args.use_sdk:
52 unmodified lines53545556575852 unmodified linespatch_content: Optional[str] = Field(None, description="The unified context patch if action is SUBMIT_PATCH")# ββ State ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ52 unmodified lines53545556575859606162636452 unmodified linespatch_content: Optional[str] = Field(None, description="The unified context patch if action is SUBMIT_PATCH")reasoning: Optional[str] = Field(None, description="Explanation of the vulnerability and chosen action")predicted_risk: Optional[float] = Field(None, description="LLM predicted risk score (0.0 to 1.0)")# ββ State ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
32 unmodified lines33343536373851 unmodified lines9091929394959650 unmodified lines14714814915015115241 unmodified lines19419519619719819920020120220320420532 unmodified linesf"<code_snippet>\n{scenario['code_snippet']}\n</code_snippet>\n""Respond in STRICT XML:\n""<thought>...</thought>\n""<action>0-4</action>\n""<patch>...</patch> (ONLY if action=3)\n")51 unmodified lineselse:print("No GPU found β training will be slow.")MODEL_NAME = "Qwen/Qwen2.5-Coder-3B-Instruct"# 4βbit quantisation configbnb_config = BitsAndBytesConfig(50 unmodified linesscore += 0.5else:score -= 1.0if re.search(r"<action>[0-4]</action>", text):score += 0.5else:41 unmodified linespatch_match = re.search(r"<patch>(.*?)</patch>", text, re.DOTALL)if patch_match:patch = patch_match.group(1).strip()try:# Reset environment to the exact scenarioenv.reset(scenario_idx=env.scenarios.index(scenario))obs = env.step(PatchHawkAction(action_type=action_type, patch_content=patch))rewards.append(float(obs.reward or 0.0))except Exception as exc:print(f"env_reward crash: {exc}")rewards.append(-3.0)32 unmodified lines3334353637383951 unmodified lines91929394959697989910050 unmodified lines15115215315415515615715815916041 unmodified lines20220320420520620720820921021121221321421521621721821922022122222332 unmodified linesf"<code_snippet>\n{scenario['code_snippet']}\n</code_snippet>\n""Respond in STRICT XML:\n""<thought>...</thought>\n""<risk_score>0.0 to 1.0</risk_score>\n""<action>0-4</action>\n""<patch>...</patch> (ONLY if action=3)\n")51 unmodified lineselse:print("No GPU found β training will be slow.")from dotenv import load_dotenvload_dotenv()MODEL_NAME = os.getenv("GRPO_POLICY_MODEL", "Qwen/Qwen2.5-Coder-3B-Instruct")# 4βbit quantisation configbnb_config = BitsAndBytesConfig(50 unmodified linesscore += 0.5else:score -= 1.0if re.search(r"<risk_score>[\d\.]+</risk_score>", text):score += 0.5else:score -= 1.0if re.search(r"<action>[0-4]</action>", text):score += 0.5else:41 unmodified linespatch_match = re.search(r"<patch>(.*?)</patch>", text, re.DOTALL)if patch_match:patch = patch_match.group(1).strip()risk_match = re.search(r"<risk_score>([\d\.]+)</risk_score>", text)predicted_risk = float(risk_match.group(1)) if risk_match else Nonetry:# Reset environment to the exact scenarioenv.reset(scenario=scenario)obs = env.step(PatchHawkAction(action_type=action_type,patch_content=patch,predicted_risk=predicted_risk))reward_val = float(obs.reward or 0.0)rewards.append(reward_val)val_msg = obs.metadata.get('validation') or ("Telemetry Extracted" if obs.metadata.get('telemetry') else "None")print(f"[Env Reward] Action: {action_type} | Reward: {reward_val:+.2f} | Docker: {val_msg}")except Exception as exc:print(f"env_reward crash: {exc}")rewards.append(-3.0)
.gitignore+1
inference.py+148-26
patchhawk/agent/environment.py+10-2
patchhawk/agent/sandbox.py+3-3
patchhawk/app/dashboard.py+18-3
patchhawk/data/generate_scenarios.py+19-9
patchhawk/data/scenarios.json
patchhawk/env_models.py+6
patchhawk/training/train_grpo.py+22-4