Spaces:
Running
Running
Upload folder using huggingface_hub
Browse filesFiles changed (4)
- Dockerfile-1
- __pycache__/app.cpython-315.pycAdded
- app.py+510-239
- static/instrument.webpDeleted
9 unmodified lines101112131415169 unmodified linesRUN pip install --no-cache-dir --upgrade -r requirements.txtCOPY --chown=user app.py .COPY --chown=user static ./staticENV HOST=0.0.0.0ENV PORT=78609 unmodified lines1011121314159 unmodified linesRUN pip install --no-cache-dir --upgrade -r requirements.txtCOPY --chown=user app.py .ENV HOST=0.0.0.0ENV PORT=7860
14 unmodified lines15161718192021222324252627282910 unmodified lines40414243444546474849140 unmodified lines19019119219319419519619719819920020116 unmodified lines2182192202212222235 unmodified lines229230231232233234139 unmodified lines37437537637737837938038157 unmodified lines43944044144244344457 unmodified lines50250350450550650750850917 unmodified lines52752852953053153253353453553653753853954054154254354422 unmodified lines5675685695705715727 unmodified lines5805815825835845857 unmodified lines5935945955965975987 unmodified lines60660760860961061114 unmodified lines6266276286296306314 unmodified lines63663763863964064116 unmodified lines65865966066166266366466566666766866967067167267367441 unmodified lines71671771871972072172245 unmodified lines7687697707717727737747757767777787797807817827837847857867877887897907917927937941 unmodified line7967977987998008018023 unmodified lines80680780880981081181281381481581681781881982082182213 unmodified lines8368378388398408418422 unmodified lines84584684784884985019 unmodified lines8708718728738748758768 unmodified lines88588688788888989089119 unmodified lines91191291391491591691711 unmodified lines92993093193293393493593693793893912 unmodified lines95295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511 unmodified line10531054105510561057105810592 unmodified lines106210631064106510661067106821 unmodified lines1090109110921093109410951096109710981099110011011 unmodified line1103110411051106110711081 unmodified line111011111112111311141115111611171118111915 unmodified lines1135113611371138113911404 unmodified lines114511461147114811491150115145 unmodified lines119711981199120012011202120314 unmodified lines12181219122012211222122312241225122612271228122912304 unmodified lines12351236123712381239124012411242124312447 unmodified lines125212531254125512561257125812591260126112621263126436 unmodified lines130113021303130413051306130713081309131013111312131315 unmodified lines13291330133113321333133413351 unmodified line13371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013618 unmodified lines1370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139224 unmodified lines1417141814191420142114221423142414251426142714281429143014311432143314344 unmodified lines143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091 unmodified line1511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461 unmodified line154815491550155115521553155433 unmodified lines158815891590159115921593159415951596159715981599160016011602160316041605160646 unmodified lines16531654165516561657165816591660166116621663166416651666166716681669167018 unmodified lines16891690169116921693169416951696169716981699170017011702170312 unmodified lines1716171717181719172017216 unmodified lines1728172917301731173217331734173517361737173817392 unmodified lines17421743174417451746174717484 unmodified lines175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417754 unmodified lines178017811782178317841785178617871788178957 unmodified lines1847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918708 unmodified lines18791880188118821883188418851886188751 unmodified lines19391940194119421943194419453 unmodified lines1949195019511952195319542 unmodified lines19571958195919601961196214 unmodified linesfrom __future__ import annotationsimport argparseimport contextlibimport contextvarsimport osimport reimport secretsimport timefrom dataclasses import dataclass, fieldfrom datetime import UTC, datetime, timedeltafrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Literalimport uvicorn10 unmodified lines)from pydantic import BaseModel, ConfigDict, Fieldfrom starlette.applications import Starlettefrom starlette.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Responsefrom starlette.routing import Routeif TYPE_CHECKING:from starlette.requests import Requestfrom starlette.types import ASGIApp, Receive, Scope, Send140 unmodified linesforbidden_keys: set[tuple[str, str]] = field(default_factory=set)poll_log: list[dict[str, Any]] = field(default_factory=list)recent_events: list[dict[str, Any]] = field(default_factory=list)event_seq: int = 0last_touched: float = field(default_factory=time.monotonic)def touch(self) -> None:self.last_touched = time.monotonic()def emit(self, event_name: str, filter_key: str, data: dict[str, Any]) -> StoredEvent:self.touch()key = (event_name, filter_key)16 unmodified linesself.recent_events.append(record.to_dict())if len(self.recent_events) > MAX_RECENT_EVENTS:del self.recent_events[:-MAX_RECENT_EVENTS]return recorddef reset(self) -> None:5 unmodified linesself.forbidden_keys.clear()self.poll_log.clear()self.recent_events.clear()class RoomRegistry:139 unmodified lineskey = _resolve_stream_key(params.name, params.arguments)if key in state.forbidden_keys:raise MCPError(EVENTS_FORBIDDEN, "Subscription revoked by server")history = state.streams.get(key, [])total = state.stream_totals.get(key, 0)# Sequence number of the last evicted event (0 when nothing has been trimmed).57 unmodified linesif len(state.poll_log) > MAX_POLL_LOG:del state.poll_log[:-MAX_POLL_LOG]return result57 unmodified lines# HTTP control plane & browser UI# ---------------------------------------------------------------------------STATIC_DIR = Path(__file__).resolve().parent / "static"def _room_from_request(request: Request) -> PlaygroundState | None:raw_room = request.path_params.get("room_id")17 unmodified linesreturn JSONResponse({"status": "ok"})async def http_static_instrument(request: Request) -> Response:del requestasset = STATIC_DIR / "instrument.webp"if not asset.is_file():return JSONResponse({"error": "asset not found"}, status_code=404)return FileResponse(asset,media_type="image/webp",headers={"Cache-Control": "public, max-age=86400"},)async def http_emit(request: Request) -> JSONResponse:state = _room_from_request(request)if state is None:22 unmodified linesstr(body.get("filter_key") or body.get("job_id") or "*"),)state.pending_gaps.add(key)return JSONResponse({"gap_armed": list(key)})7 unmodified linesstr(body.get("filter_key") or body.get("job_id") or "*"),)state.forbidden_keys.add(key)return JSONResponse({"forbidden": list(key)})7 unmodified linesstr(body.get("filter_key") or body.get("job_id") or "*"),)state.forbidden_keys.discard(key)return JSONResponse({"restored": list(key)})7 unmodified linesstate.poll_interval_ms = max(250, min(int(body["poll_interval_ms"]), 300_000))except (TypeError, ValueError):return JSONResponse({"error": "poll_interval_ms must be an integer"}, status_code=400)return JSONResponse({"poll_interval_ms": state.poll_interval_ms})14 unmodified lines"room_id": state.room_id,"poll_interval_ms": state.poll_interval_ms,"streams": {f"{k[0]}:{k[1]}": len(v) for k, v in state.streams.items()},"pending_gaps": [f"{k[0]}:{k[1]}" for k in sorted(state.pending_gaps)],"forbidden": [f"{k[0]}:{k[1]}" for k in sorted(state.forbidden_keys)],"event_count": state.event_seq,4 unmodified lines)DASHBOARD_HTML = """<!doctype html><html lang="en"><head>16 unmodified lines--muted: #4c5667;--accent: #1849d6;--accent-hover: #1239aa;--accent-soft: #eef3ff;--warm: #c84323;--warm-soft: #fdf1ee;--ok: #16794b;--ok-soft: #edf8f2;--scope-bg: #0d121c;--scope-border: #202a3d;--scope-ink: #e5ebf5;--scope-muted: #8c9bb3;--scope-trace: #3b82f6;--scope-pulse: #60a5fa;--font-sans: "IBM Plex Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;--font-mono: "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace;--text-heading: 1.125rem;41 unmodified lines.topbar-inner {max-width: 1120px;margin: 0 auto;padding: 0.85rem 1.5rem;display: flex;align-items: center;justify-content: space-between;45 unmodified lines.page {max-width: 1120px;margin: 0 auto;padding: 1.75rem 1.5rem 3.5rem;display: flex;flex-direction: column;gap: 1.75rem;}/* Opening workspace band */.opening {display: grid;grid-template-columns: minmax(0, 1.15fr) minmax(0, 0.85fr);gap: 2rem;align-items: center;}.opening > * {min-width: 0;}h1 {margin: 0 0 0.6rem;font-size: clamp(1.85rem, 3.2vw, 2.5rem);font-weight: 600;line-height: 1.08;letter-spacing: -0.03em;1 unmodified line}.opening-lead {margin: 0 0 1.25rem;max-width: 54ch;color: var(--muted);font-size: var(--text-body);3 unmodified linesbackground: var(--surface);border: 1px solid var(--border);border-radius: var(--radius);padding: 0.9rem 1rem;display: flex;flex-direction: column;gap: 0.7rem;}.connect-head {display: flex;align-items: center;justify-content: space-between;gap: 0.75rem;flex-wrap: wrap;}13 unmodified linesalign-items: center;justify-content: center;margin: 0;padding: 0.32rem 0.68rem;border: 0;border-radius: 4px;background: transparent;2 unmodified linesfont-size: var(--text-sm);font-weight: 500;cursor: pointer;transition: background-color 150ms var(--ease), color 150ms var(--ease);}19 unmodified lines.command-code {flex: 1;min-width: 0;padding: 0.58rem 0.75rem;background: var(--surface-subtle);border: 1px solid var(--border);border-radius: var(--radius-sm);8 unmodified linesdisplay: inline-flex;align-items: center;justify-content: center;padding: 0.56rem 1.05rem;border: 1px solid var(--accent);border-radius: var(--radius-sm);background: var(--accent);19 unmodified linesdisplay: inline-flex;align-items: center;justify-content: center;padding: 0.46rem 0.85rem;border: 1px solid var(--border-strong);border-radius: var(--radius-sm);background: var(--surface);11 unmodified linesborder-color: var(--ink);}.btn-danger {display: inline-flex;align-items: center;justify-content: center;padding: 0.46rem 0.85rem;border: 1px solid #e6b4a8;border-radius: var(--radius-sm);background: var(--warm-soft);12 unmodified lines}.toast {min-height: 1.25rem;font-size: var(--text-sm);color: var(--ok);font-weight: 500;}.instrument-frame {margin: 0;border-radius: var(--radius);overflow: hidden;border: 1px solid var(--border);background: var(--surface);aspect-ratio: 16 / 9;}.instrument-frame img {display: block;width: 100%;height: 100%;object-fit: cover;}/* Recessed oscilloscope signal flow strip */.scope-band {background: var(--scope-bg);border: 1px solid var(--scope-border);border-radius: var(--radius);padding: 1.1rem 1.25rem;color: var(--scope-ink);display: flex;flex-direction: column;gap: 0.9rem;}.scope-svg {width: 100%;height: auto;display: block;}.scope-line {stroke: #24324a;stroke-width: 2;fill: none;}.scope-active {stroke: var(--scope-pulse);stroke-width: 2.5;fill: none;stroke-dasharray: 12 180;stroke-dashoffset: 192;opacity: 0;}.scope-band.pulse-emit .trace-emit {opacity: 1;animation: trace-sweep 680ms var(--ease) forwards;}.scope-band.pulse-poll .trace-poll {opacity: 1;animation: trace-sweep 680ms var(--ease) forwards;}@keyframes trace-sweep {0% { stroke-dashoffset: 192; opacity: 0.95; }100% { stroke-dashoffset: 0; opacity: 0; }}.scope-metrics {display: grid;grid-template-columns: repeat(4, minmax(0, 1fr));gap: 0.75rem;padding-top: 0.85rem;border-top: 1px solid var(--scope-border);font-variant-numeric: tabular-nums;}.metric-label {display: block;font-size: var(--text-sm);color: var(--scope-muted);}.metric-value {display: block;font-family: var(--font-mono);font-size: var(--text-body);font-weight: 500;color: var(--scope-ink);overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}/* Sections */1 unmodified linebackground: var(--surface);border: 1px solid var(--border);border-radius: var(--radius);padding: 1.35rem 1.5rem;}.section-head {2 unmodified linesjustify-content: space-between;gap: 1rem;flex-wrap: wrap;margin-bottom: 1rem;}h2 {21 unmodified linesgrid-template-columns: minmax(0, 1fr) auto;gap: 0.75rem 1.25rem;align-items: center;padding: 0.95rem 0;border-top: 1px solid var(--border);}.prompt-row:first-child {padding-top: 0.25rem;border-top: 0;}1 unmodified linepadding-bottom: 0;}.prompt-title {margin: 0 0 0.2rem;font-size: var(--text-body);1 unmodified linecolor: var(--ink);}.prompt-row > div {min-width: 0;}.prompt-text {margin: 0 0 0.28rem;font-family: var(--font-mono);15 unmodified linescolor: var(--muted);}/* Control deck */.deck-grid {display: grid;4 unmodified lines.deck-col {display: flex;flex-direction: column;gap: 0.75rem;}.deck-col + .deck-col {45 unmodified linesinput[type="text"],input[type="number"] {width: 100%;padding: 0.48rem 0.65rem;border: 1px solid var(--border-strong);border-radius: var(--radius-sm);background: var(--surface);14 unmodified linesflex-wrap: wrap;gap: 0.6rem;align-items: center;margin-top: 0.15rem;}.fault-bar {margin-top: 1.25rem;padding-top: 1.1rem;border-top: 1px solid var(--border);display: flex;flex-wrap: wrap;gap: 0.75rem 1rem;4 unmodified lines.fault-group {display: flex;flex-wrap: wrap;gap: 0.55rem;align-items: flex-end;}/* Activity inspector */.inspector-grid {display: grid;7 unmodified lines}.log-list {margin-top: 0.65rem;display: flex;flex-direction: column;}.log-item {padding: 0.6rem 0;border-top: 1px solid var(--border);display: flex;flex-direction: column;36 unmodified lines}.empty-state {margin: 0.75rem 0 0;font-size: var(--text-sm);color: var(--muted);}pre.raw-json {margin: 0.65rem 0 0;padding: 0.85rem;border-radius: var(--radius-sm);background: var(--scope-bg);15 unmodified linesgap: 0.75rem;font-size: var(--text-sm);color: var(--muted);padding-top: 0.25rem;}.footer code {1 unmodified linecolor: var(--ink);}@media (max-width: 860px) {.opening {grid-template-columns: 1fr;gap: 1.25rem;}.deck-grid,.inspector-grid {grid-template-columns: 1fr;}.deck-col + .deck-col,.inspector-col + .inspector-col {padding-left: 0;padding-top: 1.25rem;border-left: 0;border-top: 1px solid var(--border);}.scope-metrics {grid-template-columns: repeat(2, minmax(0, 1fr));}}@media (max-width: 640px) {8 unmodified lines.nav {gap: 1rem;}.segmented {max-width: 100%;overflow-x: auto;}.page {padding: 1.25rem 1rem 2.5rem;}.section {padding: 1.1rem 1rem;}.prompt-row {grid-template-columns: 1fr;}.command-row {flex-direction: column;align-items: stretch;}}@media (prefers-reduced-motion: reduce) {24 unmodified lines<main class="page"><section class="opening"><div><h1>Test MCP event polling live</h1><p class="opening-lead">Trigger server events inside your isolated room and watch fast-agent wake from idle, recover from gaps, and handle revoked streams.</p><div class="connect-panel"><div class="connect-head"><div class="segmented" role="tablist" aria-label="Connection command format"><button type="button" role="tab" aria-selected="true" data-cmd="go" onclick="setCmdMode('go')">fast-agent go</button><button type="button" role="tab" aria-selected="false" data-cmd="connect" onclick="setCmdMode('connect')">/mcp connect</button><button type="button" role="tab" aria-selected="false" data-cmd="url" onclick="setCmdMode('url')">Endpoint URL</button></div><span class="toast" id="toast" role="status" aria-live="polite"></span></div>4 unmodified lines</div></div><figure class="instrument-frame"><img src="/static/instrument.webp" alt="Minimalist studio signal relay instrument with a cobalt pulse display and rotary controls" width="1279" height="720"></figure></section><section class="scope-band" id="scope-band" aria-label="SEP-3415 poll delivery signal flow"><svg class="scope-svg" viewBox="0 0 960 92" role="img" aria-label="Signal flow from browser control plane to room stream, events/poll, and fast-agent wake"><!-- Evenly spaced bus lines (80px gaps) --><line class="scope-line" x1="184" y1="46" x2="264" y2="46" /><line class="scope-line" x1="440" y1="46" x2="520" y2="46" /><line class="scope-line" x1="696" y1="46" x2="776" y2="46" /><!-- Directional chevrons --><polyline points="254,40 262,46 254,52" fill="none" stroke="#3b537a" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" /><polyline points="510,40 518,46 510,52" fill="none" stroke="#3b537a" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" /><polyline points="766,40 774,46 766,52" fill="none" stroke="#3b82f6" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" /><!-- Animated cobalt signal pulses --><line class="scope-active trace-emit" x1="184" y1="46" x2="264" y2="46" /><line class="scope-active trace-poll" x1="440" y1="46" x2="520" y2="46" /><line class="scope-active trace-poll" x1="696" y1="46" x2="776" y2="46" /><!-- Node 1 --><rect x="8" y="16" width="176" height="60" rx="8" fill="#131b29" stroke="#26344d" /><text x="24" y="42" fill="#e5ebf5" font-family="IBM Plex Sans, sans-serif" font-size="15" font-weight="600">Control plane</text><text x="24" y="61" fill="#8c9bb3" font-family="IBM Plex Mono, monospace" font-size="12.5">POST /emit</text><!-- Node 2 --><rect x="264" y="16" width="176" height="60" rx="8" fill="#131b29" stroke="#26344d" /><text x="280" y="42" fill="#e5ebf5" font-family="IBM Plex Sans, sans-serif" font-size="15" font-weight="600">Room stream</text><text x="280" y="61" fill="#8c9bb3" font-family="IBM Plex Mono, monospace" font-size="12.5">cursor + history</text><!-- Node 3 --><rect x="520" y="16" width="176" height="60" rx="8" fill="#131b29" stroke="#26344d" /><text x="536" y="42" fill="#e5ebf5" font-family="IBM Plex Sans, sans-serif" font-size="15" font-weight="600">SEP-3415 poll</text><text x="536" y="61" fill="#8c9bb3" font-family="IBM Plex Mono, monospace" font-size="12.5">events/poll</text><!-- Node 4 --><rect x="776" y="16" width="176" height="60" rx="8" fill="#131b29" stroke="#2c4a82" /><text x="792" y="42" fill="#e5ebf5" font-family="IBM Plex Sans, sans-serif" font-size="15" font-weight="600">fast-agent</text><text x="792" y="61" fill="#60a5fa" font-family="IBM Plex Mono, monospace" font-size="12.5">wake turn</text></svg><div class="scope-metrics"><div><span class="metric-label">Room</span><span class="metric-value" id="metric-room">-</span></div><div><span class="metric-label">Events emitted</span><span class="metric-value" id="metric-events">0</span></div><div><span class="metric-label">Polls received</span><span class="metric-value" id="metric-polls">0</span></div><div><span class="metric-label">nextPollMs</span><span class="metric-value" id="metric-interval">2000 ms</span></div></div></section><section class="section"><div class="section-head"><h2>Prompts to try in fast-agent</h2><p class="section-note">Paste a prompt after connecting, then trigger the matching event below.</p></div><div class="prompt-list">1 unmodified line<div><p class="prompt-title">Wake on heartbeat</p><code class="prompt-text" id="prompt-1">Register for the heartbeat and tell me an interesting fact when it triggers.</code><p class="prompt-step">Then click Send heartbeat below to wake the idle agent.</p></div><button type="button" class="btn-secondary" onclick="copyPrompt('prompt-1')">Copy prompt</button></div><div class="prompt-row"><div><p class="prompt-title">Follow a job to completion</p><code class="prompt-text" id="prompt-2">Start job-1 for "nightly fine-tune", subscribe to job.status_changed for it, and summarize the run once it finishes.</code><p class="prompt-step">Then emit running and done (or failed) for job-1 in the control deck.</p></div><button type="button" class="btn-secondary" onclick="copyPrompt('prompt-2')">Copy prompt</button></div><div class="prompt-row"><div><p class="prompt-title">Recover from a skipped-event gap</p><code class="prompt-text" id="prompt-3">Watch job-1 and if the server reports truncated events, fetch full job details to catch up.</code><p class="prompt-step">Then click Arm truncated gap and emit a new stage for job-1.</p></div><button type="button" class="btn-secondary" onclick="copyPrompt('prompt-3')">Copy prompt</button></div><div class="prompt-row"><div><p class="prompt-title">Test passive buffering or revocation</p><code class="prompt-text" id="prompt-4">Subscribe passively (wake=false) to system.heartbeat and hold updates until I ask.</code><p class="prompt-step">Send heartbeats to watch the toolbar inbox grow, or click Revoke job to test -32024 Forbidden.</p></div><button type="button" class="btn-secondary" onclick="copyPrompt('prompt-4')">Copy prompt</button></div></div></section>1 unmodified line<section class="section"><div class="section-head"><h2>Event control deck</h2><p class="section-note">Actions here affect only this room.</p></div><div class="deck-grid">33 unmodified lines</div><div class="fault-bar"><div class="fault-group"><div class="field field-compact"><label for="poll-ms">nextPollMs</label><input id="poll-ms" type="number" value="2000" min="250" max="300000" step="250"></div><button type="button" class="btn-secondary" onclick="setPollMs()">Apply</button></div><div class="fault-group"><button type="button" class="btn-secondary" onclick="armGap()">Arm truncated gap</button><button type="button" class="btn-danger" onclick="armTerm()">Revoke job</button><button type="button" class="btn-secondary" onclick="unTerm()">Restore job</button><button type="button" class="btn-danger" onclick="resetAll()">Reset room</button></div></div></section>46 unmodified linesconst apiPrefix = roomId === 'public' ? '' : '/r/' + encodeURIComponent(roomId);const mcpUrl = window.location.origin + apiPrefix + '/mcp';let cmdMode = 'go';let lastPollCount = 0;let lastEventCount = 0;document.getElementById('header-room').textContent = 'room: ' + roomId;document.getElementById('metric-room').textContent = roomId;document.getElementById('footer-room').textContent = roomId;function getCommandText(mode) {if (mode === 'connect') return '/mcp connect ' + mcpUrl + ' --name playground';if (mode === 'url') return mcpUrl;return 'fast-agent go --url ' + mcpUrl;}function setCmdMode(mode) {18 unmodified linessetTimeout(() => { if (el.textContent === msg) el.textContent = ''; }, 2600);}function triggerPulse(kind) {const band = document.getElementById('scope-band');const cls = kind === 'emit' ? 'pulse-emit' : 'pulse-poll';band.classList.remove(cls);void band.offsetWidth;band.classList.add(cls);setTimeout(() => band.classList.remove(cls), 750);}async function copyText(text, label) {try {await navigator.clipboard.writeText(text);12 unmodified linesif (el) copyText(el.textContent.trim(), 'Prompt copied');}async function post(path, body = {}) {const r = await fetch(apiPrefix + path, {method: 'POST',6 unmodified lines}function jobId() { return document.getElementById('job').value.trim() || 'job-1'; }function detail() { return document.getElementById('detail').value; }function selectedStage() {const checked = document.querySelector('input[name="stage"]:checked');return checked ? checked.value : 'running';}async function emitSelectedJob() {const stage = selectedStage();const res = await post('/emit', {2 unmodified linesstage,detail: detail(),});triggerPulse('emit');toast('Emitted ' + res.event_id + ' (' + stage + ')');}4 unmodified linesfilter_key: '*',data: { seq: Date.now(), note },});triggerPulse('emit');toast('Emitted ' + res.event_id + ' (system.heartbeat)');}async function armGap() {await post('/emit-gap', { event_name: 'job.status_changed', job_id: jobId() });toast('Armed truncated gap for ' + jobId());}async function armTerm() {await post('/terminate', { event_name: 'job.status_changed', job_id: jobId() });toast('Revoked subscription for ' + jobId());}async function unTerm() {await post('/unterminate', { event_name: 'job.status_changed', job_id: jobId() });toast('Restored subscription for ' + jobId());}async function setPollMs() {4 unmodified linesasync function resetAll() {await post('/reset');lastPollCount = 0;toast('Room streams and poll logs cleared');}function shortTime(iso) {if (!iso) return '';const d = new Date(iso);57 unmodified linesconst r = await fetch(apiPrefix + '/stats');const data = await r.json();if (data.poll_count > lastPollCount) {triggerPulse('poll');}if (data.event_count > lastEventCount && lastEventCount > 0) {triggerPulse('emit');}lastPollCount = data.poll_count || 0;lastEventCount = data.event_count || 0;document.getElementById('metric-events').textContent = String(data.event_count || 0);document.getElementById('metric-polls').textContent = String(data.poll_count || 0);document.getElementById('metric-interval').textContent = String(data.poll_interval_ms) + ' ms';renderFormatted(data);document.getElementById('events-raw').textContent = JSON.stringify({room_id: data.room_id,poll_interval_ms: data.poll_interval_ms,streams: data.streams,pending_gaps: data.pending_gaps,forbidden: data.forbidden,8 unmodified lines}}setCmdMode('go');setInterval(refresh, 1500);refresh();</script></body></html>51 unmodified linesRoute("/", http_root, methods=["GET"]),Route("/new", http_root, methods=["GET"]),Route("/r/{room_id}", http_room_index, methods=["GET"]),Route("/static/instrument.webp", http_static_instrument, methods=["GET"]),Route("/health", http_health, methods=["GET"]),# Room-scoped control planeRoute("/r/{room_id}/emit", http_emit, methods=["POST"]),3 unmodified linesRoute("/r/{room_id}/config", http_config, methods=["POST"]),Route("/r/{room_id}/reset", http_reset, methods=["POST"]),Route("/r/{room_id}/stats", http_stats, methods=["GET"]),# Public fallback control plane (backwards compatible)Route("/emit", http_emit, methods=["POST"]),Route("/emit-gap", http_gap, methods=["POST"]),2 unmodified linesRoute("/config", http_config, methods=["POST"]),Route("/reset", http_reset, methods=["POST"]),Route("/stats", http_stats, methods=["GET"]),*mcp_app.routes,],)14 unmodified lines1516171819202122232425262728293010 unmodified lines414243444546474849505152535455565758140 unmodified lines19920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822916 unmodified lines2462472482492502512525 unmodified lines258259260261262263264265139 unmodified lines40540640740840941041141241341441557 unmodified lines47347447547647747847948048148248348448548648748857 unmodified lines54654754854955055117 unmodified lines56957057157257357422 unmodified lines5975985996006016026037 unmodified lines6116126136146156166177 unmodified lines6256266276286296306317 unmodified lines63964064164264364464514 unmodified lines6606616626636646656664 unmodified lines67167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570616 unmodified lines72372472572672772872973073173273373473573673773841 unmodified lines78078178278378478578645 unmodified lines8328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638641 unmodified line8668678688698708718723 unmodified lines87687787887988088188288388488588688788888989089189213 unmodified lines9069079089099109119122 unmodified lines91591691791891992092119 unmodified lines9419429439449459469478 unmodified lines95695795895996096196219 unmodified lines98298398498598698798811 unmodified lines10001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103212 unmodified lines1045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731 unmodified line11751176117711781179118011812 unmodified lines118411851186118711881189119021 unmodified lines1212121312141215121612171218121912201221122212231 unmodified line12251226122712281229123012311232123312341 unmodified line12361237123812391240124115 unmodified lines125712581259126012611262126312641265126612671268126912704 unmodified lines127512761277127812791280128145 unmodified lines132713281329133013311332133314 unmodified lines13481349135013511352135313541355135613571358135913601361136213631364136513664 unmodified lines137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114027 unmodified lines141014111412141314141415141614171418141914201421142236 unmodified lines145914601461146214631464146514661467146814691470147115 unmodified lines14871488148914901491149214931 unmodified line149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615178 unmodified lines1526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155124 unmodified lines15761577157815791580158115821583158415851586158715881589159015911592159315944 unmodified lines15991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501 unmodified line16521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001 unmodified line170217031704170517061707170833 unmodified lines1742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176746 unmodified lines18141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518 unmodified lines19041905190619071908190912 unmodified lines1922192319241925192619271928192919306 unmodified lines1937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919602 unmodified lines1963196419651966196719684 unmodified lines19731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619974 unmodified lines200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204757 unmodified lines210521062107210821092110211121122113211421152116211721182119212021218 unmodified lines213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215751 unmodified lines2209221022112212221322143 unmodified lines22182219222022212222222322242 unmodified lines222722282229223022312232223314 unmodified linesfrom __future__ import annotationsimport argparseimport asyncioimport contextlibimport contextvarsimport jsonimport osimport reimport secretsimport timefrom dataclasses import dataclass, fieldfrom datetime import UTC, datetime, timedeltafrom typing import TYPE_CHECKING, Any, Literalimport uvicorn10 unmodified lines)from pydantic import BaseModel, ConfigDict, Fieldfrom starlette.applications import Starlettefrom starlette.responses import (HTMLResponse,JSONResponse,RedirectResponse,Response,StreamingResponse,)from starlette.routing import Routeif TYPE_CHECKING:from collections.abc import AsyncIteratorfrom starlette.requests import Requestfrom starlette.types import ASGIApp, Receive, Scope, Send140 unmodified linesforbidden_keys: set[tuple[str, str]] = field(default_factory=set)poll_log: list[dict[str, Any]] = field(default_factory=list)recent_events: list[dict[str, Any]] = field(default_factory=list)last_polled: dict[tuple[str, str], float] = field(default_factory=dict)event_seq: int = 0last_touched: float = field(default_factory=time.monotonic)subscribers: set[asyncio.Queue[dict[str, Any]]] = field(default_factory=set)def touch(self) -> None:self.last_touched = time.monotonic()def notify(self, payload: dict[str, Any]) -> None:for queue in list(self.subscribers):if queue.full():with contextlib.suppress(asyncio.QueueEmpty):queue.get_nowait()with contextlib.suppress(asyncio.QueueFull):queue.put_nowait(payload)def active_streams(self) -> list[str]:window = max((self.poll_interval_ms * 4) / 1000.0, 20.0)cutoff = time.monotonic() - windowreturn [f"{k[0]}:{k[1]}"for k, ts in sorted(self.last_polled.items(), key=lambda item: item[1], reverse=True)if ts >= cutoff]def emit(self, event_name: str, filter_key: str, data: dict[str, Any]) -> StoredEvent:self.touch()key = (event_name, filter_key)16 unmodified linesself.recent_events.append(record.to_dict())if len(self.recent_events) > MAX_RECENT_EVENTS:del self.recent_events[:-MAX_RECENT_EVENTS]self.notify({"kind": "emit", "name": event_name, "filter_key": filter_key})return recorddef reset(self) -> None:5 unmodified linesself.forbidden_keys.clear()self.poll_log.clear()self.recent_events.clear()self.last_polled.clear()self.notify({"kind": "state"})class RoomRegistry:139 unmodified lineskey = _resolve_stream_key(params.name, params.arguments)if key in state.forbidden_keys:state.notify({"kind": "fault", "reason": "forbidden", "name": params.name})raise MCPError(EVENTS_FORBIDDEN, "Subscription revoked by server")state.last_polled[key] = time.monotonic()history = state.streams.get(key, [])total = state.stream_totals.get(key, 0)# Sequence number of the last evicted event (0 when nothing has been trimmed).57 unmodified linesif len(state.poll_log) > MAX_POLL_LOG:del state.poll_log[:-MAX_POLL_LOG]state.notify({"kind": "fault" if truncated else "poll","name": params.name,"filter_key": key[1],"returned": len(result.events),"truncated": truncated,})return result57 unmodified lines# HTTP control plane & browser UI# ---------------------------------------------------------------------------def _room_from_request(request: Request) -> PlaygroundState | None:raw_room = request.path_params.get("room_id")17 unmodified linesreturn JSONResponse({"status": "ok"})async def http_emit(request: Request) -> JSONResponse:state = _room_from_request(request)if state is None:22 unmodified linesstr(body.get("filter_key") or body.get("job_id") or "*"),)state.pending_gaps.add(key)state.notify({"kind": "fault", "reason": "gap_armed", "name": key[0]})return JSONResponse({"gap_armed": list(key)})7 unmodified linesstr(body.get("filter_key") or body.get("job_id") or "*"),)state.forbidden_keys.add(key)state.notify({"kind": "fault", "reason": "revoked", "name": key[0]})return JSONResponse({"forbidden": list(key)})7 unmodified linesstr(body.get("filter_key") or body.get("job_id") or "*"),)state.forbidden_keys.discard(key)state.notify({"kind": "state"})return JSONResponse({"restored": list(key)})7 unmodified linesstate.poll_interval_ms = max(250, min(int(body["poll_interval_ms"]), 300_000))except (TypeError, ValueError):return JSONResponse({"error": "poll_interval_ms must be an integer"}, status_code=400)state.notify({"kind": "state"})return JSONResponse({"poll_interval_ms": state.poll_interval_ms})14 unmodified lines"room_id": state.room_id,"poll_interval_ms": state.poll_interval_ms,"streams": {f"{k[0]}:{k[1]}": len(v) for k, v in state.streams.items()},"active_streams": state.active_streams(),"pending_gaps": [f"{k[0]}:{k[1]}" for k in sorted(state.pending_gaps)],"forbidden": [f"{k[0]}:{k[1]}" for k in sorted(state.forbidden_keys)],"event_count": state.event_seq,4 unmodified lines)async def http_stream(request: Request) -> Response:"""Server-Sent Events stream pushing real-time emit/poll pulses to the UI."""state = _room_from_request(request)if state is None:return _invalid_room_response()queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=32)state.subscribers.add(queue)async def event_generator() -> AsyncIterator[str]:try:yield f"data: {json.dumps({'kind': 'connected'})}\n\n"while True:if await request.is_disconnected():breaktry:item = await asyncio.wait_for(queue.get(), timeout=15.0)yield f"data: {json.dumps(item)}\n\n"except TimeoutError:yield ": keepalive\n\n"finally:state.subscribers.discard(queue)return StreamingResponse(event_generator(),media_type="text/event-stream",headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},)DASHBOARD_HTML = """<!doctype html><html lang="en"><head>16 unmodified lines--muted: #4c5667;--accent: #1849d6;--accent-hover: #1239aa;--warm: #c84323;--warm-soft: #fdf1ee;--ok: #16794b;--scope-bg: #0d121c;--scope-border: #202a3d;--scope-ink: #e5ebf5;--scope-muted: #8c9bb3;--scope-emit: #3b82f6;--scope-poll: #34d399;--scope-fault: #f97316;--font-sans: "IBM Plex Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;--font-mono: "IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace;--text-heading: 1.125rem;41 unmodified lines.topbar-inner {max-width: 1120px;margin: 0 auto;padding: 0.8rem 1.5rem;display: flex;align-items: center;justify-content: space-between;45 unmodified lines.page {max-width: 1120px;margin: 0 auto;padding: 1.5rem 1.5rem 3rem;display: flex;flex-direction: column;gap: 1.35rem;}/* Opening workspace band */.opening {display: grid;grid-template-columns: minmax(0, 1.15fr) minmax(0, 0.85fr);gap: 1.5rem;align-items: stretch;}.opening > * {min-width: 0;}.opening-left {display: flex;flex-direction: column;justify-content: center;}h1 {margin: 0 0 0.5rem;font-size: clamp(1.75rem, 3vw, 2.35rem);font-weight: 600;line-height: 1.08;letter-spacing: -0.03em;1 unmodified line}.opening-lead {margin: 0 0 1.1rem;max-width: 54ch;color: var(--muted);font-size: var(--text-body);3 unmodified linesbackground: var(--surface);border: 1px solid var(--border);border-radius: var(--radius);padding: 0.85rem 1rem;display: flex;flex-direction: column;gap: 0.65rem;}.connect-head {display: flex;align-items: center;justify-content: space-between;gap: 0.65rem;flex-wrap: wrap;}13 unmodified linesalign-items: center;justify-content: center;margin: 0;padding: 0.3rem 0.62rem;border: 0;border-radius: 4px;background: transparent;2 unmodified linesfont-size: var(--text-sm);font-weight: 500;cursor: pointer;white-space: nowrap;transition: background-color 150ms var(--ease), color 150ms var(--ease);}19 unmodified lines.command-code {flex: 1;min-width: 0;padding: 0.54rem 0.72rem;background: var(--surface-subtle);border: 1px solid var(--border);border-radius: var(--radius-sm);8 unmodified linesdisplay: inline-flex;align-items: center;justify-content: center;padding: 0.5rem 0.95rem;border: 1px solid var(--accent);border-radius: var(--radius-sm);background: var(--accent);19 unmodified linesdisplay: inline-flex;align-items: center;justify-content: center;padding: 0.46rem 0.82rem;border: 1px solid var(--border-strong);border-radius: var(--radius-sm);background: var(--surface);11 unmodified linesborder-color: var(--ink);}.btn-waiting {display: inline-flex;align-items: center;justify-content: center;padding: 0.46rem 0.82rem;border: 1px solid var(--border);border-radius: var(--radius-sm);background: var(--surface-subtle);color: var(--muted);font-family: var(--font-sans);font-size: var(--text-sm);font-weight: 500;cursor: pointer;white-space: nowrap;transition: background-color 160ms var(--ease), border-color 160ms var(--ease), color 160ms var(--ease);}.btn-waiting:hover {border-color: var(--border-strong);color: var(--ink);}.btn-danger {display: inline-flex;align-items: center;justify-content: center;padding: 0.46rem 0.82rem;border: 1px solid #e6b4a8;border-radius: var(--radius-sm);background: var(--warm-soft);12 unmodified lines}.toast {min-height: 1.2rem;font-size: var(--text-sm);color: var(--ok);font-weight: 500;}/* Compact live hardware-styled oscilloscope monitor */.scope-unit {background: var(--surface);border: 1px solid var(--border);border-radius: var(--radius);padding: 0.85rem;display: flex;flex-direction: column;justify-content: space-between;gap: 0.75rem;}.scope-screen {background: var(--scope-bg);border: 1px solid var(--scope-border);border-radius: var(--radius-sm);padding: 0.55rem 0.65rem 0.45rem;display: flex;flex-direction: column;gap: 0.35rem;}.scope-screen-head {display: flex;align-items: center;justify-content: space-between;gap: 0.5rem;font-family: var(--font-mono);font-size: var(--text-sm);color: var(--scope-muted);}.scope-leds {display: inline-flex;align-items: center;gap: 0.85rem;}.led-item {display: inline-flex;align-items: center;gap: 0.35rem;color: var(--scope-muted);transition: color 180ms var(--ease);}.led-dot {width: 7px;height: 7px;border-radius: 50%;background: #28354d;transition: background-color 160ms var(--ease), box-shadow 160ms var(--ease);}.led-item.lit-emit {color: var(--scope-ink);}.led-item.lit-emit .led-dot {background: var(--scope-emit);box-shadow: 0 0 8px rgba(59, 130, 246, 0.9);}.led-item.lit-poll {color: var(--scope-ink);}.led-item.lit-poll .led-dot {background: var(--scope-poll);box-shadow: 0 0 8px rgba(52, 211, 153, 0.9);}.led-item.lit-fault {color: var(--scope-ink);}.led-item.lit-fault .led-dot {background: var(--scope-fault);box-shadow: 0 0 8px rgba(249, 115, 22, 0.9);}.scope-canvas {width: 100%;height: 86px;display: block;}.scope-readout {display: grid;grid-template-columns: repeat(3, minmax(0, 1fr));gap: 0.5rem;font-variant-numeric: tabular-nums;}.readout-label {display: block;font-size: var(--text-sm);color: var(--muted);}.readout-value {display: block;font-family: var(--font-mono);font-size: var(--text-body);font-weight: 500;color: var(--ink);}.scope-status-line {font-family: var(--font-mono);font-size: var(--text-sm);color: var(--muted);padding-top: 0.55rem;border-top: 1px solid var(--border);white-space: nowrap;overflow: hidden;text-overflow: ellipsis;}/* Sections */1 unmodified linebackground: var(--surface);border: 1px solid var(--border);border-radius: var(--radius);padding: 1.25rem 1.4rem;}.section-head {2 unmodified linesjustify-content: space-between;gap: 1rem;flex-wrap: wrap;margin-bottom: 0.85rem;}h2 {21 unmodified linesgrid-template-columns: minmax(0, 1fr) auto;gap: 0.75rem 1.25rem;align-items: center;padding: 0.9rem 0;border-top: 1px solid var(--border);}.prompt-row:first-child {padding-top: 0.2rem;border-top: 0;}1 unmodified linepadding-bottom: 0;}.prompt-row > div {min-width: 0;}.prompt-title {margin: 0 0 0.2rem;font-size: var(--text-body);1 unmodified linecolor: var(--ink);}.prompt-text {margin: 0 0 0.28rem;font-family: var(--font-mono);15 unmodified linescolor: var(--muted);}.prompt-actions {display: flex;flex-wrap: wrap;gap: 0.5rem;align-items: center;justify-content: flex-end;}/* Control deck */.deck-grid {display: grid;4 unmodified lines.deck-col {display: flex;flex-direction: column;gap: 0.7rem;}.deck-col + .deck-col {45 unmodified linesinput[type="text"],input[type="number"] {width: 100%;padding: 0.46rem 0.62rem;border: 1px solid var(--border-strong);border-radius: var(--radius-sm);background: var(--surface);14 unmodified linesflex-wrap: wrap;gap: 0.6rem;align-items: center;margin-top: 0.1rem;}.fault-bar {margin-top: 1.15rem;padding-top: 1rem;border-top: 1px solid var(--border);display: flex;flex-direction: column;gap: 0.75rem;}.fault-controls {display: flex;flex-wrap: wrap;gap: 0.75rem 1rem;4 unmodified lines.fault-group {display: flex;flex-wrap: wrap;gap: 0.5rem;align-items: flex-end;}.fault-notes {display: grid;grid-template-columns: repeat(2, minmax(0, 1fr));gap: 0.5rem 1.5rem;font-size: var(--text-sm);color: var(--muted);}.fault-notes p {margin: 0;}.fault-notes strong {color: var(--ink);font-weight: 500;}.fault-notes code {font-family: var(--font-mono);color: var(--ink);}/* Activity inspector */.inspector-grid {display: grid;7 unmodified lines}.log-list {margin-top: 0.6rem;display: flex;flex-direction: column;}.log-item {padding: 0.55rem 0;border-top: 1px solid var(--border);display: flex;flex-direction: column;36 unmodified lines}.empty-state {margin: 0.65rem 0 0;font-size: var(--text-sm);color: var(--muted);}pre.raw-json {margin: 0.6rem 0 0;padding: 0.85rem;border-radius: var(--radius-sm);background: var(--scope-bg);15 unmodified linesgap: 0.75rem;font-size: var(--text-sm);color: var(--muted);padding-top: 0.2rem;}.footer code {1 unmodified linecolor: var(--ink);}@media (max-width: 880px) {.opening {grid-template-columns: 1fr;gap: 1.1rem;}.deck-grid,.inspector-grid,.fault-notes {grid-template-columns: 1fr;}.deck-col + .deck-col,.inspector-col + .inspector-col {padding-left: 0;padding-top: 1.15rem;border-left: 0;border-top: 1px solid var(--border);}}@media (max-width: 640px) {8 unmodified lines.nav {gap: 1rem;}.page {padding: 1.15rem 1rem 2.25rem;}.section {padding: 1.05rem 1rem;}.prompt-row {grid-template-columns: 1fr;}.prompt-actions {justify-content: flex-start;}.command-row {flex-direction: column;align-items: stretch;}.segmented {max-width: 100%;overflow-x: auto;}}@media (prefers-reduced-motion: reduce) {24 unmodified lines<main class="page"><section class="opening"><div class="opening-left"><h1>Test MCP event polling live</h1><p class="opening-lead">Trigger server events in your isolated room and watch fast-agent wake from idle, catch up after gaps, and handle revoked streams.</p><div class="connect-panel"><div class="connect-head"><div class="segmented" role="tablist" aria-label="Connection command format"><button type="button" role="tab" aria-selected="true" data-cmd="uvx" onclick="setCmdMode('uvx')">uvx</button><button type="button" role="tab" aria-selected="false" data-cmd="go" onclick="setCmdMode('go')">fast-agent go</button><button type="button" role="tab" aria-selected="false" data-cmd="connect" onclick="setCmdMode('connect')">/mcp connect</button><button type="button" role="tab" aria-selected="false" data-cmd="url" onclick="setCmdMode('url')">URL</button></div><span class="toast" id="toast" role="status" aria-live="polite"></span></div>4 unmodified lines</div></div><aside class="scope-unit" aria-label="Live signal monitor"><div class="scope-screen"><div class="scope-screen-head"><span>Signal monitor</span><div class="scope-leds"><span class="led-item" id="led-emit"><span class="led-dot"></span>Emit</span><span class="led-item" id="led-poll"><span class="led-dot"></span>Poll</span></div></div><svg class="scope-canvas" id="scope-svg" viewBox="0 0 420 86" role="img" aria-label="Live waveform showing emitted events in blue and incoming client polls in green"><!-- Subtle reticle grid --><line x1="0" y1="22" x2="420" y2="22" stroke="#182235" stroke-width="1" /><line x1="0" y1="44" x2="420" y2="44" stroke="#1f2d45" stroke-width="1" /><line x1="0" y1="66" x2="420" y2="66" stroke="#182235" stroke-width="1" /><line x1="105" y1="0" x2="105" y2="86" stroke="#182235" stroke-width="1" /><line x1="210" y1="0" x2="210" y2="86" stroke="#182235" stroke-width="1" /><line x1="315" y1="0" x2="315" y2="86" stroke="#182235" stroke-width="1" /><!-- Traces updated live --><polyline id="trace-emit" fill="none" stroke="#3b82f6" stroke-width="2" stroke-linejoin="round" points="0,44 420,44" /><polyline id="trace-poll" fill="none" stroke="#34d399" stroke-width="1.8" stroke-linejoin="round" points="0,66 420,66" /></svg></div><div class="scope-readout"><div><span class="readout-label">Events</span><span class="readout-value" id="metric-events">0</span></div><div><span class="readout-label">Polls</span><span class="readout-value" id="metric-polls">0</span></div><div><span class="readout-label">nextPollMs</span><span class="readout-value" id="metric-interval">2000 ms</span></div></div><div class="scope-status-line" id="scope-status">Waiting for a client to poll this room</div></aside></section><section class="section"><div class="section-head"><h2>Prompts to try in fast-agent</h2><p class="section-note">Trigger buttons activate as soon as fast-agent starts polling the matching stream.</p></div><div class="prompt-list">1 unmodified line<div><p class="prompt-title">Wake on heartbeat</p><code class="prompt-text" id="prompt-1">Register for the heartbeat and tell me an interesting fact when it triggers.</code><p class="prompt-step" id="hint-hb">Waiting for a system.heartbeat poll, or click Send heartbeat anytime.</p></div><div class="prompt-actions"><button type="button" class="btn-secondary" onclick="copyPrompt('prompt-1')">Copy prompt</button><button type="button" class="btn-waiting" id="trigger-hb" onclick="emitHB()">Send heartbeat</button></div></div><div class="prompt-row"><div><p class="prompt-title">Follow a job to completion</p><code class="prompt-text" id="prompt-2">Start job-1 for "nightly fine-tune", subscribe to job.status_changed for it, and summarize the run once it finishes.</code><p class="prompt-step" id="hint-job">Waiting for a job.status_changed poll, then emit running and done.</p></div><div class="prompt-actions"><button type="button" class="btn-secondary" onclick="copyPrompt('prompt-2')">Copy prompt</button><button type="button" class="btn-waiting" id="trigger-job-run" onclick="emitQuickJob('running')">Emit running</button><button type="button" class="btn-waiting" id="trigger-job-done" onclick="emitQuickJob('done')">Emit done</button></div></div><div class="prompt-row"><div><p class="prompt-title">Recover from a skipped-event gap</p><code class="prompt-text" id="prompt-3">Watch job-1 and if the server reports truncated events, fetch full job details to catch up.</code><p class="prompt-step">Sets truncated: true on the next poll so fast-agent knows events were skipped and calls get_job_details.</p></div><div class="prompt-actions"><button type="button" class="btn-secondary" onclick="copyPrompt('prompt-3')">Copy prompt</button><button type="button" class="btn-waiting" id="trigger-gap" onclick="armGap()">Arm truncated gap</button></div></div><div class="prompt-row"><div><p class="prompt-title">Test passive buffering or revocation</p><code class="prompt-text" id="prompt-4">Subscribe passively (wake=false) to system.heartbeat and hold updates until I ask.</code><p class="prompt-step">Send heartbeats to queue events without waking, or revoke the job stream to test -32024 Forbidden.</p></div><div class="prompt-actions"><button type="button" class="btn-secondary" onclick="copyPrompt('prompt-4')">Copy prompt</button><button type="button" class="btn-waiting" id="trigger-revoke" onclick="armTerm()">Revoke job</button></div></div></div></section>1 unmodified line<section class="section"><div class="section-head"><h2>Event control deck</h2><p class="section-note">Custom payloads, poll interval, and fault injection for this room.</p></div><div class="deck-grid">33 unmodified lines</div><div class="fault-bar"><div class="fault-controls"><div class="fault-group"><div class="field field-compact"><label for="poll-ms">nextPollMs</label><input id="poll-ms" type="number" value="2000" min="250" max="300000" step="250"></div><button type="button" class="btn-secondary" onclick="setPollMs()">Apply</button></div><div class="fault-group"><button type="button" class="btn-secondary" onclick="armGap()">Arm truncated gap</button><button type="button" class="btn-danger" onclick="armTerm()">Revoke job</button><button type="button" class="btn-secondary" onclick="unTerm()">Restore job</button><button type="button" class="btn-danger" onclick="resetAll()">Reset room</button></div></div><div class="fault-notes"><p><strong>Arm truncated gap:</strong> marks the next <code>events/poll</code> response with <code>truncated: true</code>, simulating events that aged out of the server buffer so the agent knows to re-fetch state via <code>get_job_details</code>.</p><p><strong>Revoke job:</strong> returns <code>-32024 Forbidden</code> on the next poll for this job so fast-agent terminates the subscription cleanly.</p></div></div></section>46 unmodified linesconst apiPrefix = roomId === 'public' ? '' : '/r/' + encodeURIComponent(roomId);const mcpUrl = window.location.origin + apiPrefix + '/mcp';let cmdMode = 'uvx';let activeJobId = null;document.getElementById('header-room').textContent = 'room: ' + roomId;document.getElementById('footer-room').textContent = roomId;// -----------------------------------------------------------------------// Live oscilloscope waveform (scrolling SVG trace)// -----------------------------------------------------------------------const SAMPLES = 84;const emitBuf = new Array(SAMPLES).fill(0);const pollBuf = new Array(SAMPLES).fill(0);const emitQueue = [];const pollQueue = [];const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;function flashLed(kind) {const el = document.getElementById(kind === 'emit' ? 'led-emit' : 'led-poll');if (!el) return;const cls = kind === 'emit' ? 'lit-emit' : (kind === 'fault' ? 'lit-fault' : 'lit-poll');el.classList.remove('lit-emit', 'lit-poll', 'lit-fault');void el.offsetWidth;el.classList.add(cls);setTimeout(() => el.classList.remove(cls), 520);}function pushPulse(kind) {if (kind === 'emit') {emitQueue.push(1, 1, 1, 1, 0);flashLed('emit');} else if (kind === 'fault') {pollQueue.push(-1, 1, -1, 0);flashLed('fault');} else {pollQueue.push(1, 1, 0);flashLed('poll');}if (reducedMotion) renderWaveforms();}function renderWaveforms() {const step = 420 / (SAMPLES - 1);const emitPts = emitBuf.map((v, i) => (i * step).toFixed(1) + ',' + (44 - v * 22).toFixed(1)).join(' ');const pollPts = pollBuf.map((v, i) => (i * step).toFixed(1) + ',' + (66 - v * 16).toFixed(1)).join(' ');document.getElementById('trace-emit').setAttribute('points', emitPts);document.getElementById('trace-poll').setAttribute('points', pollPts);}if (!reducedMotion) {setInterval(() => {emitBuf.shift();emitBuf.push(emitQueue.length ? emitQueue.shift() : 0);pollBuf.shift();pollBuf.push(pollQueue.length ? pollQueue.shift() : 0);renderWaveforms();}, 65);}// -----------------------------------------------------------------------// Connection command bar// -----------------------------------------------------------------------function getCommandText(mode) {if (mode === 'uvx') return 'uvx fast-agent-mcp@latest go --url ' + mcpUrl;if (mode === 'go') return 'fast-agent go --url ' + mcpUrl;if (mode === 'connect') return '/mcp connect ' + mcpUrl + ' --name playground';return mcpUrl;}function setCmdMode(mode) {18 unmodified linessetTimeout(() => { if (el.textContent === msg) el.textContent = ''; }, 2600);}async function copyText(text, label) {try {await navigator.clipboard.writeText(text);12 unmodified linesif (el) copyText(el.textContent.trim(), 'Prompt copied');}// -----------------------------------------------------------------------// Control plane actions// -----------------------------------------------------------------------async function post(path, body = {}) {const r = await fetch(apiPrefix + path, {method: 'POST',6 unmodified lines}function jobId() { return document.getElementById('job').value.trim() || 'job-1'; }function targetJobId() { return activeJobId || jobId(); }function detail() { return document.getElementById('detail').value; }function selectedStage() {const checked = document.querySelector('input[name="stage"]:checked');return checked ? checked.value : 'running';}async function emitQuickJob(stage) {const target = targetJobId();const res = await post('/emit', {event_name: 'job.status_changed',job_id: target,stage,detail: stage === 'done' ? 'completed cleanly' : 'in progress',});toast('Emitted ' + res.event_id + ' (' + target + ': ' + stage + ')');}async function emitSelectedJob() {const stage = selectedStage();const res = await post('/emit', {2 unmodified linesstage,detail: detail(),});toast('Emitted ' + res.event_id + ' (' + stage + ')');}4 unmodified linesfilter_key: '*',data: { seq: Date.now(), note },});toast('Emitted ' + res.event_id + ' (system.heartbeat)');}async function armGap() {const target = targetJobId();await post('/emit-gap', { event_name: 'job.status_changed', job_id: target });toast('Armed truncated gap for ' + target);}async function armTerm() {const target = targetJobId();await post('/terminate', { event_name: 'job.status_changed', job_id: target });toast('Revoked subscription for ' + target);}async function unTerm() {const target = targetJobId();await post('/unterminate', { event_name: 'job.status_changed', job_id: target });toast('Restored subscription for ' + target);}async function setPollMs() {4 unmodified linesasync function resetAll() {await post('/reset');toast('Room streams and poll logs cleared');}// -----------------------------------------------------------------------// Contextual prompt button activation & activity rendering// -----------------------------------------------------------------------function setTriggerActive(id, active, activeClass = 'btn-primary') {const btn = document.getElementById(id);if (!btn) return;btn.className = active ? activeClass : 'btn-waiting';}function updateSubscriptionStates(activeStreams) {const list = activeStreams || [];const hbActive = list.some((s) => s.startsWith('system.heartbeat:'));const jobStream = list.find((s) => s.startsWith('job.status_changed:'));const jobActive = Boolean(jobStream);activeJobId = jobStream ? jobStream.slice('job.status_changed:'.length) : null;setTriggerActive('trigger-hb', hbActive, 'btn-primary');setTriggerActive('trigger-job-run', jobActive, 'btn-primary');setTriggerActive('trigger-job-done', jobActive, 'btn-primary');setTriggerActive('trigger-gap', jobActive, 'btn-primary');setTriggerActive('trigger-revoke', jobActive, 'btn-danger');document.getElementById('hint-hb').textContent = hbActive? 'Client is polling system.heartbeat. Click Send heartbeat to wake the agent.': 'Waiting for a system.heartbeat poll, or click Send heartbeat anytime.';document.getElementById('hint-job').textContent = jobActive? 'Client is polling job.status_changed (' + activeJobId + '). Emit running or done.': 'Waiting for a job.status_changed poll, then emit running and done.';const statusEl = document.getElementById('scope-status');if (list.length) {statusEl.textContent = 'Polling: ' + list.join(', ');} else {statusEl.textContent = 'Waiting for a client to poll this room';}}function shortTime(iso) {if (!iso) return '';const d = new Date(iso);57 unmodified linesconst r = await fetch(apiPrefix + '/stats');const data = await r.json();document.getElementById('metric-events').textContent = String(data.event_count || 0);document.getElementById('metric-polls').textContent = String(data.poll_count || 0);document.getElementById('metric-interval').textContent = String(data.poll_interval_ms) + ' ms';updateSubscriptionStates(data.active_streams);renderFormatted(data);document.getElementById('events-raw').textContent = JSON.stringify({room_id: data.room_id,poll_interval_ms: data.poll_interval_ms,active_streams: data.active_streams,streams: data.streams,pending_gaps: data.pending_gaps,forbidden: data.forbidden,8 unmodified lines}}function connectStream() {if (typeof EventSource === 'undefined') return;const es = new EventSource(apiPrefix + '/stream');es.onmessage = (ev) => {try {const msg = JSON.parse(ev.data);if (msg.kind === 'emit' || msg.kind === 'poll' || msg.kind === 'fault') {pushPulse(msg.kind);refresh();} else if (msg.kind === 'state') {refresh();}} catch {refresh();}};}setCmdMode('uvx');setInterval(refresh, 4000);refresh();window.addEventListener('load', () => setTimeout(connectStream, 150));</script></body></html>51 unmodified linesRoute("/", http_root, methods=["GET"]),Route("/new", http_root, methods=["GET"]),Route("/r/{room_id}", http_room_index, methods=["GET"]),Route("/health", http_health, methods=["GET"]),# Room-scoped control planeRoute("/r/{room_id}/emit", http_emit, methods=["POST"]),3 unmodified linesRoute("/r/{room_id}/config", http_config, methods=["POST"]),Route("/r/{room_id}/reset", http_reset, methods=["POST"]),Route("/r/{room_id}/stats", http_stats, methods=["GET"]),Route("/r/{room_id}/stream", http_stream, methods=["GET"]),# Public fallback control plane (backwards compatible)Route("/emit", http_emit, methods=["POST"]),Route("/emit-gap", http_gap, methods=["POST"]),2 unmodified linesRoute("/config", http_config, methods=["POST"]),Route("/reset", http_reset, methods=["POST"]),Route("/stats", http_stats, methods=["GET"]),Route("/stream", http_stream, methods=["GET"]),*mcp_app.routes,],)
Dockerfile-1
__pycache__/app.cpython-315.pycAdded
app.py+510-239
static/instrument.webpDeleted