Spaces:
Running
Running
Download app.js from ql6/BeamBridge: direct link, hf CLI and curl.
- Browser
- Download file 52.8 kB
-
https://huggingface.co/spaces/ql6/BeamBridge/resolve/main/app.js
- Command line
-
hf download hf://spaces/ql6/BeamBridge/app.js
-
curl -L -o app.js https://huggingface.co/spaces/ql6/BeamBridge/resolve/main/app.js
52.8 kB
| /* ========================================================================== | |
| BeamBridge v2 Frontend Controller (Concise · Zero Emojis · Cohesive Palette) | |
| ========================================================================== */ | |
| function safeStorageGet(k, fallback) { | |
| try { | |
| return window.sessionStorage.getItem(k) || fallback; | |
| } catch { | |
| return fallback; | |
| } | |
| } | |
| function safeStorageSet(k, v) { | |
| try { | |
| window.sessionStorage.setItem(k, v); | |
| } catch { | |
| /* sandboxed iframe fallback */ | |
| } | |
| } | |
| const STATE = { | |
| lang: "en", | |
| activeView: "dashboard", | |
| selectedRepoId: "py_moneyed", | |
| bootstrap: null, | |
| repoBundles: {}, | |
| allParityCases: [], | |
| provider: safeStorageGet("bb_provider", "openrouter"), | |
| apiKey: safeStorageGet("bb_api_key", ""), | |
| }; | |
| const I18N = { | |
| en: { | |
| nav_dashboard: "Dashboard", | |
| nav_modernizer: "Modernizer", | |
| nav_playground: "MCP Playground", | |
| nav_parity: "Parity Suite", | |
| nav_finops: "FinOps", | |
| btn_engine: "Engine", | |
| btn_connect_mcp: "Setup & /mcp", | |
| hero_title: "Beam-1.0 Modernization Hub", | |
| cap_parity: "Parity", | |
| cap_tokens: "Cost Saved", | |
| cap_naive_drift: "RAG Drift", | |
| cap_regressions: "Regressions", | |
| kpi_tests: "Verified Tests", | |
| kpi_tools: "MCP Tools", | |
| kpi_savings: "TCO Saved", | |
| card_pipeline: "Pipeline", | |
| card_estates: "GitHub Repositories", | |
| card_matrix: "Parity Matrix", | |
| card_finops_curve: "Inference Spend", | |
| card_composition: "Cost Ratio", | |
| guide_s1_title: "Paste a setup prompt into your AI", | |
| guide_s1_desc: "Select your AI client and copy its prompt to connect BeamBridge's verified /mcp gateway.", | |
| guide_paste_lbl: "You'll paste this", | |
| guide_s2_title: "Verify SHA-256 parity", | |
| guide_s2_desc: "Every tool passes 160/160 differential checks against its original GitHub library before going live.", | |
| guide_master_lbl: "Master SHA-256:", | |
| guide_s3_title: "Modernize or inspect live", | |
| guide_s3_desc: "Clone any public GitHub repo in Modernizer Studio or compare outputs side-by-side in the Playground.", | |
| guide_s4_title: "Run a verified task", | |
| guide_s4_desc: "Click an example to copy it and test it live in the Playground.", | |
| }, | |
| ar: { | |
| nav_dashboard: "الرئيسية", | |
| nav_modernizer: "المحوّل", | |
| nav_playground: "مختبر MCP", | |
| nav_parity: "الفحوصات", | |
| nav_finops: "التكلفة", | |
| btn_engine: "المحرك", | |
| btn_connect_mcp: "الربط و /mcp", | |
| hero_title: "منصة تحديث الأنظمة بـ Beam-1.0", | |
| cap_parity: "التطابق", | |
| cap_tokens: "وفر التكلفة", | |
| cap_naive_drift: "أخطاء RAG", | |
| cap_regressions: "تراجعات", | |
| kpi_tests: "اختبار موثق", | |
| kpi_tools: "أداة MCP", | |
| kpi_savings: "وفر سنوي", | |
| card_pipeline: "مراحل التحويل", | |
| card_estates: "مستودعات GitHub", | |
| card_matrix: "مصفوفة التطابق", | |
| card_finops_curve: "تكلفة الاستدلال", | |
| card_composition: "نسبة التوفير", | |
| guide_s1_title: "الصق أمر الربط في وكيلك الذكي", | |
| guide_s1_desc: "اختر المنصة وانسخ الأمر الجاهز لربط بوابة /mcp الموثقة.", | |
| guide_paste_lbl: "النص الجاهز للنسخ", | |
| guide_s2_title: "شهادات التطابق SHA-256", | |
| guide_s2_desc: "جميع الأدوات تجتاز 160/160 فحصاً تفاضلياً ضد مكتبات GitHub الأصلية.", | |
| guide_master_lbl: "البصمة الرئيسية:", | |
| guide_s3_title: "حدّث مستودعك أو اختبره مباشرة", | |
| guide_s3_desc: "استنسخ أي مستودع عام في المحوّل أو قارن المخرجات مباشرة في المختبر.", | |
| guide_s4_title: "جرّب عملية موثقة", | |
| guide_s4_desc: "اضغط على أي مثال لنسخه وتشغيله فوراً في المختبر.", | |
| }, | |
| }; | |
| const REPO_CODES = { | |
| py_moneyed: "MN", | |
| price_parser: "PR", | |
| schwifty: "SW", | |
| python_stdnum: "ST", | |
| }; | |
| const REAL_EDGE_PRESETS = { | |
| py_moneyed: { | |
| inspect_and_round_money: [ | |
| { label: "USD Whole Round", args: { amount_str: "19.50", currency_code: "USD", ndigits: null } }, | |
| { label: "BHD 3-Decimal", args: { amount_str: "45.6785", currency_code: "BHD", ndigits: 3 } }, | |
| { label: "JPY 0-Decimal", args: { amount_str: "1500.9", currency_code: "JPY", ndigits: 0 } }, | |
| ], | |
| pro_rata_subunit_split: [ | |
| { label: "$100 [1,1,1] Split", args: { amount_str: "100.00", currency_code: "USD", weights: [1, 1, 1] } }, | |
| { label: "KWD 50 [5,3,2]", args: { amount_str: "50.000", currency_code: "KWD", weights: [5, 3, 2] } }, | |
| ], | |
| convert_and_sum_ledger: [ | |
| { | |
| label: "USD + EUR → SAR", | |
| args: { | |
| entries: [{ amount: "100.00", currency: "USD" }, { amount: "250.00", currency: "EUR" }], | |
| target_currency: "SAR", | |
| rates_to_target: { USD: "3.75", EUR: "4.0625" }, | |
| }, | |
| }, | |
| ], | |
| }, | |
| price_parser: { | |
| parse_procurement_price: [ | |
| { label: "EU 1.299,95 €", args: { raw_text: "Total: 1.299,95 € (incl. VAT)", currency_hint: null, decimal_separator: null } }, | |
| { label: "CHF 1'250.50", args: { raw_text: "CHF 1'250.50", currency_hint: null, decimal_separator: null } }, | |
| { label: "Zero ('Free!')", args: { raw_text: "Free!", currency_hint: "USD", decimal_separator: null } }, | |
| ], | |
| compute_invoice_line_quote: [ | |
| { label: "4× CHF 1'250.50 − 200", args: { raw_unit_price: "CHF 1'250.50", quantity: 4, raw_discount: "CHF 200.00" } }, | |
| ], | |
| audit_price_feed_batch: [ | |
| { label: "Mixed Feed", args: { raw_items: ["$19.99", "€ 30,01", "Free!", "Contact sales"] } }, | |
| ], | |
| }, | |
| schwifty: { | |
| validate_and_decompose_iban: [ | |
| { label: "UK NatWest IBAN", args: { raw_iban: "GB29 NWBK 6016 1331 9268 19" } }, | |
| { label: "FR BNP IBAN", args: { raw_iban: "FR76 3000 6000 0112 3456 7890 189" } }, | |
| { label: "Invalid Checksum", args: { raw_iban: "GB99 NWBK 6016 1331 9268 19" } }, | |
| ], | |
| generate_iban_from_bban: [ | |
| { label: "DE BBAN → IBAN", args: { country_code: "DE", bank_code: "37040044", account_code: "0532013000" } }, | |
| ], | |
| inspect_swift_bic: [ | |
| { label: "DEUTDEFF500", args: { raw_bic: "DEUTDEFF500" } }, | |
| { label: "Invalid Country", args: { raw_bic: "DEUTXXFF" } }, | |
| ], | |
| }, | |
| python_stdnum: { | |
| validate_securities_id: [ | |
| { label: "ISIN US0378331005", args: { scheme: "ISIN", raw_code: "US0378331005" } }, | |
| { label: "SEDOL 0263494", args: { scheme: "SEDOL", raw_code: "0263494" } }, | |
| { label: "FIGI BBG000BLNNH6", args: { scheme: "FIGI", raw_code: "BBG000BLNNH6" } }, | |
| ], | |
| validate_us_routing_or_ein: [ | |
| { label: "JPM RTN 021000021", args: { id_type: "RTN", raw_number: "021000021" } }, | |
| { label: "Invalid EIN 07-", args: { id_type: "EIN", raw_number: "07-1234567" } }, | |
| ], | |
| validate_eu_vat_number: [ | |
| { label: "DE136695976", args: { raw_vat: "DE 136 695 976" } }, | |
| { label: "FR40303265045", args: { raw_vat: "FR 40 303 265 045" } }, | |
| ], | |
| }, | |
| }; | |
| function fmtCurrency(num) { | |
| const n = Number(num || 0); | |
| if (n >= 1_000_000) return "$" + (n / 1_000_000).toFixed(2) + "M"; | |
| return "$" + Math.round(n).toLocaleString("en-US"); | |
| } | |
| function fmtUsdExact(num) { | |
| return "$" + Math.round(Number(num || 0)).toLocaleString("en-US"); | |
| } | |
| function escapeHtml(str) { | |
| return String(str ?? "") | |
| .replace(/&/g, "&") | |
| .replace(/</g, "<") | |
| .replace(/>/g, ">"); | |
| } | |
| function switchView(viewId) { | |
| STATE.activeView = viewId; | |
| document.querySelectorAll(".nav-tab").forEach((btn) => { | |
| btn.classList.toggle("active", btn.dataset.view === viewId); | |
| }); | |
| document.querySelectorAll(".view-section").forEach((sec) => { | |
| sec.classList.toggle("active", sec.id === `view-${viewId}`); | |
| }); | |
| } | |
| function applyLanguage() { | |
| const dict = I18N[STATE.lang]; | |
| document.getElementById("appShell").setAttribute("dir", STATE.lang === "ar" ? "rtl" : "ltr"); | |
| document.getElementById("langToggleBtn").textContent = STATE.lang === "ar" ? "EN" : "ع"; | |
| document.querySelectorAll("[data-i18n]").forEach((el) => { | |
| const k = el.getAttribute("data-i18n"); | |
| if (dict[k]) el.textContent = dict[k]; | |
| }); | |
| } | |
| /* ========================================================================== | |
| Dashboard Renderers | |
| ========================================================================== */ | |
| function renderEstatesTable(filterText = "") { | |
| if (!STATE.bootstrap) return; | |
| const tbody = document.getElementById("estatesTableBody"); | |
| const q = filterText.trim().toLowerCase(); | |
| const rows = STATE.bootstrap.repositories.filter( | |
| (r) => | |
| !q || | |
| r.name.toLowerCase().includes(q) || | |
| r.git_sha.toLowerCase().includes(q) || | |
| r.sector.toLowerCase().includes(q) | |
| ); | |
| tbody.innerHTML = rows | |
| .map((r) => { | |
| const isSel = r.id === STATE.selectedRepoId; | |
| const code = REPO_CODES[r.id] || "GH"; | |
| const v = r.verification; | |
| return ` | |
| <tr class="${isSel ? "selected-row" : ""}" data-repoid="${r.id}"> | |
| <td><span class="row-check">•</span></td> | |
| <td> | |
| <div class="estate-name-cell"> | |
| <span class="sector-avatar">${code}</span> | |
| <div> | |
| <div style="font-weight:500;color:var(--ink-900);">${escapeHtml(r.name)} <code style="font-size:11px;color:var(--ink-500);">@${escapeHtml(r.git_sha)}</code></div> | |
| <div style="font-size:11px;color:var(--ink-500);">${r.ast.estimated_beam_tokens.toLocaleString()} BPE tokens</div> | |
| </div> | |
| </div> | |
| </td> | |
| <td style="color:var(--ink-700);font-size:12px;">${escapeHtml(r.sector)}</td> | |
| <td style="font-weight:500;font-size:12.5px;"> | |
| <span style="color:var(--ink-500);">${v.chunked_rag_parity_pct}%</span> → <strong style="color:var(--ink-900);">${v.beam_1m_parity_pct}%</strong> | |
| </td> | |
| <td> | |
| <span class="status-pill grey"> | |
| <span class="dot"></span>${v.beam_1m_passed}/${v.total_cases} | |
| </span> | |
| </td> | |
| </tr> | |
| `; | |
| }) | |
| .join(""); | |
| tbody.querySelectorAll("tr[data-repoid]").forEach((tr) => { | |
| tr.addEventListener("click", async () => { | |
| STATE.selectedRepoId = tr.dataset.repoid; | |
| renderEstatesTable(document.getElementById("estateSearchInput").value); | |
| document.getElementById("modRepoSelect").value = STATE.selectedRepoId; | |
| document.getElementById("pgRepoSelect").value = STATE.selectedRepoId; | |
| document.getElementById("liveGithubBox").style.display = "none"; | |
| await loadRepoBundle(STATE.selectedRepoId); | |
| }); | |
| }); | |
| } | |
| async function renderMatrixDots() { | |
| await ensureAllBundlesLoaded(); | |
| const grid = document.getElementById("matrixDotGrid"); | |
| const hoverBar = document.getElementById("matrixHoverText"); | |
| const cliffs = STATE.allParityCases.filter((c) => !c.chunked_rag_parity); | |
| const normals = STATE.allParityCases.filter((c) => c.chunked_rag_parity); | |
| const sampled = [...cliffs.slice(0, 46), ...normals.slice(0, 26)].slice(0, 72); | |
| grid.innerHTML = sampled | |
| .map((d, idx) => { | |
| const cls = !d.chunked_rag_parity ? "gold-cliff" : idx % 3 === 0 ? "verified-soft" : ""; | |
| return `<div class="matrix-dot ${cls}" data-idx="${idx}" title="${escapeHtml(d.case_id)}: ${escapeHtml(d.label)}"></div>`; | |
| }) | |
| .join(""); | |
| grid.querySelectorAll(".matrix-dot").forEach((dot) => { | |
| const item = sampled[Number(dot.dataset.idx)]; | |
| dot.addEventListener("mouseenter", () => { | |
| const tag = !item.chunked_rag_parity ? "RAG Failed" : "Verified"; | |
| hoverBar.textContent = `${item.case_id} · ${item.label} (${item.mcp_latency_us} μs) — ${tag}`; | |
| }); | |
| dot.addEventListener("click", () => { | |
| document.getElementById("parityRepoFilter").value = item.repo_id; | |
| switchView("parity"); | |
| renderParityTable(); | |
| }); | |
| }); | |
| } | |
| function buildSmoothSvgPath(points) { | |
| if (!points.length) return ""; | |
| let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`; | |
| for (let i = 0; i < points.length - 1; i++) { | |
| const p0 = points[i]; | |
| const p1 = points[i + 1]; | |
| const cx = (p0.x + p1.x) / 2; | |
| d += ` C ${cx.toFixed(1)} ${p0.y.toFixed(1)}, ${cx.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`; | |
| } | |
| return d; | |
| } | |
| function renderFinOpsCurve(finops) { | |
| const container = document.getElementById("finopsChartContainer"); | |
| const months = ["M1", "M2", "M3", "M4", "M5", "M6", "M7", "M8", "M9", "M10", "M11", "M12"]; | |
| const rawSeries = finops.cumulative_monthly_series; | |
| const qwenAnnual = finops.annual_inference_cost_usd.qwen_3_8_2_4t || 42000; | |
| const beamAnnual = finops.annual_inference_cost_usd.beam_1_0_with_ast_pack || 5800; | |
| const series = rawSeries | |
| ? rawSeries.map((r) => ({ | |
| month: r.month, | |
| frontier_usd: r.qwen_cumulative_usd, | |
| beam_usd: r.beam_cumulative_usd, | |
| })) | |
| : months.map((m, i) => ({ | |
| month: m, | |
| frontier_usd: (qwenAnnual / 12) * (i + 1), | |
| beam_usd: (beamAnnual / 12) * (i + 1), | |
| })); | |
| const W = 580; | |
| const H = 180; | |
| const padL = 46; | |
| const padR = 18; | |
| const padT = 26; | |
| const padB = 30; | |
| const plotW = W - padL - padR; | |
| const plotH = H - padT - padB; | |
| const maxVal = Math.max(...series.map((s) => s.frontier_usd), 100) * 1.16; | |
| const frontPts = series.map((s, i) => ({ | |
| x: padL + (i / (series.length - 1)) * plotW, | |
| y: padT + plotH - (s.frontier_usd / maxVal) * plotH, | |
| })); | |
| const beamPts = series.map((s, i) => ({ | |
| x: padL + (i / (series.length - 1)) * plotW, | |
| y: padT + plotH - (s.beam_usd / maxVal) * plotH, | |
| })); | |
| const hi = 8; | |
| const hiFront = frontPts[hi]; | |
| const hiBeam = beamPts[hi]; | |
| const savedPct = finops.annual_inference_cost_usd.token_cost_reduction_vs_qwen38_pct || 96.8; | |
| const yTicks = [0.25, 0.55, 0.85].map((f) => ({ | |
| y: padT + plotH - f * plotH, | |
| lbl: "$" + ((maxVal * f) / 1000).toFixed(0) + "k", | |
| })); | |
| container.innerHTML = ` | |
| <svg viewBox="0 0 ${W} ${H}" width="100%" height="100%" preserveAspectRatio="none"> | |
| ${yTicks | |
| .map( | |
| (t) => ` | |
| <line x1="${padL}" y1="${t.y.toFixed(1)}" x2="${W - padR}" y2="${t.y.toFixed(1)}" stroke="rgba(36,36,38,0.06)" stroke-width="1"/> | |
| <text x="4" y="${(t.y + 4).toFixed(1)}" fill="#9c9ca1" font-size="10" font-family="inherit">${t.lbl}</text> | |
| ` | |
| ) | |
| .join("")} | |
| <path d="${buildSmoothSvgPath(frontPts)}" fill="none" stroke="#242426" stroke-width="1.8" stroke-dasharray="4 4" /> | |
| <path d="${buildSmoothSvgPath(beamPts)}" fill="none" stroke="#e2ba36" stroke-width="2.4" /> | |
| <line x1="${hiFront.x.toFixed(1)}" y1="${hiFront.y.toFixed(1)}" x2="${hiFront.x.toFixed(1)}" y2="${H - padB}" stroke="#242426" stroke-width="1.2" /> | |
| <circle cx="${hiFront.x.toFixed(1)}" cy="${hiFront.y.toFixed(1)}" r="4" fill="#242426" /> | |
| <circle cx="${hiBeam.x.toFixed(1)}" cy="${hiBeam.y.toFixed(1)}" r="4.5" fill="#f5d665" stroke="#242426" stroke-width="1.3" /> | |
| <g transform="translate(${(hiFront.x - 46).toFixed(1)}, ${Math.max(4, hiFront.y - 30).toFixed(1)})"> | |
| <rect x="0" y="0" width="92" height="24" rx="12" fill="#242426" /> | |
| <text x="46" y="15.5" text-anchor="middle" fill="#ffffff" font-size="10.5" font-weight="500" font-family="inherit">−${savedPct}% Cost</text> | |
| </g> | |
| ${series | |
| .map((s, i) => { | |
| const x = padL + (i / (series.length - 1)) * plotW; | |
| const isPill = s.month === "M9"; | |
| return ` | |
| ${isPill ? `<rect x="${(x - 15).toFixed(1)}" y="${H - 22}" width="30" height="18" rx="9" fill="rgba(255,255,255,0.92)" />` : ""} | |
| <text x="${x.toFixed(1)}" y="${H - 9}" text-anchor="middle" fill="${isPill ? "#222224" : "#8b8b90"}" font-size="10.5" font-weight="${isPill ? "600" : "400"}" font-family="inherit">${s.month}</text> | |
| `; | |
| }) | |
| .join("")} | |
| </svg> | |
| `; | |
| } | |
| /* ========================================================================== | |
| Modernizer Studio & Live GitHub Cloner | |
| ========================================================================== */ | |
| async function loadRepoBundle(repoId) { | |
| if (!STATE.repoBundles[repoId]) { | |
| const resp = await fetch(`/api/repos/${repoId}`); | |
| STATE.repoBundles[repoId] = await resp.json(); | |
| } | |
| const bundle = STATE.repoBundles[repoId]; | |
| renderModernizerOutput(bundle); | |
| populatePlaygroundTools(repoId); | |
| return bundle; | |
| } | |
| function renderModernizerOutput(bundle, liveSynthesis = null) { | |
| const cat = bundle.catalog || {}; | |
| const ast = bundle.ast || {}; | |
| const ver = bundle.verification || {}; | |
| const audit = ver.synthesis_audit || {}; | |
| const packLine = | |
| Number(ast.ast_finops_compression_pct || 0) > 0 | |
| ? `${Number(ast.raw_disk_beam_tokens || 0).toLocaleString()} → <strong>${Number(ast.estimated_beam_tokens || 0).toLocaleString()} BPE tok</strong> (−${ast.ast_finops_compression_pct}%)` | |
| : `<strong>${Number(ast.estimated_beam_tokens || 0).toLocaleString()} BPE tok</strong> (${ast.file_count || 0} files)`; | |
| document.getElementById("modTelemetryBox").innerHTML = ` | |
| <div><strong>Repo:</strong> <a href="${escapeHtml(cat.github_url)}" target="_blank" rel="noreferrer" style="color:var(--ink-900);">${escapeHtml(cat.name)}</a> <code>@${escapeHtml(cat.git_sha)}</code></div> | |
| <div><strong>Tokens:</strong> ${packLine}</div> | |
| <div><strong>Parity:</strong> <strong>${ver.beam_1m_passed}/${ver.total_cases} (${ver.beam_1m_parity_pct}%)</strong> vs RAG ${ver.chunked_rag_parity_pct}%</div> | |
| <div><strong>OpenRouter IDs:</strong> <code>${escapeHtml((audit.whole_repo_request_ids || []).join(", "))}</code></div> | |
| `; | |
| const turnsHtml = (audit.whole_repo_turns || []) | |
| .map( | |
| (t) => ` | |
| <div class="rule-card"> | |
| <div class="rule-card-head"> | |
| <strong style="font-size:12.5px;">Turn ${t.turn} · <code>${escapeHtml(t.model)}</code></strong> | |
| <span class="status-pill ${t.passed === t.total ? "grey" : "amber"}"><span class="dot"></span>${t.passed}/${t.total} (${t.pass_rate_pct}%)</span> | |
| </div> | |
| <div style="font-size:11.5px;color:var(--ink-500);"> | |
| ID: <code>${escapeHtml(t.request_id)}</code> · ${(t.latency_ms / 1000).toFixed(1)}s · ${t.usage.total_tokens.toLocaleString()} tok · $${Number(t.usage.cost_usd || 0).toFixed(5)} | |
| </div> | |
| </div> | |
| ` | |
| ) | |
| .join(""); | |
| const liveBanner = liveSynthesis | |
| ? `<div class="rule-card" style="background:var(--gold-soft);border-color:var(--gold);font-size:12px;"> | |
| <strong>Synthesis (${escapeHtml(liveSynthesis.mode)}):</strong> <code>${escapeHtml(liveSynthesis.model)}</code> · <code>${escapeHtml((liveSynthesis.request_ids || []).join(", "))}</code> · ${liveSynthesis.latency_ms} ms | |
| </div>` | |
| : ""; | |
| const reasoningTxt = (liveSynthesis && liveSynthesis.reasoning_content) || bundle.recorded_reasoning_trace || ""; | |
| document.getElementById("modTabRules").innerHTML = ` | |
| ${liveBanner} | |
| <div class="rule-card" style="background:#242426;color:#fff;border-color:#242426;"> | |
| <div class="rule-card-head"> | |
| <strong style="font-size:12px;color:var(--gold);">Reasoning Trace</strong> | |
| <span style="font-size:11px;color:rgba(255,255,255,0.55);">SHA-256: ${escapeHtml((ver.certificate_sha256 || "").slice(0, 12))}…</span> | |
| </div> | |
| <div style="font-family:var(--font-mono);font-size:11.5px;line-height:1.55;white-space:pre-wrap;color:rgba(255,255,255,0.86);max-height:220px;overflow-y:auto;">${escapeHtml(reasoningTxt)}</div> | |
| </div> | |
| <div style="margin-top:10px;">${turnsHtml}</div> | |
| `; | |
| document.getElementById("modernMcpCodePre").textContent = | |
| (liveSynthesis && liveSynthesis.synthesized_code) || bundle.modernized_mcp_code || ""; | |
| const packedStr = Object.entries(bundle.legacy_files || {}) | |
| .map(([fname, src]) => `/* === ${fname} === */\n${src}`) | |
| .join("\n\n"); | |
| document.getElementById("legacyPackedCodePre").textContent = packedStr; | |
| } | |
| function renderLiveGithubCloneReport(ghReport) { | |
| document.getElementById("modTelemetryBox").innerHTML = ` | |
| <div><strong>Cloned:</strong> <a href="${escapeHtml(ghReport.github_url)}" target="_blank" rel="noreferrer" style="color:var(--ink-900);">${escapeHtml(ghReport.repo)}</a> <code>@${escapeHtml(ghReport.git_sha)}</code></div> | |
| <div><strong>Files:</strong> ${ghReport.files_analyzed} / ${ghReport.total_py_files_discovered} .py</div> | |
| <div><strong>Beam-1.0 Tokens:</strong> <strong>${ghReport.exact_beam_bpe_tokens.toLocaleString()}</strong> (${ghReport.beam_1m_utilization_pct}% of 1M)</div> | |
| <div><strong>Single-Pass Cost:</strong> <strong>$${ghReport.estimated_beam_single_pass_usd}</strong> (${ghReport.finops_cost_advantage_x}x cheaper)</div> | |
| `; | |
| document.getElementById("modTabRules").innerHTML = ` | |
| <div class="rule-card" style="background:var(--gold-soft);border-color:var(--gold);"> | |
| <strong>Cloned ${escapeHtml(ghReport.repo)}@${escapeHtml(ghReport.git_sha)}</strong> — ${ghReport.total_loc.toLocaleString()} LOC · ${ghReport.total_functions} functions · ${ghReport.cross_file_edge_count} cross-file edges. | |
| </div> | |
| ${(ghReport.top_files || []) | |
| .map( | |
| (f) => ` | |
| <div class="rule-card"> | |
| <div class="rule-card-head"> | |
| <strong style="font-size:12px;"><code>${escapeHtml(f.file)}</code></strong> | |
| <span class="status-pill grey">${f.estimated_tokens.toLocaleString()} tok</span> | |
| </div> | |
| <div style="font-size:11.5px;color:var(--ink-500);">${f.loc} LOC · ${f.function_count} functions</div> | |
| </div> | |
| ` | |
| ) | |
| .join("")} | |
| `; | |
| } | |
| /* ========================================================================== | |
| MCP Playground | |
| ========================================================================== */ | |
| function populatePlaygroundTools(repoId) { | |
| const bundle = STATE.repoBundles[repoId]; | |
| if (!bundle) return; | |
| const tools = bundle.catalog.mcp_tools || []; | |
| const toolSelect = document.getElementById("pgToolSelect"); | |
| toolSelect.innerHTML = tools | |
| .map((t) => `<option value="${t.name}">${t.name}</option>`) | |
| .join(""); | |
| if (tools.length) renderPlaygroundForm(repoId, tools[0].name); | |
| } | |
| function renderPlaygroundForm(repoId, toolName, overrideArgs = null) { | |
| const bundle = STATE.repoBundles[repoId]; | |
| if (!bundle) return; | |
| const toolMeta = (bundle.catalog.mcp_tools || []).find((t) => t.name === toolName) || bundle.catalog.mcp_tools[0]; | |
| const sample = overrideArgs || toolMeta.sample_args || {}; | |
| const presets = (REAL_EDGE_PRESETS[repoId] && REAL_EDGE_PRESETS[repoId][toolMeta.name]) || []; | |
| const presetsBar = document.getElementById("pgPresetsBar"); | |
| presetsBar.innerHTML = presets | |
| .map( | |
| (p, idx) => | |
| `<button type="button" class="btn-ghost-pill" style="font-size:11.5px;padding:5px 11px;" data-pidx="${idx}">${escapeHtml(p.label)}</button>` | |
| ) | |
| .join(""); | |
| presetsBar.querySelectorAll("button[data-pidx]").forEach((btn) => { | |
| btn.addEventListener("click", () => { | |
| const chosen = presets[Number(btn.dataset.pidx)]; | |
| renderPlaygroundForm(repoId, toolMeta.name, chosen.args); | |
| invokePlaygroundTool(); | |
| }); | |
| }); | |
| const formBox = document.getElementById("pgDynamicForm"); | |
| formBox.innerHTML = Object.entries(sample) | |
| .map(([key, val]) => { | |
| const isObj = val !== null && typeof val === "object"; | |
| const valType = val === null ? "null_or_str" : typeof val === "number" ? (Number.isInteger(val) ? "integer" : "number") : isObj ? "json" : "string"; | |
| const displayVal = val === null ? "" : isObj ? JSON.stringify(val) : String(val); | |
| return ` | |
| <div class="form-field"> | |
| <label><code>${escapeHtml(key)}</code></label> | |
| <input class="form-input" data-argkey="${escapeHtml(key)}" data-argtype="${valType}" placeholder="null" value="${escapeHtml(displayVal)}" /> | |
| </div> | |
| `; | |
| }) | |
| .join(""); | |
| invokePlaygroundTool(); | |
| } | |
| async function invokePlaygroundTool() { | |
| const repoId = document.getElementById("pgRepoSelect").value; | |
| const toolName = document.getElementById("pgToolSelect").value; | |
| const args = {}; | |
| document.querySelectorAll("#pgDynamicForm [data-argkey]").forEach((el) => { | |
| const k = el.dataset.argkey; | |
| const tp = el.dataset.argtype; | |
| const raw = el.value.trim(); | |
| if (tp === "null_or_str") { | |
| if (!raw) args[k] = null; | |
| else if (/^-?\d+$/.test(raw)) args[k] = parseInt(raw, 10); | |
| else args[k] = raw; | |
| } else if (tp === "integer") { | |
| args[k] = raw === "" ? null : parseInt(raw, 10); | |
| } else if (tp === "number") { | |
| args[k] = raw === "" ? null : parseFloat(raw); | |
| } else if (tp === "json") { | |
| try { | |
| args[k] = JSON.parse(raw); | |
| } catch { | |
| args[k] = raw; | |
| } | |
| } else { | |
| args[k] = el.value; | |
| } | |
| }); | |
| const resp = await fetch("/api/mcp/invoke", { | |
| method: "POST", | |
| headers: { "Content-Type": "application/json" }, | |
| body: JSON.stringify({ repo_id: repoId, tool_name: toolName, arguments: args }), | |
| }); | |
| const data = await resp.json(); | |
| if (!resp.ok) { | |
| document.getElementById("pgLegacyOutPre").textContent = data.detail || "Execution error"; | |
| return; | |
| } | |
| document.getElementById("pgLegacyTime").textContent = `${data.legacy_latency_us} μs`; | |
| document.getElementById("pgModernTime").textContent = `${data.modern_latency_us} μs`; | |
| document.getElementById("pgLegacyOutPre").textContent = JSON.stringify(data.legacy_output, null, 2); | |
| document.getElementById("pgModernOutPre").textContent = JSON.stringify(data.modern_output, null, 2); | |
| document.getElementById("pgJsonRpcPre").textContent = JSON.stringify(data.mcp_jsonrpc_response, null, 2); | |
| const badge = document.getElementById("pgParityBadge"); | |
| if (data.parity_verified) { | |
| badge.className = "status-pill grey"; | |
| badge.innerHTML = `<span class="dot"></span>100% Exact Match`; | |
| } else { | |
| badge.className = "status-pill amber"; | |
| badge.innerHTML = `<span class="dot"></span>Difference`; | |
| } | |
| } | |
| /* ========================================================================== | |
| Parity Suite Table | |
| ========================================================================== */ | |
| async function ensureAllBundlesLoaded() { | |
| if (!STATE.bootstrap) return; | |
| for (const r of STATE.bootstrap.repositories) { | |
| if (!STATE.repoBundles[r.id]) { | |
| const resp = await fetch(`/api/repos/${r.id}`); | |
| STATE.repoBundles[r.id] = await resp.json(); | |
| } | |
| } | |
| STATE.allParityCases = []; | |
| for (const r of STATE.bootstrap.repositories) { | |
| const b = STATE.repoBundles[r.id]; | |
| for (const c of b.verification.cases) { | |
| STATE.allParityCases.push({ | |
| ...c, | |
| case_id: `${r.id.toUpperCase()}-${String(c.case_index).padStart(2, "0")}`, | |
| repo_id: r.id, | |
| repo_name: r.name, | |
| git_sha: r.git_sha, | |
| }); | |
| } | |
| } | |
| } | |
| async function renderParityTable() { | |
| await ensureAllBundlesLoaded(); | |
| const repoF = document.getElementById("parityRepoFilter").value; | |
| const cliffF = document.getElementById("parityCliffFilter").value; | |
| const filtered = STATE.allParityCases.filter((c) => { | |
| if (repoF !== "all" && c.repo_id !== repoF) return false; | |
| if (cliffF === "cliffs" && c.chunked_rag_parity) return false; | |
| return true; | |
| }); | |
| const tbody = document.getElementById("parityCasesBody"); | |
| tbody.innerHTML = filtered | |
| .map((c) => { | |
| const digest = JSON.stringify(c.mcp_output).slice(0, 62) + "…"; | |
| return ` | |
| <tr> | |
| <td style="font-family:var(--font-mono);font-size:12px;font-weight:600;">${escapeHtml(c.case_id)}</td> | |
| <td> | |
| <div style="font-weight:500;">${escapeHtml(c.label)}</div> | |
| <div style="font-size:11px;color:var(--ink-500);">${escapeHtml(c.repo_name)}@${escapeHtml(c.git_sha)}</div> | |
| </td> | |
| <td style="font-family:var(--font-mono);font-size:11.5px;">${escapeHtml(c.tool_name)}</td> | |
| <td style="font-family:var(--font-mono);font-size:11px;color:var(--ink-700);">${escapeHtml(digest)}</td> | |
| <td> | |
| <span class="status-pill ${c.chunked_rag_parity ? "grey" : "amber"}"> | |
| <span class="dot"></span>${c.chunked_rag_parity ? "Pass" : "Failed"} | |
| </span> | |
| </td> | |
| <td> | |
| <span class="status-pill grey"> | |
| <span class="dot"></span>100% | |
| </span> | |
| </td> | |
| </tr> | |
| `; | |
| }) | |
| .join(""); | |
| } | |
| /* ========================================================================== | |
| FinOps & Benchmarks | |
| ========================================================================== */ | |
| function renderHeadToHeadTable(rows) { | |
| const tbody = document.getElementById("h2hBenchmarkBody"); | |
| if (!tbody) return; | |
| tbody.innerHTML = (rows || []) | |
| .map((r) => { | |
| const isBeam = r.model.includes("beam-1.0"); | |
| const pct = r.zero_shot_parity_pct ?? 0; | |
| const pillTone = pct === 100 ? "grey" : pct >= 90 ? "grey" : "amber"; | |
| return ` | |
| <tr class="${isBeam ? "selected-row" : ""}"> | |
| <td> | |
| <div style="font-weight:${isBeam ? "600" : "500"};color:var(--ink-900);">${escapeHtml(r.model)}</div> | |
| <div style="font-size:11px;color:var(--ink-500);">${escapeHtml(r.provider || "OpenRouter")}</div> | |
| </td> | |
| <td style="font-family:var(--font-mono);font-size:11.5px;">${escapeHtml(r.request_id || "—")}</td> | |
| <td style="font-family:var(--font-mono);font-size:11.5px;"> | |
| ${Number(r.prompt_tokens || 0).toLocaleString()} / ${Number(r.completion_tokens || 0).toLocaleString()} / ${Number(r.reasoning_tokens || 0).toLocaleString()} | |
| </td> | |
| <td style="font-weight:500;">${((r.latency_ms || 0) / 1000).toFixed(1)}s</td> | |
| <td style="font-family:var(--font-mono);font-size:12px;">$${Number(r.cost_usd || 0).toFixed(5)}</td> | |
| <td> | |
| <span class="status-pill ${pillTone}"> | |
| <span class="dot"></span>${r.zero_shot_passed}/${r.total_vectors} (${pct}%) | |
| </span> | |
| </td> | |
| </tr> | |
| `; | |
| }) | |
| .join(""); | |
| } | |
| async function updateRoiSimulator() { | |
| const kloc = Number(document.getElementById("roiKlocRange").value); | |
| const mods = Number(document.getElementById("roiModsRange").value); | |
| const runs = Number(document.getElementById("roiCallsRange").value); | |
| const eng = Number(document.getElementById("roiEngCostRange").value); | |
| document.getElementById("lblKloc").textContent = `${kloc} KLOC`; | |
| document.getElementById("lblMods").textContent = `${mods} Services`; | |
| document.getElementById("lblCalls").textContent = `${runs} / day`; | |
| document.getElementById("lblEngCost").textContent = `${fmtUsdExact(eng)} / yr`; | |
| const resp = await fetch("/api/finops", { | |
| method: "POST", | |
| headers: { "Content-Type": "application/json" }, | |
| body: JSON.stringify({ | |
| legacy_kloc: kloc, | |
| microservices_count: mods, | |
| daily_agent_verification_runs: runs, | |
| engineer_fully_loaded_annual_usd: eng, | |
| }), | |
| }); | |
| const roi = await resp.json(); | |
| document.getElementById("roiManualUsd").textContent = fmtUsdExact(roi.modernization_program_tco_usd.manual_rewrite_usd); | |
| document.getElementById("roiManualWeeks").textContent = `${roi.schedule_impact.manual_months} months`; | |
| document.getElementById("roiFrontierUsd").textContent = fmtUsdExact(roi.modernization_program_tco_usd.qwen38_agent_program_usd); | |
| document.getElementById("roiFrontierTokens").textContent = `API: ${fmtUsdExact(roi.annual_inference_cost_usd.qwen_3_8_2_4t)}/yr`; | |
| document.getElementById("roiBeamUsd").textContent = fmtUsdExact(roi.modernization_program_tco_usd.beambridge_1m_program_usd); | |
| document.getElementById("roiBeamWeeks").textContent = `${roi.schedule_impact.beambridge_months} months · API: ${fmtUsdExact(roi.annual_inference_cost_usd.beam_1_0_with_ast_pack)}/yr`; | |
| document.getElementById("roiNetSavingsBanner").textContent = `${fmtUsdExact(roi.modernization_program_tco_usd.net_enterprise_savings_usd)} Saved`; | |
| document.getElementById("roiTokenBillSaved").textContent = `${roi.annual_inference_cost_usd.token_cost_reduction_vs_qwen38_pct}% Lower Cost`; | |
| renderFinOpsCurve(roi); | |
| } | |
| function renderConsultingCards(citations) { | |
| const box = document.getElementById("consultingCardsGrid"); | |
| box.innerHTML = (citations || []) | |
| .map( | |
| (c) => ` | |
| <div class="rule-card" style="margin-bottom:0;"> | |
| <div style="margin-bottom:6px;"> | |
| <span class="status-pill grey"><span class="dot"></span>${escapeHtml(c.firm)}</span> | |
| </div> | |
| <div style="font-size:12.5px;color:var(--ink-700);line-height:1.5;">${escapeHtml(c.finding)}</div> | |
| </div> | |
| ` | |
| ) | |
| .join(""); | |
| } | |
| /* ========================================================================== | |
| Bootstrap & Event Wiring | |
| ========================================================================== */ | |
| async function initApp() { | |
| document.querySelectorAll(".nav-tab").forEach((btn) => { | |
| btn.addEventListener("click", async () => { | |
| switchView(btn.dataset.view); | |
| if (btn.dataset.view === "parity") await renderParityTable(); | |
| }); | |
| }); | |
| document.getElementById("brandHomeBtn").addEventListener("click", () => switchView("dashboard")); | |
| document.querySelectorAll("[data-goto]").forEach((el) => { | |
| el.addEventListener("click", async () => { | |
| const target = el.getAttribute("data-goto"); | |
| switchView(target); | |
| if (target === "parity") await renderParityTable(); | |
| }); | |
| }); | |
| document.querySelectorAll("#stageStrip .stage-day-item").forEach((item) => { | |
| item.addEventListener("click", () => { | |
| document.querySelectorAll("#stageStrip .stage-day-item").forEach((x) => x.classList.remove("active")); | |
| item.classList.add("active"); | |
| }); | |
| }); | |
| document.getElementById("langToggleBtn").addEventListener("click", () => { | |
| STATE.lang = STATE.lang === "en" ? "ar" : "en"; | |
| applyLanguage(); | |
| }); | |
| document.getElementById("estateSearchInput").addEventListener("input", (e) => { | |
| renderEstatesTable(e.target.value); | |
| }); | |
| document.getElementById("modRepoSelect").addEventListener("change", async (e) => { | |
| const val = e.target.value; | |
| const isGhLive = val === "__github_live__"; | |
| document.getElementById("liveGithubBox").style.display = isGhLive ? "block" : "none"; | |
| document.getElementById("runModernizerBtnText").textContent = isGhLive | |
| ? "Clone & Analyze Repository" | |
| : "Synthesize Whole-Repo MCP"; | |
| if (!isGhLive) { | |
| STATE.selectedRepoId = val; | |
| await loadRepoBundle(val); | |
| } | |
| }); | |
| document.querySelectorAll("#modSubTabs .sub-pill-btn").forEach((btn) => { | |
| btn.addEventListener("click", () => { | |
| document.querySelectorAll("#modSubTabs .sub-pill-btn").forEach((b) => b.classList.remove("active")); | |
| btn.classList.add("active"); | |
| const st = btn.dataset.subtab; | |
| document.getElementById("modTabRules").style.display = st === "rules" ? "block" : "none"; | |
| document.getElementById("modTabMcpCode").style.display = st === "mcp_code" ? "block" : "none"; | |
| document.getElementById("modTabLegacyCode").style.display = st === "legacy_code" ? "block" : "none"; | |
| }); | |
| }); | |
| document.getElementById("runModernizerBtn").addEventListener("click", async () => { | |
| const btn = document.getElementById("runModernizerBtn"); | |
| const repoSel = document.getElementById("modRepoSelect").value; | |
| const effort = document.getElementById("modEffortSelect").value; | |
| btn.disabled = true; | |
| try { | |
| if (repoSel === "__github_live__") { | |
| btn.innerHTML = `<span>Cloning Repository...</span>`; | |
| const ghUrl = document.getElementById("liveGithubUrlInput").value.trim(); | |
| const resp = await fetch("/api/github/ingest", { | |
| method: "POST", | |
| headers: { "Content-Type": "application/json" }, | |
| body: JSON.stringify({ github_url: ghUrl }), | |
| }); | |
| const ghData = await resp.json(); | |
| if (!resp.ok) { | |
| alert(ghData.detail || "GitHub clone failed"); | |
| } else { | |
| renderLiveGithubCloneReport(ghData); | |
| } | |
| } else { | |
| btn.innerHTML = `<span>Synthesizing...</span>`; | |
| const bundle = await loadRepoBundle(repoSel); | |
| const resp = await fetch("/api/beam/synthesize", { | |
| method: "POST", | |
| headers: { "Content-Type": "application/json" }, | |
| body: JSON.stringify({ | |
| repo_id: repoSel, | |
| provider: STATE.provider, | |
| api_key: STATE.apiKey || null, | |
| reasoning_effort: effort, | |
| }), | |
| }); | |
| const syn = await resp.json(); | |
| if (resp.ok && syn.mode !== "live_api_error") { | |
| renderModernizerOutput(bundle, syn); | |
| } else { | |
| alert(syn.error || syn.detail || "Synthesis error"); | |
| } | |
| } | |
| } finally { | |
| btn.disabled = false; | |
| btn.innerHTML = `<span id="runModernizerBtnText">${ | |
| repoSel === "__github_live__" ? "Clone & Analyze Repository" : "Synthesize Whole-Repo MCP" | |
| }</span>`; | |
| } | |
| }); | |
| document.getElementById("copyMcpCodeBtn").addEventListener("click", () => { | |
| navigator.clipboard.writeText(document.getElementById("modernMcpCodePre").textContent || ""); | |
| const b = document.getElementById("copyMcpCodeBtn"); | |
| b.textContent = "Copied"; | |
| setTimeout(() => (b.textContent = "Copy Code"), 1400); | |
| }); | |
| document.getElementById("jumpToPlaygroundBtn").addEventListener("click", () => switchView("playground")); | |
| document.getElementById("pgRepoSelect").addEventListener("change", async (e) => { | |
| const rid = e.target.value; | |
| await loadRepoBundle(rid); | |
| populatePlaygroundTools(rid); | |
| }); | |
| document.getElementById("pgToolSelect").addEventListener("change", (e) => { | |
| renderPlaygroundForm(document.getElementById("pgRepoSelect").value, e.target.value); | |
| }); | |
| document.getElementById("invokeMcpBtn").addEventListener("click", invokePlaygroundTool); | |
| document.getElementById("parityRepoFilter").addEventListener("change", renderParityTable); | |
| document.getElementById("parityCliffFilter").addEventListener("change", renderParityTable); | |
| ["roiKlocRange", "roiModsRange", "roiCallsRange", "roiEngCostRange"].forEach((id) => { | |
| document.getElementById(id).addEventListener("input", updateRoiSimulator); | |
| document.getElementById(id).addEventListener("change", updateRoiSimulator); | |
| }); | |
| const engModal = document.getElementById("engineModal"); | |
| document.getElementById("openEngineModalBtn").addEventListener("click", () => { | |
| document.getElementById("cfgProvider").value = STATE.provider; | |
| document.getElementById("cfgApiKey").value = STATE.apiKey; | |
| engModal.classList.add("open"); | |
| }); | |
| document.getElementById("closeEngineModalBtn").addEventListener("click", () => engModal.classList.remove("open")); | |
| document.getElementById("saveEngineCfgBtn").addEventListener("click", () => { | |
| STATE.provider = document.getElementById("cfgProvider").value; | |
| STATE.apiKey = document.getElementById("cfgApiKey").value.trim(); | |
| safeStorageSet("bb_provider", STATE.provider); | |
| safeStorageSet("bb_api_key", STATE.apiKey); | |
| document.getElementById("engineStatusDot").classList.toggle("live", Boolean(STATE.apiKey)); | |
| engModal.classList.remove("open"); | |
| }); | |
| // Clean 01–04 Onboarding & SHA-256 Modal | |
| const certModal = document.getElementById("certModal"); | |
| let activeGuideClient = "claude"; | |
| let activeGuideSubIndex = 0; | |
| function buildGuideClients(origin) { | |
| const mcpUrl = `${origin}/mcp`; | |
| return { | |
| claude: { | |
| title: "Claude", | |
| extLabel: "claude.ai ↗", | |
| extHref: "https://claude.ai", | |
| modes: [ | |
| { | |
| label: "Claude", | |
| copyLabel: "Copy for Claude", | |
| helper: | |
| STATE.lang === "ar" | |
| ? "يرشدك Claude لإضافة بوابة BeamBridge كموصل مخصص في الإعدادات." | |
| : "Claude walks you through adding BeamBridge as a custom connector in settings.", | |
| snippet: `Connect BeamBridge (${mcpUrl}) to Claude: open Settings › Connectors › Add custom connector, paste ${mcpUrl}, click Add, then list the 12 tools and test pro_rata_subunit_split on $100 USD across [1, 1, 1].`, | |
| }, | |
| { | |
| label: "Claude Code", | |
| copyLabel: "Copy for Claude Code", | |
| helper: | |
| STATE.lang === "ar" | |
| ? "أمر واحد يربط خادم HTTP JSON-RPC 2.0 مباشرة في Claude Code." | |
| : "Attach BeamBridge in one CLI command over HTTP JSON-RPC 2.0.", | |
| snippet: `claude mcp add --transport http beambridge ${mcpUrl}`, | |
| }, | |
| ], | |
| }, | |
| openai: { | |
| title: "OpenAI", | |
| extLabel: "chatgpt.com ↗", | |
| extHref: "https://chatgpt.com", | |
| modes: [ | |
| { | |
| label: "ChatGPT", | |
| copyLabel: "Copy for ChatGPT", | |
| helper: | |
| STATE.lang === "ar" | |
| ? "أضف البوابة كموصل MCP مخصص داخل إعدادات ChatGPT." | |
| : "Attach BeamBridge via ChatGPT Custom MCP Connectors.", | |
| snippet: `Connect custom MCP server ${mcpUrl}, list all 12 tools, and test validate_and_decompose_iban on "GB29 NWBK 6016 1331 9268 19".`, | |
| }, | |
| { | |
| label: "Codex", | |
| copyLabel: "Copy for Codex", | |
| helper: | |
| STATE.lang === "ar" | |
| ? "أضف هذا المقطع إلى ملف إعدادات Codex CLI." | |
| : "Add this block to ~/.codex/config.toml.", | |
| snippet: `[mcp_servers.beambridge]\nurl = "${mcpUrl}"\ntransport = "streamable_http"`, | |
| }, | |
| ], | |
| }, | |
| cursor: { | |
| title: "Cursor", | |
| extLabel: "cursor.com ↗", | |
| extHref: "https://cursor.com", | |
| modes: [ | |
| { | |
| label: "Prompt", | |
| copyLabel: "Copy for Cursor", | |
| helper: | |
| STATE.lang === "ar" | |
| ? "الصقه في محادثة Cursor ليضبط ملف .cursor/mcp.json تلقائياً." | |
| : "Paste into Cursor Agent to configure .cursor/mcp.json automatically.", | |
| snippet: `Add HTTP MCP server "beambridge" (${mcpUrl}) to .cursor/mcp.json and test parse_procurement_price on "1.299,95 €".`, | |
| }, | |
| { | |
| label: "mcp.json", | |
| copyLabel: "Copy mcp.json", | |
| helper: | |
| STATE.lang === "ar" | |
| ? "أو ضعه مباشرة في ملف .cursor/mcp.json." | |
| : "Or save directly into .cursor/mcp.json.", | |
| snippet: JSON.stringify({ mcpServers: { beambridge: { url: mcpUrl, transport: "streamable-http" } } }, null, 2), | |
| }, | |
| ], | |
| }, | |
| antigravity: { | |
| title: "Antigravity", | |
| extLabel: "idx.google.com ↗", | |
| extHref: "https://idx.google.com", | |
| modes: [ | |
| { | |
| label: "Setup", | |
| copyLabel: "Copy for Antigravity", | |
| helper: | |
| STATE.lang === "ar" | |
| ? "اربط بوابة BeamBridge داخل إعدادات MCP في Antigravity." | |
| : "Register BeamBridge inside Antigravity MCP settings.", | |
| snippet: `Register MCP server "beambridge" at ${mcpUrl} and run inspect_and_round_money("45.6785", "BHD", 3).`, | |
| }, | |
| ], | |
| }, | |
| other: { | |
| title: "Other", | |
| extLabel: "modelcontextprotocol.io ↗", | |
| extHref: "https://modelcontextprotocol.io", | |
| modes: [ | |
| { | |
| label: "JSON Config", | |
| copyLabel: "Copy Config", | |
| helper: | |
| STATE.lang === "ar" | |
| ? "متوافق مع أي عميل يدعم بروتوكول MCP عبر HTTP." | |
| : "Standard config for any HTTP JSON-RPC 2.0 MCP client.", | |
| snippet: JSON.stringify({ mcpServers: { beambridge: { url: mcpUrl } } }, null, 2), | |
| }, | |
| { | |
| label: "cURL", | |
| copyLabel: "Copy cURL", | |
| helper: | |
| STATE.lang === "ar" | |
| ? "اختبار مباشر من الطرفية." | |
| : "Test directly from any terminal.", | |
| snippet: `curl -sS -X POST ${mcpUrl} -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'`, | |
| }, | |
| ], | |
| }, | |
| }; | |
| } | |
| function renderGuideClientCard() { | |
| const clients = buildGuideClients(window.location.origin); | |
| const cfg = clients[activeGuideClient] || clients.claude; | |
| if (activeGuideSubIndex >= cfg.modes.length) activeGuideSubIndex = 0; | |
| const mode = cfg.modes[activeGuideSubIndex]; | |
| document.querySelectorAll("#guideClientList .guide-client-btn").forEach((btn) => { | |
| btn.classList.toggle("active", btn.dataset.client === activeGuideClient); | |
| }); | |
| document.getElementById("guideClientHeading").textContent = cfg.title; | |
| const extEl = document.getElementById("guideClientExtLink"); | |
| extEl.textContent = cfg.extLabel; | |
| extEl.href = cfg.extHref; | |
| const pillsBox = document.getElementById("guideModePills"); | |
| if (cfg.modes.length > 1) { | |
| pillsBox.style.display = "inline-flex"; | |
| pillsBox.innerHTML = cfg.modes | |
| .map( | |
| (m, idx) => | |
| `<button type="button" class="guide-mode-pill ${idx === activeGuideSubIndex ? "active" : ""}" data-mindex="${idx}">${escapeHtml(m.label)}</button>` | |
| ) | |
| .join(""); | |
| pillsBox.querySelectorAll(".guide-mode-pill").forEach((pb) => { | |
| pb.addEventListener("click", () => { | |
| activeGuideSubIndex = Number(pb.dataset.mindex); | |
| renderGuideClientCard(); | |
| }); | |
| }); | |
| } else { | |
| pillsBox.style.display = "none"; | |
| pillsBox.innerHTML = ""; | |
| } | |
| document.getElementById("guideClientHelper").textContent = mode.helper; | |
| document.getElementById("mcpEndpointSnippet").textContent = mode.snippet; | |
| document.getElementById("copyClientPromptLabel").textContent = mode.copyLabel; | |
| } | |
| function renderGuideCertificates() { | |
| if (!STATE.bootstrap) return; | |
| document.getElementById("certListBox").innerHTML = STATE.bootstrap.repositories | |
| .map((r) => { | |
| const firstId = (r.verification.synthesis_audit.whole_repo_request_ids || [])[0] || ""; | |
| const sha = r.verification.certificate_sha256 || ""; | |
| return ` | |
| <div class="guide-cert-card"> | |
| <div class="guide-cert-top"> | |
| <div class="guide-cert-repo">${escapeHtml(r.name)} <code style="color:#8e8e9a;font-size:11px;">@${escapeHtml(r.git_sha)}</code></div> | |
| <span class="guide-cert-badge">${r.verification.beam_1m_passed}/${r.verification.total_cases}</span> | |
| </div> | |
| <div class="guide-cert-meta"> | |
| ID: ${escapeHtml(firstId)} · SHA: ${escapeHtml(sha.slice(0, 14))}… | |
| </div> | |
| </div> | |
| `; | |
| }) | |
| .join(""); | |
| } | |
| document.querySelectorAll("#guideClientList .guide-client-btn").forEach((btn) => { | |
| btn.addEventListener("click", () => { | |
| activeGuideClient = btn.dataset.client; | |
| activeGuideSubIndex = 0; | |
| renderGuideClientCard(); | |
| }); | |
| }); | |
| document.getElementById("copyClientPromptBtn").addEventListener("click", () => { | |
| const txt = document.getElementById("mcpEndpointSnippet").textContent || ""; | |
| navigator.clipboard.writeText(txt); | |
| const lbl = document.getElementById("copyClientPromptLabel"); | |
| const prev = lbl.textContent; | |
| lbl.textContent = "Copied"; | |
| setTimeout(() => { | |
| lbl.textContent = prev; | |
| }, 1400); | |
| }); | |
| document.getElementById("copyMasterShaBtn").addEventListener("click", (e) => { | |
| const masterSha = | |
| (STATE.bootstrap && STATE.bootstrap.portfolio_totals && STATE.bootstrap.portfolio_totals.master_certificate_sha256) || ""; | |
| navigator.clipboard.writeText(masterSha); | |
| const btn = e.currentTarget; | |
| const prev = btn.textContent; | |
| btn.textContent = "Copied"; | |
| setTimeout(() => { | |
| btn.textContent = prev; | |
| }, 1500); | |
| }); | |
| document.getElementById("guideOpenEngineBtn").addEventListener("click", () => { | |
| certModal.classList.remove("open"); | |
| document.getElementById("cfgProvider").value = STATE.provider; | |
| document.getElementById("cfgApiKey").value = STATE.apiKey; | |
| engModal.classList.add("open"); | |
| }); | |
| document.getElementById("guideJumpModernizerBtn").addEventListener("click", () => { | |
| certModal.classList.remove("open"); | |
| switchView("modernizer"); | |
| }); | |
| document.getElementById("guideJumpPlaygroundBtn").addEventListener("click", () => { | |
| certModal.classList.remove("open"); | |
| switchView("playground"); | |
| }); | |
| document.getElementById("guideJumpParityBtn").addEventListener("click", async () => { | |
| certModal.classList.remove("open"); | |
| switchView("parity"); | |
| await renderParityTable(); | |
| }); | |
| const CHIP_ACTIONS = { | |
| money: { | |
| repo: "py_moneyed", | |
| tool: "pro_rata_subunit_split", | |
| args: { amount_str: "100.00", currency_code: "USD", weights: [1, 1, 1] }, | |
| }, | |
| iban: { | |
| repo: "schwifty", | |
| tool: "validate_and_decompose_iban", | |
| args: { raw_iban: "GB29 NWBK 6016 1331 9268 19" }, | |
| }, | |
| vat: { | |
| repo: "python_stdnum", | |
| tool: "validate_eu_vat_number", | |
| args: { raw_vat: "DE 136 695 976" }, | |
| }, | |
| }; | |
| document.querySelectorAll("#guideExampleChips .guide-prompt-chip").forEach((chip) => { | |
| chip.addEventListener("click", async () => { | |
| navigator.clipboard.writeText(chip.textContent.trim()); | |
| const act = CHIP_ACTIONS[chip.dataset.chip]; | |
| certModal.classList.remove("open"); | |
| if (act) { | |
| switchView("playground"); | |
| document.getElementById("pgRepoSelect").value = act.repo; | |
| await loadRepoBundle(act.repo); | |
| populatePlaygroundTools(act.repo); | |
| document.getElementById("pgToolSelect").value = act.tool; | |
| renderPlaygroundForm(act.repo, act.tool, act.args); | |
| } | |
| }); | |
| }); | |
| document.getElementById("openCertModalBtn").addEventListener("click", () => { | |
| renderGuideClientCard(); | |
| renderGuideCertificates(); | |
| certModal.classList.add("open"); | |
| }); | |
| document.getElementById("closeCertModalBtn").addEventListener("click", () => certModal.classList.remove("open")); | |
| certModal.addEventListener("click", (e) => { | |
| if (e.target === certModal) certModal.classList.remove("open"); | |
| }); | |
| window.addEventListener("keydown", (e) => { | |
| if (e.key === "Escape") { | |
| certModal.classList.remove("open"); | |
| engModal.classList.remove("open"); | |
| } | |
| }); | |
| // Bootstrap | |
| const bootResp = await fetch("/api/bootstrap"); | |
| const boot = await bootResp.json(); | |
| STATE.bootstrap = boot; | |
| const pt = boot.portfolio_totals; | |
| const fin = boot.finops; | |
| const savedPct = Math.round(fin.annual_inference_cost_usd.token_cost_reduction_vs_qwen38_pct || 97); | |
| const driftPct = Math.round(100 - pt.chunked_rag_parity_pct); | |
| document.getElementById("capParityVal").textContent = `${Math.round(pt.beam_1m_parity_pct)}%`; | |
| document.getElementById("capTokenSavedVal").textContent = `${savedPct}%`; | |
| document.getElementById("capDriftVal").textContent = `${driftPct}%`; | |
| document.getElementById("capRegVal").textContent = "0%"; | |
| document.getElementById("kpiTestsNum").textContent = String(pt.total_verification_assertions); | |
| document.getElementById("kpiToolsNum").textContent = String(pt.mcp_tools_exposed); | |
| document.getElementById("kpiSavingsNum").textContent = fmtCurrency(fin.modernization_program_tco_usd.net_enterprise_savings_usd); | |
| document.getElementById("tlPackSub").textContent = `${(pt.total_raw_beam_tokens / 1_000_000).toFixed(2)}M → ${pt.total_beam_tokens.toLocaleString()} tokens`; | |
| const chunkFails = Math.round(pt.total_verification_assertions * (1 - pt.chunked_rag_parity_pct / 100)); | |
| document.getElementById("darkPassedNum").textContent = String(pt.total_verification_assertions); | |
| document.getElementById("darkFailedNaiveNum").textContent = String(chunkFails); | |
| const mult = (fin.annual_inference_cost_usd.qwen_3_8_2_4t / Math.max(1, fin.annual_inference_cost_usd.beam_1_0_with_ast_pack)).toFixed(1); | |
| document.getElementById("donutCenterMult").textContent = `${mult}x`; | |
| document.getElementById("donutSavedPct").textContent = `${savedPct}%`; | |
| document.getElementById("donutUsedPct").textContent = `${100 - savedPct}%`; | |
| renderEstatesTable(); | |
| renderFinOpsCurve(fin); | |
| renderHeadToHeadTable(boot.head_to_head_benchmark); | |
| renderConsultingCards(fin.citations); | |
| await loadRepoBundle(STATE.selectedRepoId); | |
| await renderMatrixDots(); | |
| await updateRoiSimulator(); | |
| } | |
| window.addEventListener("DOMContentLoaded", initApp); | |