text
stringlengths
185
73.3k
repo
stringlengths
7
100
path
stringlengths
4
146
language
stringclasses
7 values
hash
stringlengths
16
16
score
float64
7
8.5
stars
int64
0
237k
"""Model drift sync, escalation, and per-model context adaptation. Extracted from the monolithic ``core/agent/loop.py`` (Tier 3 #7). Each function takes the ``AgenticLoop`` as the first parameter (``loop``). """ from __future__ import annotations import asyncio import logging from typing import TYPE_CHECKING, Any i...
mangowhoiscloud/geode
core/agent/loop/_model_switching.py
.py
008a1226c591c1a2
7.59
14
"""Reflection node — LLM-driven belief update after the tool batch. PR-3 C-2 of the cognitive-loop-uplift sprint (``docs/plans/2026-05-21-cognitive-loop-uplift.md``). PR-B (2026-05-21) — migrated the reflection call from free-form JSON-in-text to Anthropic ``tool_use`` structured output. Pre-PR-B the system prompt as...
mangowhoiscloud/geode
core/agent/loop/_reflection.py
.py
b352cb83074e55d2
7.59
14
"""Response handling: text/content extraction, usage tracking, tool refresh. Extracted from the monolithic ``core/agent/loop.py`` (Tier 3 #7). Each function takes the ``AgenticLoop`` as the first parameter (``loop``) and reads/writes its state. Convergence/error-tracking helpers live here too because they share the re...
mangowhoiscloud/geode
core/agent/loop/_response.py
.py
2264fb7fcd02f73c
7.59
14
"""Enforcement-policy latency benchmark (issue #93). Measures the real, reproducible added wall-clock latency per ingested step when an enforcement policy is configured, across three halt-endpoint behaviors: * responding : localhost endpoint answering {"action": "continue"} at once * refused : dead endpoint (c...
Cyrax321/SNAGLINE
benchmarks/enforcement_benchmark.py
.py
57ec883ab40472f4
7.42
6
"""Overhead benchmark -- the credibility artifact for "cheap enough to run on every step" (project.md §10 / §13 step 4). Measures the real, reproducible cost of ``Monitor.ingest()`` in microseconds per call, amortized over a large number of synthetic steps. Run directly:: python benchmarks/overhead_benchmark.py ...
Cyrax321/SNAGLINE
benchmarks/overhead_benchmark.py
.py
c6e1e7840013d9fc
7.42
6
"""End-to-end example: baseline a healthy run, then monitor live traffic. This walks the full next-phase pipeline without any optional dependency: 1. Write a small "known-good" trajectory (one JSON StepEvent per line). 2. Fit a healthy ``BaselineProfile`` from it via ``snagline baseline`` (or the ``fit_baseline_fr...
Cyrax321/SNAGLINE
examples/baseline_to_monitor.py
.py
d515584b567e4518
7.42
6
"""Runnable demo: SNAGLINE watching a plain Python agent loop (the ``raw`` adapter). Run: PYTHONPATH=src python3 examples/raw_loop_example.py # faulty run (shows detections) PYTHONPATH=src python3 examples/raw_loop_example.py --healthy # clean run (no detections) Detections print as JSON lines to st...
Cyrax321/SNAGLINE
examples/raw_loop_example.py
.py
a6df29723d5cf193
7.42
6
"""Real-time SNAGLINE: real LLM -> real detectors -> WebhookSink -> HTTP sidecar. End-to-end proof of the NEW webhook sink + HTTP sidecar with REAL detection (nothing faked): 1. A genuine LangChain 1.x ``create_agent`` agent runs with a REAL chat model and REAL tools. 2. The SnaglineCallbackHandler feeds rea...
Cyrax321/SNAGLINE
examples/real_time_webhook_demo.py
.py
bd75beff72267f31
7.42
6
"""Runnable demo: offline analysis of a trajectory file via ``snagline replay``. Builds a small synthetic trajectory (a loop + an error cascade), writes it to a temp file, and replays it through the detectors. Mirrors: snagline replay trajectory.jsonl --summary Run: PYTHONPATH=src python3 examples/replay_off...
Cyrax321/SNAGLINE
examples/replay_offline_trajectory.py
.py
cfaaad29ece86aa2
7.42
6
"""Autogen adapter (optional extra: ``pip install snagline[autogen]``). Turns Autogen agent events into ``StepEvent``s and feeds them to a ``Monitor``. Autogen is async-first; the most stable integration point is the event stream emitted by ``agent.run_stream(task)``. This adapter provides a handler you can feed event...
Cyrax321/SNAGLINE
src/snagline/adapters/autogen.py
.py
dd5798c76750f56c
7.42
6
"""CrewAI adapter (optional extra: ``pip install snagline[crewai]``). Turns CrewAI agent steps into ``StepEvent``s and feeds them to a ``Monitor``. CrewAI agents accept a ``step_callback`` that receives each agent step as it is produced. :func:`snagline_step_callback` returns a callback compatible with that hook, so w...
Cyrax321/SNAGLINE
src/snagline/adapters/crewai.py
.py
db3a733134edcc5f
7.42
6
"""LangGraph adapter (optional extra: ``pip install snagline[langgraph]``). Wraps ``graph.stream(...)`` -- LangGraph's public streaming API -- and turns each node update into a ``StepEvent`` for the Monitor (project.md §6.3). Works with any framework that yields ``{node_name: state_update}`` items (LangGraph's default...
Cyrax321/SNAGLINE
src/snagline/adapters/langgraph_adapter.py
.py
bff996901a6e64c1
7.42
6
"""Raw adapter -- for anyone with a plain loop and no framework (project.md §6.1). This is likely the single most-used adapter: most real agent code today is a custom loop, not a framework. Its only job is to turn a call in the host loop into a ``StepEvent`` and call ``monitor.ingest``. It contains no detection logic....
Cyrax321/SNAGLINE
src/snagline/adapters/raw.py
.py
f06624b61a475d0c
7.42
6
"""Auto-instrumentation for LangChain (ATTACH_ANY_SYSTEM P0). Wraps the common ``invoke`` / ``generate`` entrypoints on a LangChain model or chain so each call emits a ``StepEvent``. Import-safe: a no-op when LangChain is absent, and handles synchronous and asynchronous methods. """ from __future__ import annotations...
Cyrax321/SNAGLINE
src/snagline/auto/langchain.py
.py
77a90a287b829740
7.42
6
"""Healthy-run baseline fitting (project.md §5 / the `snagline baseline` CLI). Fits a per-tool profile (latency mean/std/min/max and error rate) from a JSONL trajectory of a *known-healthy* agent run. The profile is persisted as JSON so later build phases (the `goal_drift` and `ml_ensemble` detectors) have a reference...
Cyrax321/SNAGLINE
src/snagline/baseline.py
.py
ab0db3aeedbd9880
7.42
6
"""Opt-in threshold auto-calibration from a fitted BaselineProfile (issue #101). With ``Config(calibration="auto")`` and a healthy-run profile loaded (the output of ``snagline baseline``), ``Monitor.default()`` replaces two hand-tuned inputs with values derived from the deployment's own observed behavior: * Error-cas...
Cyrax321/SNAGLINE
src/snagline/calibration.py
.py
7665979309a3aab6
7.42
6
"""Extension point: the Detector protocol. Detectors operate ONLY on ``StepEvent``. They must be O(1) amortized per step (project.md §1.5) and must never raise into the host agent -- the Monitor wraps every ``observe`` call in a fail-open guard. ``reset`` is called when an episode ends so per-episode state does not le...
Cyrax321/SNAGLINE
src/snagline/detectors/base.py
.py
4bb4e5da9626a654
7.42
6
"""Compaction tripwire: governance-decay detection across compactions. Motivation (issue #90): arXiv:2606.22528 studies "governance decay": when a host agent compacts its context (summarization, truncation, eviction), the governance constraints stated earlier in that context can silently drop out, and policy-violation...
Cyrax321/SNAGLINE
src/snagline/detectors/compaction_tripwire.py
.py
8c40e24bb9fcdddc
7.42
6
"""Error-cascade detector (tier-1, deterministic, O(1) amortized). Same sliding-window shape as the loop detector but tracks the ``error`` boolean per episode instead of signatures. Fires on either of two conditions: * Consecutive: ``cascade_consecutive_threshold`` (default 3) errors in a row -- catches fast ca...
Cyrax321/SNAGLINE
src/snagline/detectors/error_cascade.py
.py
159d904a4fd3c193
7.42
6
"""Goal-drift detector (next phase, step 2). Compares a live run's per-tool behavior against a *persisted healthy* ``BaselineProfile`` (see ``snagline.baseline``) and flags meaningful drift: a rising error rate, latency blowing past the healthy mean by several sigmas, or tools that never appeared in the healthy baseli...
Cyrax321/SNAGLINE
src/snagline/detectors/goal_drift.py
.py
fef142bcf3add1ce
7.42
6
"""Latency / CUSUM anomaly detector (tier-1, deterministic, O(1) amortized). Stdlib-only. Per ``(episode_id, tool_name)`` it learns a baseline mean/variance via Welford's algorithm during a short warm-up, *freezes* that baseline, and then feeds standardized deviations into a CUSUM-with-alarms statistic:: cusum = ...
Cyrax321/SNAGLINE
src/snagline/detectors/latency_anomaly.py
.py
9008d5dad2970152
7.42
6
"""Loop detector (tier-1, deterministic, O(1) amortized). Per-episode sliding window (``collections.deque``) of recent ``action_signature`` values. If the same signature appears ``repeat_threshold`` times within ``window_size`` steps, emit a risk. Each looping signature escalates once and then stays quiet until that ...
Cyrax321/SNAGLINE
src/snagline/detectors/loop.py
.py
9b721a52cbd33199
7.42
6
"""Meltdown detector (opt-in): entropy collapse / thrash detection. Long-horizon agents exhibit a characteristic transition called *meltdown* (arXiv:2603.29231, which detects it via sliding-window entropy over tool-call sequences): coherent behavior degrades into either rote repetition or chaotic churn. This detector ...
Cyrax321/SNAGLINE
src/snagline/detectors/meltdown.py
.py
85c7e9b7fbf2f0ea
7.42
6
"""ML ensemble detector (next phase, step 3). An orchestrator that combines the signals of several base detectors into a single, stronger failure risk. The default combiner is a transparent, dependency-free *noisy-OR* over the base detectors' scores (``1 - prod(1 - score_i)``), which boosts confidence when multiple i...
Cyrax321/SNAGLINE
src/snagline/detectors/ml_ensemble.py
.py
4784b746453debd3
7.42
6
"""Side-effect guard: duplicate non-idempotent action detection (issue #88). Adapters and hosts mark steps whose action is known to be non-idempotent (a payment, a send, a deploy) with ``StepEvent.side_effect=True``. Within one episode, the second occurrence of the same ``(tool_name, action_signature)`` pair emits a H...
Cyrax321/SNAGLINE
src/snagline/detectors/side_effect_guard.py
.py
4d2399823e8105e2
7.42
6
"""Silent-abort detector (opt-in completion check, evaluated at episode end). The run looked clean -- no loop, no cascade, no latency shift -- but the very last ingested step was an error-free bare tool call instead of an output step. The agent stopped mid-work without producing its result: a failure of *omission*. No...
Cyrax321/SNAGLINE
src/snagline/detectors/silent_abort.py
.py
a0fa2448da018217
7.42
6
"""Stagnation detector: novelty-rate collapse ("stuck" is not "loop"). ``LoopDetector`` asks whether the agent repeats identical actions; this detector asks whether it discovers anything new at all (issue #87). An agent can evade exact loop matching by varying its arguments slightly: near duplicates produce distinct s...
Cyrax321/SNAGLINE
src/snagline/detectors/stagnation.py
.py
46d9e79f763ce842
7.42
6
"""Window auto-scaling shared by window-based detectors (issue #92). Fixed windows tuned for interactive runs (``loop_window_size=12``) mean nothing across a 500k-step week-long episode: they either fire constantly or are gone in the first minute of noise. When ``Config.window_scale_steps`` is set (> 0), each detector...
Cyrax321/SNAGLINE
src/snagline/detectors/windowing.py
.py
3b0173750affaf0c
7.42
6
"""Canonical event schema for SNAGLINE. This is the only wire format detectors and sinks ever see. Framework-specific adapters translate their host runtime's events into ``StepEvent`` instances and pass them to ``Monitor.ingest``. No core code imports a framework. Design constraints honored here (see project.md §1): ...
Cyrax321/SNAGLINE
src/snagline/events.py
.py
abca66e91e1dd3e7
7.42
6
"""FastAPI application for the Indian Market Trading Agent.""" import sys import os # Add project root to path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from dotenv import load_dotenv load_dotenv(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ".env"), ...
pradeepsiddappa/indian-trading-agent
backend/app.py
.py
b51584fb05ddec3d
7.65
19
"""Application authentication and request-boundary security. This is a single-user application boundary, not an account/authorization system. Local browser authentication is opt-in; public deployments always require an explicitly configured credential. When enabled, a shared secret establishes one signed session cooki...
pradeepsiddappa/indian-trading-agent
backend/auth.py
.py
1da425be44c529b9
7.65
19
"""Core backtesting engine — runs the AI pipeline on historical dates and tracks P&L.""" import time import yfinance as yf from datetime import datetime, timedelta from typing import Optional from tradingagents.utils.ticker import normalize_ticker from tradingagents.utils.market_calendar import is_trading_day, next_tr...
pradeepsiddappa/indian-trading-agent
backend/backtest_engine.py
.py
84b85108213baaa3
8.15
19
"""Sector Concentration Checker. Prevents the AI from over-exposing to a single sector. Critical for autonomous trading because 5 BUY signals in one morning could all be in the same sector — making them essentially one trade with 5x the risk. Sources of "open positions" we track: 1. Paper trades (status='active') fro...
pradeepsiddappa/indian-trading-agent
backend/concentration.py
.py
d8bdb13469d905b7
7.65
19
"""Confidence Calibration — measures whether the recommender's stated `success_probability` is honest. The recommendation engine outputs a `success_probability` (e.g., 65%) for every pick. This module checks: when the engine says 65%, do the trades actually win 65% of the time? Or is it overconfident (says 65%, wins 5...
pradeepsiddappa/indian-trading-agent
backend/confidence_calibration.py
.py
600500cba829b7ec
7.65
19
"""Cyclical pattern analysis — monthly seasonality, sector rotation, event cycles.""" import yfinance as yf import numpy as np from datetime import datetime, timedelta from collections import defaultdict from tradingagents.utils.ticker import normalize_ticker MONTH_NAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "...
pradeepsiddappa/indian-trading-agent
backend/cyclical.py
.py
5c87c5e47c2e7f44
7.65
19
"""FII/DII Daily Flow Tracker. Fetches FII (Foreign Institutional Investor) and DII (Domestic Institutional Investor) daily buy/sell data — the single biggest predictor of next-day market direction in Indian markets. Data sources (with fallback chain): 1. NSE India official API (requires cookies + headers) 2. Moneyco...
pradeepsiddappa/indian-trading-agent
backend/fii_dii.py
.py
2b0c15cc8a9b810b
7.65
19
"""Learning Insights — analyzes past trades (paper + real) to surface patterns. Pure statistical analysis, no ML training. Helps user identify: - Which signals work best for THEM - Which market conditions their strategy fails in - When confidence levels are reliable vs noise - Seasonal patterns in their trading result...
pradeepsiddappa/indian-trading-agent
backend/insights.py
.py
46527c16551d5c2c
7.65
19
"""Market regime classifier — labels every trading day as one of 4 regimes based on Nifty technicals. Used to make signal performance conditional on regime ('this signal works in bull markets but fails in bear'). Regimes: - BULL: Nifty > 50 SMA > 200 SMA, low/normal vol - BEAR: Nifty < 50 SMA < 200 SMA, ...
pradeepsiddappa/indian-trading-agent
backend/market_regime.py
.py
616b0e310c4b6c32
7.65
19
"""News aggregator — pulls from multiple Indian market news sources. Supports: - yfinance search queries (general market / custom queries) - RSS feeds from Indian news sites - Stock-specific news via yfinance """ import yfinance as yf import feedparser from datetime import datetime, timedelta from concurrent.futures ...
pradeepsiddappa/indian-trading-agent
backend/news_sources.py
.py
1e0c4d1d3d81f808
7.65
19
"""Local position tracking with explicit, read-only Kite synchronization.""" from datetime import datetime, timezone from datetime import date from threading import Lock from typing import Any from backend.db import delete_position, get_position, get_setting, list_positions, replace_kite_positions, set_setting, upser...
pradeepsiddappa/indian-trading-agent
backend/positions.py
.py
409263899e5c92eb
7.65
19
"""Analysis endpoints — run multi-agent analysis with WebSocket streaming.""" import asyncio import uuid import time import threading from fastapi import APIRouter, WebSocket, WebSocketDisconnect, BackgroundTasks from backend.models import AnalysisRequest, AnalysisResponse from backend.ws import manager from backend.d...
pradeepsiddappa/indian-trading-agent
backend/routers/analysis.py
.py
b40280cbbecec511
7.65
19
"""Login/logout routes for the single-user application boundary.""" import os import secrets from fastapi import APIRouter, Request from fastapi.responses import JSONResponse from pydantic import BaseModel from backend.auth import CSRF_COOKIE, SESSION_COOKIE, auth_required, cookie_secure, make_session, public_mode, ...
pradeepsiddappa/indian-trading-agent
backend/routers/auth.py
.py
26a222eb7128cee4
7.65
19
"""Backtest endpoints — run historical backtests with P&L tracking.""" import uuid import threading import asyncio from fastapi import APIRouter, WebSocket, WebSocketDisconnect from pydantic import BaseModel from typing import Optional from backend.ws import manager from backend.db import ( save_backtest_run, ...
pradeepsiddappa/indian-trading-agent
backend/routers/backtest.py
.py
8e25196ffd02d97c
8.15
19
"""Calendar API — earnings + economic events.""" from fastapi import APIRouter, Query from datetime import date, timedelta, datetime from backend.calendar_data import ( get_today_events, get_upcoming_events, get_event_filter_for_ticker, refresh_earnings_calendar, get_market_events_in_range, get...
pradeepsiddappa/indian-trading-agent
backend/routers/calendar.py
.py
a43b33203e85a147
7.65
19
"""Sector Concentration API.""" from fastapi import APIRouter, Query from backend.concentration import ( get_sector_allocation, get_concentration_summary, check_new_trade_concentration, get_open_positions, get_sector_for_ticker, ) router = APIRouter(prefix="/api/concentration", tags=["concentratio...
pradeepsiddappa/indian-trading-agent
backend/routers/concentration.py
.py
6294cfe868d07b5d
7.65
19
"""FII/DII API — daily institutional flow tracker.""" from fastapi import APIRouter, Query from pydantic import BaseModel from backend.fii_dii import ( get_today_data, get_recent_history, get_market_bias, manual_entry, get_data_for_date, ) router = APIRouter(prefix="/api/fii-dii", tags=["fii-dii"]...
pradeepsiddappa/indian-trading-agent
backend/routers/fii_dii.py
.py
0dfafd0313b3b60c
7.65
19
"""Kite Connect OAuth, credential status, and read-only session routes.""" from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit from fastapi import APIRouter, HTTPException, Request from fastapi.responses import RedirectResponse from pydantic import BaseModel from backend.auth import frontend_page_url...
pradeepsiddappa/indian-trading-agent
backend/routers/kite.py
.py
df9c4f897ec47389
7.65
19
"""Agent memory admin API — list, inspect, prune BM25 memories per agent. Backs the /memory-admin frontend page (Tier 4.2 — Memory pruning + decay). """ from fastapi import APIRouter, HTTPException from pydantic import BaseModel from typing import Optional from tradingagents.agents.utils.memory import ( Financia...
pradeepsiddappa/indian-trading-agent
backend/routers/memory.py
.py
5ff38a0e2a3dc55e
7.65
19
"""News Feed API — aggregates news from multiple sources.""" from fastapi import APIRouter, Query from pydantic import BaseModel from backend.news_sources import ( fetch_all_news, fetch_ticker_news, get_news_sources_config, save_news_sources_config, ) router = APIRouter(prefix="/api/news", tags=["news...
pradeepsiddappa/indian-trading-agent
backend/routers/news.py
.py
529fc7a8e2d62d45
7.65
19
"""Recommendation Engine API — combines all strategies into ranked trade ideas.""" from fastapi import APIRouter, Query from backend.recommender import recommend, _analyze_stock router = APIRouter(prefix="/api/recommend", tags=["recommend"]) @router.get("/") def get_recommendations( universe: str = Query("nifty...
pradeepsiddappa/indian-trading-agent
backend/routers/recommender.py
.py
4bbb897ae1c52b4a
7.65
19
"""Market regime API — current regime classifier + backfill + conditional signal stats.""" from fastapi import APIRouter from datetime import date from backend.market_regime import get_current_regime, classify_regime_for_date from backend.regime_backfill import backfill_regime_at_entry from backend.signal_performance...
pradeepsiddappa/indian-trading-agent
backend/routers/regime.py
.py
c7085d1c96b7fa59
7.65
19
"""Market Scanner API endpoints.""" from fastapi import APIRouter from pydantic import BaseModel from backend.scanner import run_scan, UNIVERSES router = APIRouter(prefix="/api/scanner", tags=["scanner"]) class ScanRequest(BaseModel): universe: str = "nifty50" strategies: list[str] = ["gap", "volume", "brea...
pradeepsiddappa/indian-trading-agent
backend/routers/scanner.py
.py
0d64c0e954991d00
7.65
19
"""Settings API — manage API keys and LLM provider config from the UI.""" import json import logging import urllib.request from fastapi import APIRouter from pydantic import BaseModel from backend.settings_manager import ( get_api_keys_status, save_api_key, test_api_key, get_llm_config, save_llm_c...
pradeepsiddappa/indian-trading-agent
backend/routers/settings.py
.py
b00e39754416cc12
7.65
19
"""Shadow trades API — counterfactual tracking of every STRONG BUY / HIGH-conf BUY the recommender produces, regardless of whether the user clicked Track.""" from fastapi import APIRouter from backend.shadow_trades import ( list_shadow_trades, refresh_shadow_prices, shadow_vs_user_comparison, ) router = ...
pradeepsiddappa/indian-trading-agent
backend/routers/shadow_trades.py
.py
57c61c9e992659e5
7.65
19
"""Per-signal performance API — track which recommender signals actually win, and let the user auto-tune the weights from real trade outcomes.""" from fastapi import APIRouter from pydantic import BaseModel from typing import Optional from backend.signal_performance import ( compute_signal_performance, apply_...
pradeepsiddappa/indian-trading-agent
backend/routers/signal_performance.py
.py
f785ca30e0257640
7.65
19
"""Simulation API — paper trading + historical recommender backtest.""" from fastapi import APIRouter, Query from pydantic import BaseModel from backend.simulation import ( open_paper_trade, close_paper_trade as close_paper_trade_fn, refresh_paper_trade_prices, paper_trading_stats, run_recommender_...
pradeepsiddappa/indian-trading-agent
backend/routers/simulation.py
.py
c519a6befc0866c7
7.65
19
"""Strategy endpoints — Support/Resistance, Pivot Points, and strategy-based signals.""" from fastapi import APIRouter, Query import yfinance as yf import numpy as np from datetime import datetime, timedelta from tradingagents.utils.ticker import normalize_ticker from backend.cyclical import ( analyze_monthly_seas...
pradeepsiddappa/indian-trading-agent
backend/routers/strategies.py
.py
f1d5118883558749
7.65
19
""" CyberHuaTuo 配置管理 从 .env 文件和环境变量中加载配置 """ import os import sys from pathlib import Path from dotenv import load_dotenv def _discover_root_dir() -> Path: """ 智能发现项目根目录: 1. 开发模式:__file__ 的父级父级目录(包含 cases/ 目录) 2. uvx / pip install 模式: - 检查 site-packages 中 cyberhuatuo_data (data_files) ...
JinNing6/CyberHuaTuo
cyberhuatuo/config.py
.py
7517b1d8b6318ab6
7.54
11
""" CyberHuaTuo 药方贡献生成器 帮助开发者快速生成规范格式的病例文件 """ import json import re from dataclasses import dataclass, field from datetime import date from typing import Any import litellm from .config import config from .doc_sources import get_agent_framework_keys # 框架枚举值(从 doc_sources 动态获取 Agent 框架列表) FRAMEWORKS = get_agent_fra...
JinNing6/CyberHuaTuo
cyberhuatuo/contributor.py
.py
fa11b86291ddc083
7.54
11
""" CyberHuaTuo 望闻问切诊断引擎 基于 LLM 的智能诊断(需要 API Key) 支持注入 Context7 官方技术文档上下文 """ from .config import config from .doc_fetcher import DocSnippet, smart_fetch from .searcher import SearchResult SYSTEM_PROMPT = """你是赛博华佗(CyberHuaTuo),一个专精于 AI 技术问题诊断的智能医师。 你的诊疗范围涵盖所有 AI 相关领域: - AI Agent 框架(LangChain、CrewAI、AutoGen、LlamaInd...
JinNing6/CyberHuaTuo
cyberhuatuo/diagnosis.py
.py
deb21c85c08c7e8a
7.54
11
""" CyberHuaTuo 官方文档检索器 通过 Context7 REST API 获取最新官方技术文档,支持智能体直接检索 """ import asyncio from dataclasses import dataclass from typing import Any import httpx from .config import config from .doc_sources import ( ALL_FRAMEWORKS, get_framework, search_frameworks, ) @dataclass class DocSnippet: """检索到的文档...
JinNing6/CyberHuaTuo
cyberhuatuo/doc_fetcher.py
.py
dadcbf31f44ea0df
7.54
11
""" 🤖 CyberHuaTuo GitHub Bot — 入口脚本 被 GitHub Actions workflow 调用,自动在 Issue 中回复匹配的药方 用法: python -m cyberhuatuo.github_bot \\ --event-type "issues" \\ --event-path "/path/to/event.json" 环境变量: GITHUB_TOKEN — GitHub Actions 自动提供 GITHUB_REPOSITORY — 格式 "owner/repo" BOT_MIN_SCORE —...
JinNing6/CyberHuaTuo
cyberhuatuo/github_bot.py
.py
c2b06025f2d0bf2e
7.54
11
""" CyberHuaTuo 索引构建器 解析 cases/ 目录下所有 .md 病例文件,构建 ChromaDB 向量索引 """ import hashlib import re from pathlib import Path from typing import Any import chromadb import yaml from .config import config def parse_case_file(filepath: Path) -> dict[str, Any] | None: """ 解析单个病例文件,提取 YAML 元数据和 Markdown 正文 Return...
JinNing6/CyberHuaTuo
cyberhuatuo/indexer.py
.py
2e45d0a6e3b38d7e
7.54
11
""" CyberHuaTuo 滋补药方引擎 AI 安全体检 + 健康评分 + 滋补方案推荐 """ import json from .config import config # ===== 安全体检 System Prompt ===== CHECKUP_SYSTEM_PROMPT = """你是赛博华佗(CyberHuaTuo)的「养生堂」紫金阶炼丹师,专精于 AI Agent 代码的六经脉安全体检和健康评估。 请以严谨的赛博东方医学口吻(如“诊断发现心火过旺”、“需服用安全护肩散”等),对代码进行望闻问切。 你的职责不是修复 Bug(那是「急诊科」的事),而是: 1. 对用户提交的 Agent 代码进行全面的「安...
JinNing6/CyberHuaTuo
cyberhuatuo/nourishing.py
.py
cdd259efe5cb5df2
7.54
11
""" Llama Guard 3 真实基线评估器 Llama Guard 3 是 Meta 的安全分类模型,输入 user/agent 对话 → 输出 safe/unsafe。 我们将其作为 TEC 的真实基线对比: - TEC: 运行时策略引擎,检测工具调用参数 - Llama Guard: 预检分类器,检测 prompt 本身是否恶意 评估方式: 1. 将每个场景的 user_prompt 发给 Llama Guard 3 2. 如果判定 unsafe → 视为"拦截" 3. 如果判定 safe → 视为"放行" 4. 对比 TEC 的拦截率 这是一种公平的对比,因为论文中 Llama Guard 被定位为"提示级防护"...
JinNing6/CyberHuaTuo
cyberhuatuo/sandbox/benchmark/llama_guard_eval.py
.py
e60fe035d3f87f62
7.54
11
""" TEC Benchmark — LLM 端到端评估引擎 """ import time import logging from cyberhuatuo.sandbox.policy import PolicyEngine from cyberhuatuo.sandbox.schemas import PolicyAction from cyberhuatuo.sandbox.benchmark.harness import ScenarioResult, SystemResult, CategoryResult from cyberhuatuo.sandbox.benchmark.llm_driver import Ba...
JinNing6/CyberHuaTuo
cyberhuatuo/sandbox/benchmark/llm_harness.py
.py
060662e462ed7beb
7.54
11
""" McNemar 统计检验 — 用于比较两个安全系统在同一测试集上的差异显著性 用法: python -m cyberhuatuo.sandbox.benchmark.mcnemar \ --result_a llm_eval_full549.txt \ --result_b llm_eval_full549_v2.txt 原理: McNemar's test 检验两个分类器在同一数据集上的预测差异是否显著。 构建 2×2 混淆矩阵: - b: A对B错 (A拦截了但B漏拦) - c: A错B对 (A漏拦了但B拦截) χ² = (|b ...
JinNing6/CyberHuaTuo
cyberhuatuo/sandbox/benchmark/mcnemar.py
.py
9b530b401980fb82
7.54
11
""" TEC LLM 端到端测试入口 CLI 支持三种模式: - core: 仅跑手工精选的 10 个核心场景(快速验证) - full: 跑全部 550 个自动生成的场景(学术级评估) - sample: 从 550 个场景中随机抽样 N 个 实验数据自动遵循三层安全架构: - 层1: Append-Only 全局账本 (data/experiment_ledger.csv) - 层2: 不可变原始快照 (data/runs/{timestamp}_{model}/) - 层3: 最新视图 + 备份 (data/latest/ + data/history/) """ import csv import json impo...
JinNing6/CyberHuaTuo
cyberhuatuo/sandbox/benchmark/run_llm_eval.py
.py
105b19e4ef301bbb
7.54
11
""" CyberHuaTuo 搜索引擎 — 双层药方库架构 Search Engine — Dual-layer Prescription Architecture 支持两个搜索源: 1. 常驻药方库(ChromaDB 向量语义搜索) 2. 瞬时药方库(GitHub Issues API 搜索) """ import json import logging import re from dataclasses import dataclass import chromadb import httpx from .config import config from .indexer import get_case_c...
JinNing6/CyberHuaTuo
cyberhuatuo/searcher.py
.py
76ab15483de6856d
7.54
11
""" 赛博华佗 · 版本检查模块 CyberHuaTuo · Version Update Checker 在 MCP Server 启动时后台异步检查 PyPI 最新版本, 如果发现有更新,在用户首次调用工具时输出温和提示。 """ import logging import threading from typing import Optional logger = logging.getLogger("cyberhuatuo.version_check") # 全局状态:更新提示信息(线程安全写入,主线程读取) _update_notice: Optional[str] = None _check_done = Fa...
JinNing6/CyberHuaTuo
cyberhuatuo/version_check.py
.py
47e61653b64c9da5
7.54
11
""" 终端动画 → asciicast → GIF 录制器 Recording terminal animations as asciicast v2 format for GIF conversion. 用法: python tapes/record_animations.py boot # 录制启动动画 python tapes/record_animations.py effects # 录制电影级特效 python tapes/record_animations.py all # 录制全部 """ import io import json import sys import...
JinNing6/CyberHuaTuo
tapes/record_animations.py
.py
b387c68c75845d4c
7.54
11
""" 🦠 CyberHuaTuo 测试 — 疫情通报模块 测试健康分数计算、异常检测、报告生成等核心逻辑 所有测试使用 mock 数据,不依赖外部 API """ import json from dataclasses import field import pytest import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent.resolve())) from cyberhuatuo.epidemic_monitor import ( FrameworkHealthData, Crit...
JinNing6/CyberHuaTuo
tests/test_epidemic.py
.py
7bd504a9ab9a17a9
8.04
11
# -*- coding: utf-8 -*- """ TTS MultiModel - 应用启动脚本 ============================== 项目名称: TTS MultiModel (多引擎语音合成平台) 主要功能: 应用程序的主启动入口,负责环境初始化、配置加载、模型检查和服务启动 核心技术栈: Python + asyncio + FastAPI + WinPython (Windows 便携版) 启动链路: start.bat -> clean_launch.py -> integrated_app/app_server.py 启动流程: 1. 环境变量初始化 - 设置离线模式、OpenM...
ReSerendipity/TTS_MultiModel
app/clean_launch.py
.py
584e81f773cb51c2
7.48
8
"""音频文件水印嵌入与提取(P2-1: 输出音频水印可溯源,来源:Image_MultiModel DCT 水印思路)。 本模块在已有的 ``watermark.py``(numpy 级 FFT 频域水印)基础上,提供文件路径级别的 水印嵌入与提取 API,并增加 CRC32 校验 + Base62 编码的 payload 序列化方案。 水印方案: - 底层使用 ``watermark.py`` 的 FFT 频域扩频水印(16-20kHz 高频段嵌入) - payload 序列化:dict → JSON → CRC32 校验 → Base62 编码 → 嵌入音频 - 提取时先校验 CRC32,防篡改 使用方式::...
ReSerendipity/TTS_MultiModel
app/integrated_app/audio_watermark.py
.py
40732f67269431aa
7.48
8
"""Bearer Token API 认证中间件模块。 架构说明: 本模块提供基于 Bearer Token 的程序化 API 认证,作为 ASGI 中间件 挂载在 FastAPI 调用栈中。使用 ``hmac.compare_digest`` 恒定时间比较 防止定时攻击(Timing Attack)逐字节爆破 token。 配置入口(config.yaml): api_auth: enabled: true # 是否启用 Bearer Token 认证 token: "your-token" # 期望的 Bearer Token 明文 与 CS...
ReSerendipity/TTS_MultiModel
app/integrated_app/auth.py
.py
a3ee33b68351e8dc
7.48
8
"""坏案例自动重试机制(Bad Case Retry) 参考 Fish Speech、CosyVoice 和 Chatterbox 的容错设计: - 检测退化输出(静音、过短、爆音、重复模式等) - 多维度参数调整策略(cfg_value、temperature、top_p、seed) - 指数退避 + 参数渐进调整 - 重试耗尽时优雅降级,不中断整体生成 核心策略: 1. 第一次重试:递增 cfg_value + 新 seed 2. 第二次重试:提高 temperature + 降低 top_p + 新 seed 3. 第三次重试:大幅提高 cfg_value + 提高 temperature +...
ReSerendipity/TTS_MultiModel
app/integrated_app/bad_case_retry.py
.py
1899479b9c58e4fb
7.48
8
""" 批量推理工具 - 提供高效的批量 TTS 推理能力。 在显存允许的范围内,将多个文本片段批量送入模型推理, 相比逐句推理可显著减少 GPU kernel launch 开销,提升整体吞吐量。 包含动态 batch size 调整、显存自适应和错误回退机制。 """ from __future__ import annotations import logging import time from collections.abc import Callable from dataclasses import dataclass from typing import TYPE_CHECKING, Any import t...
ReSerendipity/TTS_MultiModel
app/integrated_app/batch_inference.py
.py
0e7729d2b4d012e5
7.48
8
"""断点续跑管理器(来源:Image_MultiModel 的 checkpoint.py)。 TTS 批量剧本配音 / 批量克隆任务执行到一半被中断(用户关闭窗口 / 断电 / OOM 崩溃)时, 已生成的音频不会浪费。Checkpoint 机制记录已完成的子任务,重启后可跳过已完成的子任务。 存储格式: ``data/checkpoints/{task_id}.json`` P1-2 改造:适配 TTS_MultiModel 项目结构,使用原子写入保存 checkpoint 文件。 """ from __future__ import annotations import contextlib import json...
ReSerendipity/TTS_MultiModel
app/integrated_app/checkpoint.py
.py
8a7cc74c1206f1df
7.48
8
"""VoxCPM2 生成函数装饰器模块。 架构说明: 本模块将 VoxCPM2 各生成函数(design/clone/ultimate/script/streaming/prompt) 中重复的"模型就绪检查 → 生成锁获取 → 追踪器启停 → 进度管理 → 异常处理 → 耗时日志"模式抽取为可复用装饰器,避免各子模块重复样板代码。 主要组件: with_generation_context: 核心装饰器工厂,统一处理生成上下文管理。 依赖关系: - model_registry.registry: 获取 voxcpm_model 实例检查模型是否加载 - model_mana...
ReSerendipity/TTS_MultiModel
app/integrated_app/engines/voxcpm2/decorators.py
.py
fa5da6fe7922417b
7.48
8
"""VoxCPM2 语音设计(Prompt-based Voice Design)子模块。 本模块在 VoxCPM2Engine 门面模式中承担「文本描述 → 定制音色」生成子系统的角色: - 上层入口:`engine.py` 的 `VoxCPM2Engine.design(description, text, **kwargs)` 方法 最终委托本模块的 `fn_voxcpm_design()` 公开函数完成实际推理。 - 路由协作:`routes/generate/voxcpm2/design_route.py` 通过 FastAPI 端点接收前端 请求(description、text、cfg、steps、deno...
ReSerendipity/TTS_MultiModel
app/integrated_app/engines/voxcpm2/design.py
.py
a3905cdad30ce5a8
7.48
8
"""生成时间估算器模块。 本模块实现 :class:`GenerationTimeEstimator`,通过持久化线性回归训练样本 (字符数 → 实际耗时)对新的 TTS 生成任务预测耗时。 数据持久化 ---------- 训练样本以 JSON 格式存储在 ``data/generation_times.json`` 文件中, 采用滑动窗口策略,最多保留 ``max_entries`` 条记录(默认 200 条), 防止数据文件无限增长。 调用链路 -------- - ``model_manager`` 在每段生成完成后调用 :meth:`record_sample` 记录样本 - 估算结果通过 ``/api/sse/t...
ReSerendipity/TTS_MultiModel
app/integrated_app/estimator.py
.py
b011e959b07d831a
7.48
8
"""FTS5 中文分词改进模块。 使用 jieba 对中文关键词进行分词预处理,提升 FTS5 全文搜索的召回率。 当前 history_db 使用 trigram 分词器,对 >=3 字符的子串匹配良好, 但对中文短语分词不友好("语音合成" 会匹配 "语音合" 和 "音合成" 而非语义化的 "语音" + "合成")。 本模块提供预处理函数,将中文关键词分词后构建更精确的 FTS5 查询。 使用方式(在 history_db.py 的 _build_fts_query 中调用):: from .fts_tokenizer import tokenize_search_keyword fts_query ...
ReSerendipity/TTS_MultiModel
app/integrated_app/fts_tokenizer.py
.py
3eeb17c939f53b1a
7.48
8
"""JSON 文件驱动的 i18n 国际化模块。 支持五种语言(zh-CN/zh-TW/en/ja/ko),翻译内容以 JSON 文件形式存储在 `locales/` 目录中。 两层 fallback 链保障翻译永不显示空值: 1. 用户指定语言 → 英文(en)回退 → key 本身兜底(三层保障) 2. 翻译键查找支持两种模式:扁平键直接命中(含 "." 字符的整串) 和命名空间嵌套(namespace.sub.key 逐段下钻)。 """ import json import logging import os from typing import Any _LOCALES_DIR: str = os.path...
ReSerendipity/TTS_MultiModel
app/integrated_app/i18n.py
.py
7ffe0d9cf291b243
7.48
8
# SPDX-FileCopyrightText: 2026 ReSerendipity # SPDX-License-Identifier: Apache-2.0 """轻量级 API 速率限制中间件。 P2 安全修复:防止单 IP 狂发生成请求打爆 GPU 资源。 使用滑动窗口算法,纯内存实现,无需外部依赖。 配置项(通过 config.yaml 的 rate_limit 节或环境变量): - enabled: 是否启用(默认 true) - requests_per_minute: 每分钟最大请求数(默认 10,仅限 /api/generate/* 路径) - burst: 允许的突发请求数(默认 ...
ReSerendipity/TTS_MultiModel
app/integrated_app/middleware/rate_limit.py
.py
7bd0deef1a0d8f2e
7.48
8
"""请求 ID 中间件 — 为每个入站 HTTP 请求分配全局唯一标识符。 架构角色: 本模块实现 ASGI 全局请求 ID 中间件,为每个入站请求分配 UUID4(16 hex) request_id,并完成三件事: 1. 将 request_id 注入 Python logging 上下文(通过 ContextVar + 线程本地镜像) 使整条链路(middleware → route → model_manager → SSE 事件)的日志都能 自动携带 request_id,用于 ELK/EFK 日志聚合与分布式链路追踪。 2. 在响应中写入 `...
ReSerendipity/TTS_MultiModel
app/integrated_app/middleware/request_id.py
.py
7b4ed71eb744a86c
7.48
8
"""模型管理模块(薄门面,M-R7 拆分,2026-08-17)。 提供模型加载、卸载、引擎切换、LRU 缓存、进度追踪、GPU 显存监控以及音色缓存预热。 支持 VoxCPM2 与 IndexTTS 2.5 双引擎架构。 M-R7: 实现拆分至 model_manager_core 子包: - state: 共享状态/常量/单例(_model_lock、_persona_embedding_cache 等) - load: load_voxcpm2 / load_indextts2 / PreloadService / PersonaWarmupService - unload: unload_model / _chec...
ReSerendipity/TTS_MultiModel
app/integrated_app/model_manager.py
.py
213b0b15ba0e1d35
7.48
8
"""Windows Credential Manager Tier-2 backend. In-process ``ctypes`` against ``advapi32.dll``'s ``CredReadW`` / ``CredWriteW`` / ``CredDeleteW`` / ``CredFree`` — stdlib only, no ``pywin32`` dependency. Token bytes never cross a process boundary; the entire flow stays inside the Python heap. Struct layout: per ``wincre...
eugenelim/agent-ready-repo
.agentbundle/bin/_sso_credman_windows.py
.py
a09d2d3a508aab43
7.63
17
"""Windows Credential Manager Tier-2 backend. In-process ``ctypes`` against ``advapi32.dll``'s ``CredReadW`` / ``CredWriteW`` / ``CredDeleteW`` / ``CredFree`` — stdlib only, no ``pywin32`` dependency. Token bytes never cross a process boundary; the entire flow stays inside the Python heap. Struct layout: per ``wincre...
eugenelim/agent-ready-repo
.agentbundle/lib/credbroker/_credman_windows.py
.py
3c7efb44786c7a65
7.63
17
#!/usr/bin/env python3 """Activation-collision check for a migrated skill's description: target-state craft conformance — activation + no collision. When assimilation rewrites a skill's `description`, that description must not collide with an existing skill's — two skills fighting for the same natural phrasing degrade...
eugenelim/agent-ready-repo
.agents/skills/assimilate-primitive/scripts/collision_check.py
.py
cb37bf1f59087c8c
7.63
17
#!/usr/bin/env python3 """SSRF-guarded source validation for catalogue-curation ingest: URL-source SSRF confinement. A source is a local path or a URL. A URL is fetched only over an allowlisted scheme, and never to a private / loopback / link-local / cloud-metadata address — the design-time control is the allowlist, n...
eugenelim/agent-ready-repo
.agents/skills/assimilate-primitive/scripts/ssrf_check.py
.py
0869399e13b73d5f
7.63
17
#!/usr/bin/env python3 """Write-confinement for catalogue-curation, via the blessed helper. A thin wrapper over the engine's blessed path-jail — `agentbundle.safety` (`write_jailed` / `assert_under`: resolve → resolve symlinks → verify-prefix). We **reuse** it, never roll our own path handling: a traversing/absolute p...
eugenelim/agent-ready-repo
.agents/skills/assimilate-primitive/scripts/write_jail.py
.py
2d366e730d75baab
7.63
17
"""Cross-process advisory lock for a state-file read-modify-write. A project-knowledge script, owned by this skill. Stdlib only — no ``agentbundle`` import, direct or lazy — so it works in adopter trees and user-scope installs where nothing else is on the path. Its siblings load it by path (``importlib.util.spec_from_...
eugenelim/agent-ready-repo
.agents/skills/project-knowledge/scripts/_statelock.py
.py
ba8c05c78bd2b4ae
7.63
17
#!/usr/bin/env python3 """Brief-coverage auto-rollup lint. This is a `receive-brief` **skill script**: it lives at `packs/core/.apm/skills/receive-brief/scripts/lint-brief-coverage.py` and projects to every adapter's `.../skills/receive-brief/scripts/`, the same way the work-loop's `lint-spec-status.py` does. The agen...
eugenelim/agent-ready-repo
.agents/skills/receive-brief/scripts/lint-brief-coverage.py
.py
fb052a1e4ccdbb06
7.63
17
"""Pre-write confidentiality and minimal-intent rendering guards.""" from __future__ import annotations import json import os import re import stat from dataclasses import dataclass from pathlib import Path from typing import Protocol class NormalizedIntakeLike(Protocol): """Validated intake fields used by the ...
eugenelim/agent-ready-repo
.agents/skills/work-intake/scripts/intake_guard.py
.py
7c6c6ec8b076611b
7.63
17
"""Fail-closed sequencing for durable artifact creation, registration, and dispatch.""" from __future__ import annotations import re from collections.abc import Callable from dataclasses import dataclass from enum import Enum from pathlib import Path class TransactionStatus(Enum): """Terminal state of one intak...
eugenelim/agent-ready-repo
.agents/skills/work-intake/scripts/intake_transaction.py
.py
a621d62c337cdfc9
7.63
17
"""Cross-process advisory lock for a state-file read-modify-write. A work-loop script, owned by this skill. Stdlib only — no ``agentbundle`` import, direct or lazy — so it works in adopter trees and user-scope installs where nothing else is on the path. Its siblings load it by path (``importlib.util.spec_from_file_loc...
eugenelim/agent-ready-repo
.agents/skills/work-loop/scripts/_statelock.py
.py
8a43d3a7ffac7c5a
7.63
17
#!/usr/bin/env python3 """check-spec-status — guard: a spec or plan file must have a specific Status value. Used as the reviewers-clean guard in CODE-REVIEW → CODE-HUMAN-GATE (default: Status Shipped) and as the spec-approved / plan-approved / plan-locked guards (--expect Approved). Usage: check-spec-status.py <s...
eugenelim/agent-ready-repo
.agents/skills/work-loop/scripts/check-spec-status.py
.py
1e56d9613361c8b7
8.13
17
#!/usr/bin/env python3 """Validate an orchestrator-owned review artifact without disclosing its path or body.""" from __future__ import annotations import argparse import hashlib import os import re import stat import sys import uuid from dataclasses import dataclass from pathlib import Path from typing import Binary...
eugenelim/agent-ready-repo
.agents/skills/work-loop/scripts/review-artifact.py
.py
554d3b5eaae6e4a9
7.63
17
""" Creates a VERSION.txt file and then increments it over each Python script related commit. """ # Version 1.0.1 # Edited: 2026-02-09 15:18:54 +1100 # Generated using AI (duck.ai) # Tested on local PC and on GitHub # IMPORTS import os def read_version(): """ Reads the VERSION.txt file as ...
hl2guide/combined-adblock-lists
version_increment.py
.py
e19a07717a054172
7.6
15
"""Compare voluptuous and probatio (interpreted and compiled) validation throughput. Run with: ``uv run --no-sync python bench/bench.py``. For each scenario the same schema is built in voluptuous and in probatio, the probatio one twice: once interpreted (``compile=False``) and once compiled (``.compile()``). A fixed ...
frenck/probatio
bench/bench.py
.py
6ceebea763c0c1ba
7.59
14