vieforge 0.4.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- core/__init__.py +99 -0
- core/_bundled_assets/AGENTS.md +18 -0
- core/_bundled_assets/config/budget_limits.json +8 -0
- core/_bundled_assets/config/pricing.example.json +41 -0
- core/_bundled_assets/config/qa_error_codes.json +50 -0
- core/_bundled_assets/examples/01_batch_doc_processor/run_demo.py +177 -0
- core/_bundled_assets/extensions/tierforge-bridge/README.md +28 -0
- core/_bundled_assets/extensions/tierforge-bridge/SECURITY.md +14 -0
- core/_bundled_assets/extensions/tierforge-bridge/background.js +288 -0
- core/_bundled_assets/extensions/tierforge-bridge/content_bridge.js +193 -0
- core/_bundled_assets/extensions/tierforge-bridge/manifest.json +32 -0
- core/_bundled_assets/extensions/tierforge-bridge/popup.html +59 -0
- core/_bundled_assets/extensions/tierforge-bridge/popup.js +90 -0
- core/_bundled_assets/skills/three-tier-orchestrator/SKILL.md +30 -0
- core/_bundled_assets/skills/three-tier-orchestrator/references/hardware-profiles.md +21 -0
- core/_bundled_assets/skills/three-tier-orchestrator/references/routing-matrix.md +32 -0
- core/cdp_bridge.py +506 -0
- core/concurrency.py +189 -0
- core/cost_tracker.py +385 -0
- core/extension_bridge.py +593 -0
- core/license_audit.py +153 -0
- core/llm_router.py +309 -0
- core/output_trimmer.py +215 -0
- core/paths.py +44 -0
- core/pipeline_runner.py +98 -0
- core/qa_logger.py +106 -0
- core/state_db.py +367 -0
- core/step_auditor.py +550 -0
- core/subprocess_runner.py +157 -0
- core/vram_manager.py +298 -0
- mcp/mcp_config.example.json +14 -0
- mcp/worker_mcp_server.py +339 -0
- scripts/__init__.py +1 -0
- scripts/audit_step.py +38 -0
- scripts/benchmark_token_savings.py +383 -0
- scripts/browser_bridge.py +85 -0
- scripts/cli.py +76 -0
- scripts/extension_bridge_server.py +101 -0
- scripts/install_skill.py +184 -0
- scripts/preflight_check.py +401 -0
- scripts/quick_setup.py +128 -0
- scripts/start_tierforge_bridge.bat +8 -0
- scripts/verify_cross_os.py +360 -0
- vieforge-0.4.1.dist-info/METADATA +223 -0
- vieforge-0.4.1.dist-info/RECORD +48 -0
- vieforge-0.4.1.dist-info/WHEEL +4 -0
- vieforge-0.4.1.dist-info/entry_points.txt +7 -0
- vieforge-0.4.1.dist-info/licenses/LICENSE +21 -0
core/__init__.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""TierForge core orchestration modules (100% Python stdlib, MIT clean-room).
|
|
2
|
+
|
|
3
|
+
Uses PEP 562 lazy attribute loading (`__getattr__`) so CLI startup stays fast and
|
|
4
|
+
running `python -m core.<submodule>` emits zero `runpy` RuntimeWarnings.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import importlib
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
__version__ = "0.4.1"
|
|
13
|
+
|
|
14
|
+
_EXPORTS: dict[str, tuple[str, str]] = {
|
|
15
|
+
"BrowserCandidate": ("core.cdp_bridge", "BrowserCandidate"),
|
|
16
|
+
"CDPEndpoint": ("core.cdp_bridge", "CDPEndpoint"),
|
|
17
|
+
"ThreeTierRouter": ("core.cdp_bridge", "ThreeTierRouter"),
|
|
18
|
+
"detect_installed_browsers": ("core.cdp_bridge", "detect_installed_browsers"),
|
|
19
|
+
"discover_cdp_endpoints": ("core.cdp_bridge", "discover_cdp_endpoints"),
|
|
20
|
+
"find_free_port": ("core.cdp_bridge", "find_free_port"),
|
|
21
|
+
"get_default_profile_dir": ("core.cdp_bridge", "get_default_profile_dir"),
|
|
22
|
+
"launch_managed_browser": ("core.cdp_bridge", "launch_managed_browser"),
|
|
23
|
+
"resolve_cdp_url": ("core.cdp_bridge", "resolve_cdp_url"),
|
|
24
|
+
"CrossProcessLock": ("core.concurrency", "CrossProcessLock"),
|
|
25
|
+
"OllamaLeaseManager": ("core.concurrency", "OllamaLeaseManager"),
|
|
26
|
+
"atomic_write_json": ("core.concurrency", "atomic_write_json"),
|
|
27
|
+
"exclusive_gpu_lock": ("core.concurrency", "exclusive_gpu_lock"),
|
|
28
|
+
"BudgetExceededError": ("core.cost_tracker", "BudgetExceededError"),
|
|
29
|
+
"CostEvent": ("core.cost_tracker", "CostEvent"),
|
|
30
|
+
"CostTracker": ("core.cost_tracker", "CostTracker"),
|
|
31
|
+
"DryRunEstimate": ("core.cost_tracker", "DryRunEstimate"),
|
|
32
|
+
"SavingsReceipt": ("core.cost_tracker", "SavingsReceipt"),
|
|
33
|
+
"compute_provider_cost_usd": ("core.cost_tracker", "compute_provider_cost_usd"),
|
|
34
|
+
"load_budget_limits": ("core.cost_tracker", "load_budget_limits"),
|
|
35
|
+
"load_pricing": ("core.cost_tracker", "load_pricing"),
|
|
36
|
+
"BridgeJob": ("core.extension_bridge", "BridgeJob"),
|
|
37
|
+
"ConnectedBrowser": ("core.extension_bridge", "ConnectedBrowser"),
|
|
38
|
+
"ExtensionBridgeClient": ("core.extension_bridge", "ExtensionBridgeClient"),
|
|
39
|
+
"ExtensionBridgeServer": ("core.extension_bridge", "ExtensionBridgeServer"),
|
|
40
|
+
"load_or_create_bridge_token": ("core.extension_bridge", "load_or_create_bridge_token"),
|
|
41
|
+
"LicenseAuditReport": ("core.license_audit", "LicenseAuditReport"),
|
|
42
|
+
"LicenseFinding": ("core.license_audit", "LicenseFinding"),
|
|
43
|
+
"run_license_audit": ("core.license_audit", "run_license_audit"),
|
|
44
|
+
"LLMResponse": ("core.llm_router", "LLMResponse"),
|
|
45
|
+
"LLMRouter": ("core.llm_router", "LLMRouter"),
|
|
46
|
+
"TrimResult": ("core.output_trimmer", "TrimResult"),
|
|
47
|
+
"compact_job_summary": ("core.output_trimmer", "compact_job_summary"),
|
|
48
|
+
"redact_secrets_text": ("core.output_trimmer", "redact_secrets_text"),
|
|
49
|
+
"trim_output": ("core.output_trimmer", "trim_output"),
|
|
50
|
+
"default_data_dir": ("core.paths", "default_data_dir"),
|
|
51
|
+
"is_source_checkout": ("core.paths", "is_source_checkout"),
|
|
52
|
+
"resolve_asset": ("core.paths", "resolve_asset"),
|
|
53
|
+
"GateBlockedError": ("core.pipeline_runner", "GateBlockedError"),
|
|
54
|
+
"GateStatus": ("core.pipeline_runner", "GateStatus"),
|
|
55
|
+
"JobWorkspace": ("core.pipeline_runner", "JobWorkspace"),
|
|
56
|
+
"assert_gate_approved": ("core.pipeline_runner", "assert_gate_approved"),
|
|
57
|
+
"check_retry_cap": ("core.pipeline_runner", "check_retry_cap"),
|
|
58
|
+
"run_profiled_stage": ("core.pipeline_runner", "run_profiled_stage"),
|
|
59
|
+
"QALogger": ("core.qa_logger", "QALogger"),
|
|
60
|
+
"load_qa_codes": ("core.qa_logger", "load_qa_codes"),
|
|
61
|
+
"ItemRecord": ("core.state_db", "ItemRecord"),
|
|
62
|
+
"StateDB": ("core.state_db", "StateDB"),
|
|
63
|
+
"compute_input_hash": ("core.state_db", "compute_input_hash"),
|
|
64
|
+
"scoped_job_id": ("core.state_db", "scoped_job_id"),
|
|
65
|
+
"StepAuditFinding": ("core.step_auditor", "StepAuditFinding"),
|
|
66
|
+
"StepTelemetry": ("core.step_auditor", "StepTelemetry"),
|
|
67
|
+
"export_step_3judge_audit": ("core.step_auditor", "export_step_3judge_audit"),
|
|
68
|
+
"run_step_telemetry": ("core.step_auditor", "run_step_telemetry"),
|
|
69
|
+
"SubprocessResult": ("core.subprocess_runner", "SubprocessResult"),
|
|
70
|
+
"VRAMInsufficientError": ("core.subprocess_runner", "VRAMInsufficientError"),
|
|
71
|
+
"run_isolated": ("core.subprocess_runner", "run_isolated"),
|
|
72
|
+
"GPUStatus": ("core.vram_manager", "GPUStatus"),
|
|
73
|
+
"VRAMPhaseRecord": ("core.vram_manager", "VRAMPhaseRecord"),
|
|
74
|
+
"flush": ("core.vram_manager", "flush"),
|
|
75
|
+
"free_comfyui_vram": ("core.vram_manager", "free_comfyui_vram"),
|
|
76
|
+
"free_http_gpu_server": ("core.vram_manager", "free_http_gpu_server"),
|
|
77
|
+
"query_gpu_status": ("core.vram_manager", "query_gpu_status"),
|
|
78
|
+
"recommend_local_model": ("core.vram_manager", "recommend_local_model"),
|
|
79
|
+
"unload_ollama_model": ("core.vram_manager", "unload_ollama_model"),
|
|
80
|
+
"vram_phase_profiler": ("core.vram_manager", "vram_phase_profiler"),
|
|
81
|
+
"wait_for_free_vram": ("core.vram_manager", "wait_for_free_vram"),
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
__all__ = ["__version__", *_EXPORTS.keys()]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def __getattr__(name: str) -> Any:
|
|
88
|
+
target = _EXPORTS.get(name)
|
|
89
|
+
if target is None:
|
|
90
|
+
raise AttributeError(f"module 'core' has no attribute {name!r}")
|
|
91
|
+
mod_name, attr_name = target
|
|
92
|
+
mod = importlib.import_module(mod_name)
|
|
93
|
+
val = getattr(mod, attr_name)
|
|
94
|
+
globals()[name] = val
|
|
95
|
+
return val
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def __dir__() -> list[str]:
|
|
99
|
+
return sorted(set(globals().keys()) | set(__all__))
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# AGENTS.md — TierForge Harness Instructions
|
|
2
|
+
|
|
3
|
+
This repository implements **TierForge** (*Code First, Local LLM Second, Cloud Last*): a 3-Tier Hybrid AI Agent Harness designed to cut Cloud Agent token burn and API spend by 70–90%.
|
|
4
|
+
|
|
5
|
+
## Operating Rules for AI Agents (Antigravity, Claude Code, Cursor, Windsurf, Codex CLI)
|
|
6
|
+
|
|
7
|
+
1. **Delegate Bulk Work Off Cloud Context:**
|
|
8
|
+
- **Tier 1 (You / Cloud Brain):** Architecture, code edits, reviews, Approval Gates, root-cause debugging.
|
|
9
|
+
- **Tier 2 (Local Backbone — `$0`):** Deterministic Python + SQLite checkpoints (`core/state_db.py`) + Ollama local LLM (`core/llm_router.py`).
|
|
10
|
+
- **Tier 3 (Isolated Muscle):** Heavy local GPU jobs in child subprocesses (`core/subprocess_runner.py`, `exclusive_gpu=True`) and paid external APIs guarded by `--dry-run`, `MAX_RETRY_PER_ITEM <= 2`, `MAX_JOB_USD`, and `DAILY_USD_CAP` (`core/cost_tracker.py`).
|
|
11
|
+
2. **Multi-Project Concurrency Safety:**
|
|
12
|
+
- When running multiple workspaces concurrently on one machine, pass `project_id` to `tool_run_local_batch` / `scoped_job_id()`, use `LLMRouter.batch_session()` (ref-counted Ollama VRAM lease), and `exclusive_gpu=True` for heavy Tier 3 GPU subprocesses.
|
|
13
|
+
3. **Non-Negotiable Guardrails:**
|
|
14
|
+
- **Zero OS-Mutation:** Never edit OS services, Windows Registry, network stacks, or pagefiles.
|
|
15
|
+
- **Clean-Room MIT Licensing:** `core/` stays 100% Python stdlib. Never embed `BUSL-1.1` (`rtk-engine`), `AGPL-3.0`, or `CC-BY-NC`.
|
|
16
|
+
- **Verify Before Reporting Done:** Run `uv run --extra dev pytest -v` and `uv run python scripts/audit_step.py --step <name>`.
|
|
17
|
+
4. **If a Beginner User Asks You to Install TierForge:**
|
|
18
|
+
- Read and follow [AGENT_INSTALL.md](AGENT_INSTALL.md) directly — run `python scripts/quick_setup.py` and explain the result in plain language.
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"_comment": "Example pricing table for --dry-run estimation. Override or copy to config/pricing.json with your provider's current rates. All values in USD.",
|
|
3
|
+
"currency": "USD",
|
|
4
|
+
"updated_at": "2026-01-01",
|
|
5
|
+
"models": {
|
|
6
|
+
"ollama/qwen2.5:7b": {
|
|
7
|
+
"tier": 2,
|
|
8
|
+
"billing_unit": "1m_tokens",
|
|
9
|
+
"input_usd_per_1m": 0.0,
|
|
10
|
+
"output_usd_per_1m": 0.0
|
|
11
|
+
},
|
|
12
|
+
"ollama/llama3.2:3b": {
|
|
13
|
+
"tier": 2,
|
|
14
|
+
"billing_unit": "1m_tokens",
|
|
15
|
+
"input_usd_per_1m": 0.0,
|
|
16
|
+
"output_usd_per_1m": 0.0
|
|
17
|
+
},
|
|
18
|
+
"local/gpu-subprocess": {
|
|
19
|
+
"tier": 3,
|
|
20
|
+
"billing_unit": "item",
|
|
21
|
+
"usd_per_item": 0.0
|
|
22
|
+
},
|
|
23
|
+
"external/text-small": {
|
|
24
|
+
"tier": 3,
|
|
25
|
+
"billing_unit": "1m_tokens",
|
|
26
|
+
"input_usd_per_1m": 0.15,
|
|
27
|
+
"output_usd_per_1m": 0.60
|
|
28
|
+
},
|
|
29
|
+
"external/text-frontier": {
|
|
30
|
+
"tier": 3,
|
|
31
|
+
"billing_unit": "1m_tokens",
|
|
32
|
+
"input_usd_per_1m": 3.00,
|
|
33
|
+
"output_usd_per_1m": 15.00
|
|
34
|
+
},
|
|
35
|
+
"external/media-render-unit": {
|
|
36
|
+
"tier": 3,
|
|
37
|
+
"billing_unit": "item",
|
|
38
|
+
"usd_per_item": 0.08
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": "1.0",
|
|
3
|
+
"codes": {
|
|
4
|
+
"OK": {
|
|
5
|
+
"key": "y",
|
|
6
|
+
"severity": "info",
|
|
7
|
+
"description": "Output passed quality gate."
|
|
8
|
+
},
|
|
9
|
+
"SCHEMA_INVALID": {
|
|
10
|
+
"key": "s",
|
|
11
|
+
"severity": "error",
|
|
12
|
+
"description": "Output failed JSON/schema validation."
|
|
13
|
+
},
|
|
14
|
+
"HALLUCINATION": {
|
|
15
|
+
"key": "h",
|
|
16
|
+
"severity": "error",
|
|
17
|
+
"description": "Output introduced unsupported facts or deviated from source."
|
|
18
|
+
},
|
|
19
|
+
"TRUNCATED": {
|
|
20
|
+
"key": "t",
|
|
21
|
+
"severity": "warning",
|
|
22
|
+
"description": "Output was cut off or incomplete."
|
|
23
|
+
},
|
|
24
|
+
"FORMAT_DRIFT": {
|
|
25
|
+
"key": "f",
|
|
26
|
+
"severity": "warning",
|
|
27
|
+
"description": "Output violated requested formatting or style constraints."
|
|
28
|
+
},
|
|
29
|
+
"RETRY_EXHAUSTED": {
|
|
30
|
+
"key": "r",
|
|
31
|
+
"severity": "error",
|
|
32
|
+
"description": "Item reached MAX_RETRY_PER_ITEM without passing."
|
|
33
|
+
},
|
|
34
|
+
"BUDGET_BLOCKED": {
|
|
35
|
+
"key": "b",
|
|
36
|
+
"severity": "error",
|
|
37
|
+
"description": "Execution halted by job or daily USD cap."
|
|
38
|
+
},
|
|
39
|
+
"VRAM_INSUFFICIENT": {
|
|
40
|
+
"key": "v",
|
|
41
|
+
"severity": "error",
|
|
42
|
+
"description": "Pre-flight GPU free VRAM check below threshold."
|
|
43
|
+
},
|
|
44
|
+
"REJECT_OTHER": {
|
|
45
|
+
"key": "x",
|
|
46
|
+
"severity": "error",
|
|
47
|
+
"description": "Rejected for another reason (add optional note)."
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Example 01: 5-Minute $0 Batch Document Processor (Dry-Run + Interrupt/Resume + Savings Receipt).
|
|
3
|
+
|
|
4
|
+
Demonstrates TierForge's core value proposition in 3 commands:
|
|
5
|
+
1. Dry-run cost preview:
|
|
6
|
+
python examples/01_batch_doc_processor/run_demo.py --dry-run
|
|
7
|
+
2. Forced mid-run interrupt after 2 items (offline --mock-llm or real Ollama):
|
|
8
|
+
python examples/01_batch_doc_processor/run_demo.py --mock-llm --simulate-interrupt-after 2
|
|
9
|
+
3. Zero-cost checkpoint resume (skips already-done items, completes the rest):
|
|
10
|
+
python examples/01_batch_doc_processor/run_demo.py --mock-llm
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import json
|
|
17
|
+
import sys
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
REPO_ROOT = Path(__file__).resolve().parent.parent.parent
|
|
21
|
+
if str(REPO_ROOT) not in sys.path:
|
|
22
|
+
sys.path.insert(0, str(REPO_ROOT))
|
|
23
|
+
|
|
24
|
+
from core.cost_tracker import CostTracker
|
|
25
|
+
from core.llm_router import LLMRouter
|
|
26
|
+
from core.output_trimmer import compact_job_summary
|
|
27
|
+
from core.paths import default_data_dir
|
|
28
|
+
from core.state_db import StateDB, compute_input_hash
|
|
29
|
+
from core.vram_manager import recommend_local_model
|
|
30
|
+
|
|
31
|
+
SAMPLE_DOCS = [
|
|
32
|
+
(
|
|
33
|
+
"doc_01_auth",
|
|
34
|
+
"Incident report: OAuth token refresh failed intermittently under 200 RPS due to clock skew of 90s.",
|
|
35
|
+
),
|
|
36
|
+
(
|
|
37
|
+
"doc_02_billing",
|
|
38
|
+
"Customer invoice #8841 disputed duplicate charge of $49.00 caused by missing idempotency key on retry.",
|
|
39
|
+
),
|
|
40
|
+
(
|
|
41
|
+
"doc_03_gpu",
|
|
42
|
+
"Worker OOM on 8GB VRAM card when keeping Ollama resident while spawning local diffusion pipeline.",
|
|
43
|
+
),
|
|
44
|
+
(
|
|
45
|
+
"doc_04_search",
|
|
46
|
+
"Full-text search p99 latency spiked from 45ms to 1.8s after unindexed JSONB filter was deployed.",
|
|
47
|
+
),
|
|
48
|
+
(
|
|
49
|
+
"doc_05_release",
|
|
50
|
+
"Release v2.4.0 checklist passed unit tests, license audit, and zero-downtime migration verification.",
|
|
51
|
+
),
|
|
52
|
+
]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _mock_extractor(prompt: str, _system: str) -> str:
|
|
56
|
+
body = prompt.splitlines()[-1].strip() if "\n" in prompt else prompt.strip()
|
|
57
|
+
first_word = body.split(":")[0].strip() if ":" in body else "General"
|
|
58
|
+
return json.dumps(
|
|
59
|
+
{
|
|
60
|
+
"category": first_word[:32],
|
|
61
|
+
"severity": "high" if any(w in body.lower() for w in ("oom", "failed", "disputed")) else "normal",
|
|
62
|
+
"summary": body[:90],
|
|
63
|
+
}
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def main() -> int:
|
|
68
|
+
parser = argparse.ArgumentParser(description="TierForge 5-Minute $0 Batch Document Processor Demo.")
|
|
69
|
+
parser.add_argument("--job-id", default="demo_01_batch", help="Job ID for SQLite checkpointing.")
|
|
70
|
+
parser.add_argument("--db", default="data/demo_01_state.db", help="SQLite checkpoint path.")
|
|
71
|
+
parser.add_argument("--model", default=None, help="Ollama model override (default: hardware-recommended).")
|
|
72
|
+
parser.add_argument("--dry-run", action="store_true", help="Print cost estimate vs. Cloud baseline and exit.")
|
|
73
|
+
parser.add_argument("--mock-llm", action="store_true", help="Run with offline mock LLM (no Ollama required).")
|
|
74
|
+
parser.add_argument(
|
|
75
|
+
"--simulate-interrupt-after",
|
|
76
|
+
type=int,
|
|
77
|
+
default=0,
|
|
78
|
+
help="Simulate a forced crash/interrupt after N items to demonstrate $0 checkpoint resume.",
|
|
79
|
+
)
|
|
80
|
+
parser.add_argument("--reset", action="store_true", help="Delete existing demo SQLite DB before running.")
|
|
81
|
+
args = parser.parse_args()
|
|
82
|
+
|
|
83
|
+
data_dir = default_data_dir()
|
|
84
|
+
db_path = (data_dir / "demo_01_state.db") if args.db == "data/demo_01_state.db" else Path(args.db).expanduser()
|
|
85
|
+
if args.reset and db_path.exists():
|
|
86
|
+
db_path.unlink()
|
|
87
|
+
|
|
88
|
+
rec_hw = recommend_local_model()
|
|
89
|
+
model_name = args.model or rec_hw["model"]
|
|
90
|
+
tracker = CostTracker(job_id=args.job_id, daily_spend_path=data_dir / "demo_daily_spend.json")
|
|
91
|
+
|
|
92
|
+
if args.dry_run:
|
|
93
|
+
local_est = tracker.estimate_dry_run(
|
|
94
|
+
provider="ollama/qwen2.5:7b",
|
|
95
|
+
item_count=len(SAMPLE_DOCS),
|
|
96
|
+
avg_input_tokens=1200,
|
|
97
|
+
avg_output_tokens=300,
|
|
98
|
+
)
|
|
99
|
+
cloud_est = tracker.estimate_dry_run(
|
|
100
|
+
provider="external/text-frontier",
|
|
101
|
+
item_count=len(SAMPLE_DOCS),
|
|
102
|
+
avg_input_tokens=1200,
|
|
103
|
+
avg_output_tokens=300,
|
|
104
|
+
)
|
|
105
|
+
print("=== TierForge --dry-run Cost Comparison ===")
|
|
106
|
+
print(f"Hardware profile : {rec_hw['profile']} -> recommended local model: {model_name}")
|
|
107
|
+
print(f"Items to process : {len(SAMPLE_DOCS)}")
|
|
108
|
+
print(f"Tier 2 Local LLM : ${local_est.estimated_base_usd:.4f} USD (within_budget={local_est.within_budget})")
|
|
109
|
+
print(f"Cloud Frontier : ${cloud_est.estimated_base_usd:.4f} USD (worst-case w/ retries: ${cloud_est.estimated_worst_case_usd:.4f})")
|
|
110
|
+
print(f"Approval required : {local_est.requires_approval}")
|
|
111
|
+
return 0
|
|
112
|
+
|
|
113
|
+
router = LLMRouter(
|
|
114
|
+
model=model_name,
|
|
115
|
+
mock=args.mock_llm,
|
|
116
|
+
mock_handler=_mock_extractor if args.mock_llm else None,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
doc_map = dict(SAMPLE_DOCS)
|
|
120
|
+
reg_pairs = [(doc_id, compute_input_hash(text)) for doc_id, text in SAMPLE_DOCS]
|
|
121
|
+
|
|
122
|
+
interrupted = False
|
|
123
|
+
processed_now = 0
|
|
124
|
+
raw_verbose_chars = 0
|
|
125
|
+
|
|
126
|
+
with StateDB(db_path) as db:
|
|
127
|
+
counts = db.register_items(args.job_id, reg_pairs)
|
|
128
|
+
pending = db.get_pending_items(args.job_id, max_retries=tracker.max_retry_per_item)
|
|
129
|
+
print(
|
|
130
|
+
f"[Start] job={args.job_id} total={len(SAMPLE_DOCS)} "
|
|
131
|
+
f"already_done={counts['done']} pending={len(pending)} "
|
|
132
|
+
f"mode={'mock-llm' if args.mock_llm else f'ollama/{model_name}'}"
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
if pending:
|
|
136
|
+
with router.batch_session(keep_alive="2m", unload_on_exit=True):
|
|
137
|
+
for rec in pending:
|
|
138
|
+
text = doc_map[rec.item_id]
|
|
139
|
+
resp = router.generate_json(
|
|
140
|
+
f"Extract JSON with keys category, severity, summary from:\n{text}",
|
|
141
|
+
system="Return strictly valid JSON.",
|
|
142
|
+
required_keys=["category", "severity", "summary"],
|
|
143
|
+
max_retries=2,
|
|
144
|
+
)
|
|
145
|
+
db.mark_done(args.job_id, rec.item_id, output=resp.parsed_json, cost_usd=0.0)
|
|
146
|
+
tracker.record("extract", f"ollama/{model_name}", 0.0, item_id=rec.item_id)
|
|
147
|
+
raw_verbose_chars += len(text) + len(resp.text) + 450
|
|
148
|
+
processed_now += 1
|
|
149
|
+
print(f" [DONE] {rec.item_id} (attempts={resp.attempts}) -> {resp.parsed_json}")
|
|
150
|
+
|
|
151
|
+
if args.simulate_interrupt_after and processed_now >= args.simulate_interrupt_after:
|
|
152
|
+
print(
|
|
153
|
+
f"\n[INTERRUPTED] Simulated crash after {processed_now} items! "
|
|
154
|
+
f"Re-run the same command to resume at $0 extra cost."
|
|
155
|
+
)
|
|
156
|
+
interrupted = True
|
|
157
|
+
break
|
|
158
|
+
|
|
159
|
+
summary = db.get_job_summary(args.job_id)
|
|
160
|
+
|
|
161
|
+
compact = compact_job_summary(summary)
|
|
162
|
+
print(f"\n[SQLite Checkpoint Summary] {compact}")
|
|
163
|
+
if not interrupted:
|
|
164
|
+
receipt = tracker.build_savings_receipt(
|
|
165
|
+
items_processed=summary["done"],
|
|
166
|
+
cloud_baseline_provider="external/text-frontier",
|
|
167
|
+
avg_input_tokens=1200,
|
|
168
|
+
avg_output_tokens=300,
|
|
169
|
+
raw_log_chars=max(raw_verbose_chars, len(compact) * 4),
|
|
170
|
+
trimmed_log_chars=len(compact),
|
|
171
|
+
)
|
|
172
|
+
print("\n" + receipt.format_summary())
|
|
173
|
+
return 130 if interrupted else 0
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
if __name__ == "__main__":
|
|
177
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# TierForge AI Bridge Extension (Manifest V3)
|
|
2
|
+
|
|
3
|
+
Optional **Layer-3 (Zero-CDP)** localhost bridge connecting your already-open browser (**Chrome, Edge, Brave, Opera, Vivaldi, Coc Coc, Firefox**) to your local `tierforge-harness` (`127.0.0.1:19876`):
|
|
4
|
+
|
|
5
|
+
- No `--remote-debugging-port` flags required (compatible with Chrome 136+ security restrictions).
|
|
6
|
+
- Zero cloud servers, zero analytics, zero third-party telemetry, 100% unminified auditable JS.
|
|
7
|
+
- Strictly scoped to `127.0.0.1:19876` and the 4 supported AI web apps only — includes TOFU Origin Pinning and a 1-click **Pause Bridge** kill switch.
|
|
8
|
+
- **Compliance Note:** Intended for personal BYOA (Bring Your Own Account) productivity only. See [LEGAL_AND_COMPLIANCE.md](../../LEGAL_AND_COMPLIANCE.md) and [SECURITY.md](SECURITY.md).
|
|
9
|
+
|
|
10
|
+
## Quick Install (30 Seconds)
|
|
11
|
+
|
|
12
|
+
### Chrome / Edge / Brave / Opera / Coc Coc
|
|
13
|
+
1. Open the extensions page (`chrome://extensions`, `edge://extensions`, or `brave://extensions`).
|
|
14
|
+
2. Enable **Developer mode**.
|
|
15
|
+
3. Click **Load unpacked** and select this folder (`extensions/tierforge-bridge`).
|
|
16
|
+
|
|
17
|
+
### Firefox (115+)
|
|
18
|
+
1. Open `about:debugging#/runtime/this-firefox`.
|
|
19
|
+
2. Click **Load Temporary Add-on…** and select `manifest.json` in this folder.
|
|
20
|
+
|
|
21
|
+
## Start Local Bridge (Zero Copy-Paste Pairing)
|
|
22
|
+
Run once from the repository root (or double-click `scripts/start_tierforge_bridge.bat` on Windows):
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
python scripts/extension_bridge_server.py serve
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
The extension automatically pairs over localhost (`POST /extension/pair`) within 2 seconds and shows **Connected (Auto-Paired)** in the popup.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# TierForge AI Bridge — Security & Privacy Architecture (Glass-Box Trust)
|
|
2
|
+
|
|
3
|
+
1. **Zero Cloud Telemetry:** 100% traffic stays strictly inside your machine (`127.0.0.1:19876`). Zero bytes are ever sent to any third-party server.
|
|
4
|
+
2. **Least-Privilege Permissions:**
|
|
5
|
+
- NEVER requests `<all_urls>`, `cookies`, `history`, or `webRequest`.
|
|
6
|
+
- Restricted strictly to 1 localhost port (`http://127.0.0.1:19876/*`) and 4 AI web apps (`gemini.google.com`, `chatgpt.com`, `claude.ai`, `labs.google`).
|
|
7
|
+
- Cannot read banking, email, social media, or any non-AI tab.
|
|
8
|
+
3. **TOFU (Trust-On-First-Use) Origin Pinning:**
|
|
9
|
+
- Auto-pairing (`POST /extension/pair`) accepts ONLY browser extension origins (`chrome-extension://` / `moz-extension://`) and permanently pins the first paired Extension ID.
|
|
10
|
+
- Any website or second unknown extension attempting to pair is hard-blocked with `HTTP 403`.
|
|
11
|
+
4. **Visible Execution & Instant Kill Switch:**
|
|
12
|
+
- Icon badge switches to orange `RUN` whenever a prompt is actively executing.
|
|
13
|
+
- Popup displays the last 10 local jobs (`time • service • chars • status`) and provides a 1-click red **Pause Bridge** kill switch.
|
|
14
|
+
5. **100% Readable Unminified Source:** All JS files (`background.js`, `content_bridge.js`, `popup.js`) are plain, unminified JavaScript (~200 lines total) so any user or security auditor can inspect every line in under 1 minute.
|