Deploy 2026-06-12
Browse filesCo-authored-by: OpenAI Codex <codex@openai.com>
Files changed (43)
- AGENTS.md+1
- agent/README.md+1-1
- agent/core/agent_loop.py-11
- agent/core/hf_access.py-13
- agent/core/hf_router_catalog.py-14
- agent/core/model_ids.py-2
- agent/core/session.py+17-21
- agent/core/session_persistence.py-7
- agent/core/session_uploader.py+25
- agent/core/telemetry.py-24
- agent/core/tools.py-6
- agent/core/usage_metrics.pyAdded+448
- agent/core/usage_thresholds.py+1-3
- agent/tools/hf_repo_files_tool.py+1-3
- agent/tools/hf_repo_git_tool.py+1-18
- agent/tools/jobs_tool.py+1-19
- agent/tools/papers_tool.py-13
- agent/tools/private_hf_repo_tools.pyDeleted-650
- agent/tools/sandbox_client.py-27
- agent/tools/sandbox_tool.py+1-64
- agent/utils/particle_logo.py-4
- backend/dependencies.py-53
- backend/main.py+27-9
- backend/models.py-1
- backend/routes/agent.py+41-7
- backend/session_manager.py+73-21
- backend/usage.py+68-77
- frontend/src/components/Chat/ThinkingIndicator.tsxDeleted-48
- frontend/src/components/UsageMeter.tsx+1-1
- frontend/src/theme.ts-3
- frontend/src/types/agent.ts-7
- frontend/src/types/events.ts-65
- pyproject.toml-1
- scripts/sweep_orphan_sandboxes.py-1
- tests/integration/test_live_thinking_models.py+3-3
- tests/unit/test_auto_approval_policy.py-3
- tests/unit/test_hf_access.py-28
- tests/unit/test_sandbox_auto_start.py+11-5
- tests/unit/test_sandbox_private_spaces.py-27
- tests/unit/test_session_manager_persistence.py+177
- tests/unit/test_session_uploader.py+98
- tests/unit/test_usage.py+292
- uv.lock-2
13 unmodified lines14151617181913 unmodified lines- If `127.0.0.1:7860` is already owned by another local process, binding the backend to `::1` lets the Vite proxy resolve `localhost` cleanly.- Prefer `npm ci` over `npm install` for setup, since `npm install` may rewrite `frontend/package-lock.json` metadata depending on npm version.- Non-local LLM calls use `https://router.huggingface.co/v1` with the active Hugging Face user's token. Web sessions default to Kimi K2.6 for free users and Claude Opus 4.8 for Pro users; the CLI default is Claude Opus 4.8. For local development, set `HF_TOKEN` and optionally `ML_INTERN_DEFAULT_MODEL_ID`.- When debugging a web app issue tied to a session ID, inspect the session data in `smolagents/ml-intern-sessions` for additional context.## Development Checks13 unmodified lines1415161718192013 unmodified lines- If `127.0.0.1:7860` is already owned by another local process, binding the backend to `::1` lets the Vite proxy resolve `localhost` cleanly.- Prefer `npm ci` over `npm install` for setup, since `npm install` may rewrite `frontend/package-lock.json` metadata depending on npm version.- Non-local LLM calls use `https://router.huggingface.co/v1` with the active Hugging Face user's token. Web sessions default to Kimi K2.6 for free users and Claude Opus 4.8 for Pro users; the CLI default is Claude Opus 4.8. For local development, set `HF_TOKEN` and optionally `ML_INTERN_DEFAULT_MODEL_ID`.- When asked to start the local server, export the GitHub CLI token first with `export GITHUB_TOKEN="$(gh auth token)"`.- When debugging a web app issue tied to a session ID, inspect the session data in `smolagents/ml-intern-sessions` for additional context.## Development Checks
6 unmodified lines789101112136 unmodified lines**Queue-based async system:**- Submissions in (user input) → Agent Loop → Events output for possible UI updates- Session maintains state (context + tools) for possible future Context Engineering- Handlers operations like (USER_INPUT, INTERRUPT, COMPACT, UNDO, SHUTDOWN) for possible UI control## Components6 unmodified lines789101112136 unmodified lines**Queue-based async system:**- Submissions in (user input) → Agent Loop → Events output for possible UI updates- Session maintains state (context + tools) for possible future Context Engineering- Handlers operations like (USER_INPUT, COMPACT, UNDO, SHUTDOWN) for possible UI control## Components
323 unmodified lines324325326327328329330331332333334335336337338339340323 unmodified linesreturn Falsedef _needs_approval(tool_name: str, tool_args: dict, config: Config | None = None) -> bool:"""Legacy sync approval predicate used by tests and CLI display helpers."""if _is_scheduled_hf_job_run(tool_name, tool_args):return Trueif config and config.yolo_mode:return Falsereturn _base_needs_approval(tool_name, tool_args, config)def _session_auto_approval_enabled(session: Session | None) -> bool:return bool(session and getattr(session, "auto_approval_enabled", False))323 unmodified lines324325326327328329323 unmodified linesreturn Falsedef _session_auto_approval_enabled(session: Session | None) -> bool:return bool(session and getattr(session, "auto_approval_enabled", False))
20 unmodified lines212223242526274 unmodified lines3233343536373887 unmodified lines12612712812913013113213313413513613713813914014114220 unmodified linesHF_PRO_SUBSCRIBE_URL = "https://huggingface.co/subscribe/pro"HfUserPlan = Literal["free", "pro"]HfUserPlanStatus = Literal["free", "pro", "unknown"]@dataclass(frozen=True)4 unmodified linesorg_names: list[str]eligible_namespaces: list[str]default_namespace: str | Noneaccess_known: bool = Trueclass JobsAccessError(Exception):87 unmodified linesreturn Noneasync def fetch_hf_user_plan(token: str | None,timeout: float = 5.0,) -> HfUserPlanStatus:"""Return the token owner's HF plan, or ``unknown`` if lookup fails."""if not token:return "unknown"whoami = await fetch_whoami_v2(token, timeout=timeout)return normalize_hf_user_plan(whoami) or "unknown"async def get_jobs_access(token: str) -> JobsAccess | None:whoami = await fetch_whoami_v2(token)if whoami is None:20 unmodified lines2122232425264 unmodified lines31323334353687 unmodified lines12412512612712812920 unmodified linesHF_PRO_SUBSCRIBE_URL = "https://huggingface.co/subscribe/pro"HfUserPlan = Literal["free", "pro"]@dataclass(frozen=True)4 unmodified linesorg_names: list[str]eligible_namespaces: list[str]default_namespace: str | Noneclass JobsAccessError(Exception):87 unmodified linesreturn Noneasync def get_jobs_access(token: str) -> JobsAccess | None:whoami = await fetch_whoami_v2(token)if whoami is None:
6 unmodified lines7891011121328 unmodified lines424344454647485 unmodified lines545556575859606162636432 unmodified lines97989910010110210310410513 unmodified lines1191201211221231241251261271286 unmodified lines• Validate ``/model`` switches with live data instead of a hard-coded allowlist.• Show the user which providers serve a model, at what price, and whether theysupport tool calls.• Derive a reasonable context-window limit for any routed model.The listing is cached in-memory for a few minutes so repeated lookups during asession are free. On fetch failure we return stale data if we have it, or an28 unmodified linesinput_price: Optional[float]output_price: Optional[float]supports_tools: boolsupports_structured_output: bool@dataclass5 unmodified linesdef live_providers(self) -> list[ProviderInfo]:return [p for p in self.providers if p.status == "live"]@propertydef max_context_length(self) -> Optional[int]:lengths = [p.context_length for p in self.live_providers if p.context_length]return max(lengths) if lengths else None@propertydef any_supports_tools(self) -> bool:return any(p.supports_tools for p in self.live_providers)32 unmodified linesinput_price=pricing.get("input"),output_price=pricing.get("output"),supports_tools=bool(p.get("supports_tools", False)),supports_structured_output=bool(p.get("supports_structured_output", False)),))return ModelInfo(id=entry.get("id", ""), providers=providers)13 unmodified linesreturn Nonedef last_fetch_error() -> Optional[str]:return _last_fetch_errordef fuzzy_suggest(model_id: str, limit: int = 3) -> list[str]:"""Return the closest model ids from the catalog."""bare = model_id.split(":", 1)[0]6 unmodified lines78910111228 unmodified lines4142434445465 unmodified lines52535455565732 unmodified lines90919293949513 unmodified lines1091101111121131146 unmodified lines• Validate ``/model`` switches with live data instead of a hard-coded allowlist.• Show the user which providers serve a model, at what price, and whether theysupport tool calls.The listing is cached in-memory for a few minutes so repeated lookups during asession are free. On fetch failure we return stale data if we have it, or an28 unmodified linesinput_price: Optional[float]output_price: Optional[float]supports_tools: bool@dataclass5 unmodified linesdef live_providers(self) -> list[ProviderInfo]:return [p for p in self.providers if p.status == "live"]@propertydef any_supports_tools(self) -> bool:return any(p.supports_tools for p in self.live_providers)32 unmodified linesinput_price=pricing.get("input"),output_price=pricing.get("output"),supports_tools=bool(p.get("supports_tools", False)),))return ModelInfo(id=entry.get("id", ""), providers=providers)13 unmodified linesreturn Nonedef fuzzy_suggest(model_id: str, limit: int = 3) -> list[str]:"""Return the closest model ids from the catalog."""bare = model_id.split(":", 1)[0]
9 unmodified lines10111213141516179 unmodified linesGLM_51_MODEL_ID = "zai-org/GLM-5.1:novita"DEEPSEEK_V4_PRO_MODEL_ID = "deepseek-ai/DeepSeek-V4-Pro:novita"DEFAULT_MODEL_ID = CLAUDE_OPUS_48_MODEL_IDHOSTED_MODEL_IDS = {CLAUDE_OPUS_48_MODEL_ID,GPT_55_MODEL_ID,9 unmodified lines1011121314159 unmodified linesGLM_51_MODEL_ID = "zai-org/GLM-5.1:novita"DEEPSEEK_V4_PRO_MODEL_ID = "deepseek-ai/DeepSeek-V4-Pro:novita"HOSTED_MODEL_IDS = {CLAUDE_OPUS_48_MODEL_ID,GPT_55_MODEL_ID,
79 unmodified lines8081828384858675 unmodified lines162163164165166167299 unmodified lines46746846947047147262 unmodified lines5355365375385395402 unmodified lines54354454554654754865 unmodified lines61461561661761861962062162262362462562662762862963063163263363463563663763863979 unmodified linesclass OpType(Enum):USER_INPUT = "user_input"EXEC_APPROVAL = "exec_approval"INTERRUPT = "interrupt"UNDO = "undo"COMPACT = "compact"NEW = "new"75 unmodified linesself.usage_warning_next_threshold_usd: float = USAGE_WARNING_FIRST_THRESHOLD_USDself.usage_threshold_checker: Any | None = Noneself.yolo_budget_checker: Any | None = None# Session trajectory loggingself.logged_events: list[dict] = []299 unmodified linesself.pending_approval = Noneself.auto_approval_estimated_spend_usd = 0.0self._yolo_budget_reservations = {}self.reset_cancel()# Previous-session metadata is intentionally included for event62 unmodified linesfor e in self.logged_eventsif e.get("event_type") == "llm_call")return {"session_id": self.session_id,"user_id": self.user_id,2 unmodified lines"session_end_time": datetime.now().isoformat(),"model_name": self.config.model_name,"total_cost_usd": total_cost_usd,"messages": [msg.model_dump() for msg in self.context_manager.items],"events": self.logged_events,"tools": tools,65 unmodified lineslogger.error(f"Failed to save session locally: {e}")return Nonedef update_local_save_status(self, filepath: str, upload_status: str, dataset_url: Optional[str] = None) -> bool:"""Update the upload status of an existing local save file"""try:with open(filepath, "r") as f:data = json.load(f)data["upload_status"] = upload_statusdata["upload_url"] = dataset_urldata["last_save_time"] = datetime.now().isoformat()with open(filepath, "w") as f:json.dump(data, f, indent=2)return Trueexcept Exception as e:logger.error(f"Failed to update local save status: {e}")return Falsedef _personal_trace_repo_id(self) -> Optional[str]:"""Resolve the per-user trace repo id from config + HF username.79 unmodified lines80818283848575 unmodified lines161162163164165166167168299 unmodified lines46846947047147247347447562 unmodified lines5385395405415425435445455465475485495505515525535545552 unmodified lines55855956056156256356465 unmodified lines63063163263363463579 unmodified linesclass OpType(Enum):USER_INPUT = "user_input"EXEC_APPROVAL = "exec_approval"UNDO = "undo"COMPACT = "compact"NEW = "new"75 unmodified linesself.usage_warning_next_threshold_usd: float = USAGE_WARNING_FIRST_THRESHOLD_USDself.usage_threshold_checker: Any | None = Noneself.yolo_budget_checker: Any | None = Noneself.usage_hf_billing_snapshot: dict[str, Any] | None = Noneself.usage_metrics: dict[str, Any] | None = None# Session trajectory loggingself.logged_events: list[dict] = []299 unmodified linesself.pending_approval = Noneself.auto_approval_estimated_spend_usd = 0.0self._yolo_budget_reservations = {}self.usage_hf_billing_snapshot = Noneself.usage_metrics = Noneself.reset_cancel()# Previous-session metadata is intentionally included for event62 unmodified linesfor e in self.logged_eventsif e.get("event_type") == "llm_call")try:from agent.core.usage_metrics import summarize_usage_eventsusage_metrics = summarize_usage_events(self.logged_events,session_id=self.session_id,hf_billing_snapshot=self.usage_hf_billing_snapshot,)self.usage_metrics = usage_metricsexcept Exception as e:logger.debug("Usage metrics summary failed for %s: %s", self.session_id, e)usage_metrics = self.usage_metrics or {}return {"session_id": self.session_id,"user_id": self.user_id,2 unmodified lines"session_end_time": datetime.now().isoformat(),"model_name": self.config.model_name,"total_cost_usd": total_cost_usd,"usage_metrics": usage_metrics,"messages": [msg.model_dump() for msg in self.context_manager.items],"events": self.logged_events,"tools": tools,65 unmodified lineslogger.error(f"Failed to save session locally: {e}")return Nonedef _personal_trace_repo_id(self) -> Optional[str]:"""Resolve the per-user trace repo id from config + HF username.
517 unmodified lines518519520521522523524525526527517 unmodified linesdb_name = os.environ.get("MONGODB_DB", "ml-intern")_store = MongoSessionStore(uri, db_name) if uri else NoopSessionStore()return _storedef _reset_store_for_tests(store: NoopSessionStore | MongoSessionStore | None = None,) -> None:global _store_store = store517 unmodified lines518519520517 unmodified linesdb_name = os.environ.get("MONGODB_DB", "ml-intern")_store = MongoSessionStore(uri, db_name) if uri else NoopSessionStore()return _store
25 unmodified lines262728293031229 unmodified lines2612622632642652662672682694 unmodified lines27427527627727827928025 unmodified linesfrom dotenv import load_dotenvload_dotenv()# Token resolution for the org KPI dataset. Fallback chain (least-privilege229 unmodified linesreturn scrubbeddef _write_row_payload(data: dict, tmp_path: str) -> None:"""Single-row JSONL (existing format) — used by KPI scheduler."""scrubbed = _scrub_session_for_upload(data)session_row = {"session_id": data["session_id"],"user_id": data.get("user_id"),4 unmodified lines"messages": json.dumps(scrubbed["messages"]),"events": json.dumps(scrubbed["events"]),"tools": json.dumps(scrubbed["tools"]),}with open(tmp_path, "w") as tmp:json.dump(session_row, tmp)25 unmodified lines2627282930313233343536229 unmodified lines2662672682692702712722732742752762772782792802812822832842852862872882892902912924 unmodified lines29729829930030130230330430525 unmodified linesfrom dotenv import load_dotenvfrom agent.core.usage_metrics import (summarize_usage_events,usage_metric_scalar_fields,)load_dotenv()# Token resolution for the org KPI dataset. Fallback chain (least-privilege229 unmodified linesreturn scrubbeddef _usage_metrics_for_row(data: dict) -> dict:metrics = data.get("usage_metrics")if isinstance(metrics, str):try:parsed = json.loads(metrics)metrics = parsed if isinstance(parsed, dict) else Noneexcept (json.JSONDecodeError, TypeError):metrics = Noneif isinstance(metrics, dict):return metricsevents = data.get("events")return summarize_usage_events(events if isinstance(events, list) else [],session_id=data.get("session_id"),)def _write_row_payload(data: dict, tmp_path: str) -> None:"""Single-row JSONL (existing format) — used by KPI scheduler."""scrubbed = _scrub_session_for_upload(data)usage_metrics = _usage_metrics_for_row(data)session_row = {"session_id": data["session_id"],"user_id": data.get("user_id"),4 unmodified lines"messages": json.dumps(scrubbed["messages"]),"events": json.dumps(scrubbed["events"]),"tools": json.dumps(scrubbed["tools"]),"usage_metrics": json.dumps(_scrub(usage_metrics)),}session_row.update(usage_metric_scalar_fields(usage_metrics))with open(tmp_path, "w") as tmp:json.dump(session_row, tmp)
325 unmodified lines326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355325 unmodified lineslogger.debug("record_feedback failed (non-fatal): %s", e)async def record_jobs_access_blocked(session: Any,*,tool_call_ids: list[str],plan: str,eligible_namespaces: list[str],) -> None:from agent.core.session import Eventtry:await session.send_event(Event(event_type="jobs_access_blocked",data={"tool_call_ids": tool_call_ids,"plan": plan,"eligible_namespaces": eligible_namespaces,},))except Exception as e:logger.debug("record_jobs_access_blocked failed (non-fatal): %s", e)async def record_pro_cta_click(session: Any,*,325 unmodified lines326327328329330331325 unmodified lineslogger.debug("record_feedback failed (non-fatal): %s", e)async def record_pro_cta_click(session: Any,*,
50 unmodified lines51525354555657585960616250 unmodified linesfrom agent.tools.sandbox_tool import get_sandbox_toolsfrom agent.tools.web_search_tool import WEB_SEARCH_TOOL_SPEC, web_search_handler# NOTE: Private HF repo tool disabled - replaced by hf_repo_files and hf_repo_git# from agent.tools.private_hf_repo_tools import (# PRIVATE_HF_REPO_TOOL_SPEC,# private_hf_repo_handler,# )# Suppress aiohttp deprecation warningwarnings.filterwarnings("ignore", category=DeprecationWarning, module="aiohttp.connector"50 unmodified lines51525354555650 unmodified linesfrom agent.tools.sandbox_tool import get_sandbox_toolsfrom agent.tools.web_search_tool import WEB_SEARCH_TOOL_SPEC, web_search_handler# Suppress aiohttp deprecation warningwarnings.filterwarnings("ignore", category=DeprecationWarning, module="aiohttp.connector"
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448"""Pure usage/billing summaries for session trajectory analytics."""
from collections import Counter, defaultdictfrom datetime import UTC, datetime, timedeltafrom math import isfinitefrom typing import Any
from agent.core.cost_estimation import SPACE_PRICE_USD_PER_HOUR
USAGE_METRICS_VERSION = 1BILLING_SCOPE_ACCOUNT_WINDOW_DELTA = "account_window_delta"
_USAGE_SCALAR_KEYS = ( "usage_total_usd", "usage_total_usd_source", "usage_app_total_usd", "usage_hf_billing_total_usd", "usage_llm_calls", "usage_total_tokens", "usage_hf_job_submits", "usage_hf_job_status_snapshots", "usage_sandbox_creates", "usage_sandbox_pairs",)
def _coerce_float(value: Any) -> float: if isinstance(value, bool) or value is None: return 0.0 try: parsed = float(value) except (TypeError, ValueError): return 0.0 return parsed if isfinite(parsed) else 0.0
def _coerce_optional_float(value: Any) -> float | None: if isinstance(value, bool) or value is None: return None try: parsed = float(value) except (TypeError, ValueError): return None return parsed if isfinite(parsed) else None
def _coerce_int(value: Any) -> int: if isinstance(value, bool) or value is None: return 0 try: return int(value) except (TypeError, ValueError): return 0
def _round_usd(value: Any) -> float: return round(_coerce_float(value), 6)
def _parse_timestamp(value: Any) -> datetime | None: if isinstance(value, datetime): dt = value elif isinstance(value, str) and value: try: dt = datetime.fromisoformat(value.replace("Z", "+00:00")) except ValueError: return None else: return None if dt.tzinfo is None: return dt.replace(tzinfo=UTC) return dt.astimezone(UTC)
def event_created_at(event: dict[str, Any]) -> datetime | None: return _parse_timestamp(event.get("created_at") or event.get("timestamp"))
def _event_data(event: dict[str, Any]) -> dict[str, Any]: data = event.get("data") or {} return data if isinstance(data, dict) else {}
def _has_number(value: Any) -> bool: return _coerce_optional_float(value) is not None
def _counter_dict(counter: Counter[str]) -> dict[str, int]: return dict(sorted(counter.items()))
def _empty_app_bucket(session_id: str | None) -> dict[str, Any]: return { "session_id": session_id, "total_usd": 0.0, "inference_usd": 0.0, "hf_jobs_estimated_usd": 0.0, "sandbox_estimated_usd": 0.0, "llm_calls": 0, "hf_jobs_count": 0, "sandbox_count": 0, "prompt_tokens": 0, "completion_tokens": 0, "cache_read_tokens": 0, "cache_creation_tokens": 0, "total_tokens": 0, "hf_jobs_billable_seconds_estimate": 0, "sandbox_billable_seconds_estimate": 0, }
def _sandbox_id(event: dict[str, Any]) -> str | None: sandbox_id = _event_data(event).get("sandbox_id") return sandbox_id if isinstance(sandbox_id, str) and sandbox_id else None
def _sandbox_duration_seconds( create_event: dict[str, Any], destroy_event: dict[str, Any],) -> int: create_data = _event_data(create_event) destroy_data = _event_data(destroy_event) lifetime_s = _coerce_int(destroy_data.get("lifetime_s")) if lifetime_s > 0: return lifetime_s
create_at = event_created_at(create_event) destroy_at = event_created_at(destroy_event) if create_at is None or destroy_at is None: return 0 create_latency_s = max(0, _coerce_int(create_data.get("create_latency_s"))) interval_start = create_at - timedelta(seconds=create_latency_s) if destroy_at <= interval_start: return 0 return int((destroy_at - interval_start).total_seconds())
def summarize_sandbox_lifecycle( lifecycle_events: list[tuple[int, dict[str, Any]]],) -> dict[str, Any]: """Pair sandbox lifecycle events and estimate billed usage.
Shared by dataset usage metrics and backend usage responses so sandbox pricing and create/destroy pairing semantics cannot drift. """ ordered_events = [ event for _, event in sorted( lifecycle_events, key=lambda indexed: ( event_created_at(indexed[1]) is None, event_created_at(indexed[1]) or datetime.min.replace(tzinfo=UTC), indexed[0], ), ) ] active_creates: dict[str, list[dict[str, Any]]] = defaultdict(list) matched_pairs = 0 unpaired_destroys = 0 estimated_usd = 0.0 billable_seconds = 0
for event in ordered_events: event_type = event.get("event_type") sandbox_id = _sandbox_id(event) if sandbox_id is None: continue if event_type == "sandbox_create": active_creates[sandbox_id].append(event) continue if event_type != "sandbox_destroy": continue
creates = active_creates.get(sandbox_id) if not creates: unpaired_destroys += 1 continue
create_event = creates.pop() if not creates: active_creates.pop(sandbox_id, None)
hardware = str(_event_data(create_event).get("hardware") or "cpu-basic") seconds = _sandbox_duration_seconds(create_event, event) price_usd_per_hour = _coerce_float(SPACE_PRICE_USD_PER_HOUR.get(hardware)) matched_pairs += 1 if price_usd_per_hour > 0: billable_seconds += seconds estimated_usd += price_usd_per_hour * (seconds / 3600)
return { "matched_pairs": matched_pairs, "unpaired_creates": sum(len(events) for events in active_creates.values()), "unpaired_destroys": unpaired_destroys, "estimated_usd": _round_usd(estimated_usd), "billable_seconds_estimate": billable_seconds, }
def normalize_hf_billing_snapshot(snapshot: dict[str, Any] | None) -> dict[str, Any]: """Return a dataset-safe HF billing snapshot.
Only current-session window rollups are retained. Monthly account totals, credit limits, and any caller-provided extra fields are intentionally dropped before the snapshot can be serialized into session artifacts. """ hf_billing = snapshot.get("hf_billing") if isinstance(snapshot, dict) else None hf_billing = hf_billing if isinstance(hf_billing, dict) else {} current_session = hf_billing.get("current_session") current_session = current_session if isinstance(current_session, dict) else None
sanitized_current = None if current_session is not None: sanitized_current = { "window_start": current_session.get("window_start"), "window_end": current_session.get("window_end"), "timezone": current_session.get("timezone"), "total_usd": _round_usd(current_session.get("total_usd")), "inference_providers_usd": _round_usd( current_session.get("inference_providers_usd") ), "hf_jobs_usd": _round_usd(current_session.get("hf_jobs_usd")), "inference_provider_requests": _coerce_int( current_session.get("inference_provider_requests") ), "hf_jobs_minutes": round( _coerce_float(current_session.get("hf_jobs_minutes")), 3 ), }
available = bool(hf_billing.get("available") and sanitized_current is not None) return { "billing_scope": BILLING_SCOPE_ACCOUNT_WINDOW_DELTA, "hf_billing": { "source": str(hf_billing.get("source") or "hf_billing_usage_v2"), "available": available, "error": None if available else hf_billing.get("error"), "current_session": sanitized_current if available else None, }, }
def summarize_usage_events( events: list[dict[str, Any]], *, session_id: str | None = None, hf_billing_snapshot: dict[str, Any] | None = None,) -> dict[str, Any]: app = _empty_app_bucket(session_id) llm_by_kind: Counter[str] = Counter() llm_by_model: Counter[str] = Counter() job_statuses: Counter[str] = Counter() job_submit_flavors: Counter[str] = Counter() job_status_flavors: Counter[str] = Counter() sandbox_hardware: Counter[str] = Counter() lifecycle_events: list[tuple[int, dict[str, Any]]] = []
event_count = 0 events_without_timestamp = 0 llm_calls_with_cost_usd = 0 llm_calls_with_nonzero_cost_usd = 0 job_submits = 0 job_status_snapshots = 0 job_snapshots_with_estimated_cost = 0 job_snapshots_with_nonzero_estimated_cost = 0 sandbox_creates = 0 sandbox_destroys = 0 turn_complete_count = 0 assistant_stream_end_count = 0
for index, event in enumerate(events or []): if not isinstance(event, dict): continue event_count += 1 if event_created_at(event) is None: events_without_timestamp += 1
event_type = event.get("event_type") data = _event_data(event) if event_type == "llm_call": app["llm_calls"] += 1 if "cost_usd" in data: llm_calls_with_cost_usd += 1 cost_usd = _coerce_float(data.get("cost_usd")) if cost_usd > 0: llm_calls_with_nonzero_cost_usd += 1 app["inference_usd"] += cost_usd
prompt_tokens = _coerce_int(data.get("prompt_tokens")) completion_tokens = _coerce_int(data.get("completion_tokens")) cache_read_tokens = _coerce_int(data.get("cache_read_tokens")) cache_creation_tokens = _coerce_int(data.get("cache_creation_tokens")) total_tokens = _coerce_int(data.get("total_tokens")) or ( prompt_tokens + completion_tokens + cache_read_tokens + cache_creation_tokens ) app["prompt_tokens"] += prompt_tokens app["completion_tokens"] += completion_tokens app["cache_read_tokens"] += cache_read_tokens app["cache_creation_tokens"] += cache_creation_tokens app["total_tokens"] += total_tokens llm_by_kind[str(data.get("kind") or "unknown")] += 1 llm_by_model[str(data.get("model") or "unknown")] += 1 elif event_type == "hf_job_submit": job_submits += 1 job_submit_flavors[str(data.get("flavor") or "unknown")] += 1 elif event_type == "hf_job_complete": job_status_snapshots += 1 app["hf_jobs_count"] += 1 estimated_cost = _coerce_float(data.get("estimated_cost_usd")) app["hf_jobs_estimated_usd"] += estimated_cost app["hf_jobs_billable_seconds_estimate"] += _coerce_int( data.get("billable_seconds_estimate") or data.get("wall_time_s") ) if _has_number(data.get("estimated_cost_usd")): job_snapshots_with_estimated_cost += 1 if estimated_cost > 0: job_snapshots_with_nonzero_estimated_cost += 1 job_statuses[str(data.get("final_status") or "unknown")] += 1 job_status_flavors[str(data.get("flavor") or "unknown")] += 1 elif event_type == "sandbox_create": sandbox_creates += 1 sandbox_hardware[str(data.get("hardware") or "cpu-basic")] += 1 lifecycle_events.append((index, event)) elif event_type == "sandbox_destroy": sandbox_destroys += 1 lifecycle_events.append((index, event)) elif event_type == "turn_complete": turn_complete_count += 1 elif event_type == "assistant_stream_end": assistant_stream_end_count += 1
sandbox = summarize_sandbox_lifecycle(lifecycle_events) app["sandbox_count"] = sandbox["matched_pairs"] app["sandbox_estimated_usd"] = sandbox["estimated_usd"] app["sandbox_billable_seconds_estimate"] = sandbox["billable_seconds_estimate"] app["inference_usd"] = _round_usd(app["inference_usd"]) app["hf_jobs_estimated_usd"] = _round_usd(app["hf_jobs_estimated_usd"]) app["total_usd"] = _round_usd( app["inference_usd"] + app["hf_jobs_estimated_usd"] + app["sandbox_estimated_usd"] )
billing = normalize_hf_billing_snapshot(hf_billing_snapshot) current_billing = billing["hf_billing"]["current_session"] hf_billing_total = None if billing["hf_billing"]["available"] and current_billing is not None: hf_billing_total = _round_usd(current_billing.get("total_usd")) usage_total = _round_usd(hf_billing_total + app["sandbox_estimated_usd"]) usage_total_source = "hf_billing_plus_sandbox_estimate" else: usage_total = app["total_usd"] usage_total_source = "app_telemetry_fallback"
job_flavors = job_submit_flavors + job_status_flavors
return { "version": USAGE_METRICS_VERSION, "session_id": session_id, "billing_scope": BILLING_SCOPE_ACCOUNT_WINDOW_DELTA, "total_usd": usage_total, "total_usd_source": usage_total_source, "app_total_usd": app["total_usd"], "hf_billing_total_usd": hf_billing_total, "app_telemetry": app, "hf_billing": billing["hf_billing"], "llm": { "calls": app["llm_calls"], "calls_by_kind": _counter_dict(llm_by_kind), "calls_by_model": _counter_dict(llm_by_model), "prompt_tokens": app["prompt_tokens"], "completion_tokens": app["completion_tokens"], "cache_read_tokens": app["cache_read_tokens"], "cache_creation_tokens": app["cache_creation_tokens"], "total_tokens": app["total_tokens"], }, "turns": { "turn_complete_count": turn_complete_count, "assistant_stream_end_count": assistant_stream_end_count, }, "hf_jobs": { "submits": job_submits, "status_snapshots": job_status_snapshots, "statuses": _counter_dict(job_statuses), "flavors": _counter_dict(job_flavors), "submit_flavors": _counter_dict(job_submit_flavors), "status_snapshot_flavors": _counter_dict(job_status_flavors), "estimated_usd": app["hf_jobs_estimated_usd"], "billable_seconds_estimate": app["hf_jobs_billable_seconds_estimate"], "snapshots_with_estimated_cost": job_snapshots_with_estimated_cost, "snapshots_with_nonzero_estimated_cost": ( job_snapshots_with_nonzero_estimated_cost ), }, "sandboxes": { "creates": sandbox_creates, "destroys": sandbox_destroys, "matched_pairs": sandbox["matched_pairs"], "unpaired_creates": sandbox["unpaired_creates"], "unpaired_destroys": sandbox["unpaired_destroys"], "hardware": _counter_dict(sandbox_hardware), "estimated_usd": app["sandbox_estimated_usd"], "billable_seconds_estimate": app["sandbox_billable_seconds_estimate"], }, "data_quality": { "event_count": event_count, "events_without_timestamp": events_without_timestamp, "llm_calls_with_cost_usd": llm_calls_with_cost_usd, "llm_calls_with_nonzero_cost_usd": llm_calls_with_nonzero_cost_usd, "job_snapshots_with_estimated_cost": job_snapshots_with_estimated_cost, "job_snapshots_missing_estimated_cost": ( job_status_snapshots - job_snapshots_with_estimated_cost ), }, }
def usage_metric_scalar_fields(metrics: dict[str, Any]) -> dict[str, Any]: app = metrics.get("app_telemetry") if isinstance(metrics, dict) else {} llm = metrics.get("llm") if isinstance(metrics, dict) else {} jobs = metrics.get("hf_jobs") if isinstance(metrics, dict) else {} sandboxes = metrics.get("sandboxes") if isinstance(metrics, dict) else {} values = { "usage_total_usd": metrics.get("total_usd"), "usage_total_usd_source": metrics.get("total_usd_source"), "usage_app_total_usd": metrics.get("app_total_usd"), "usage_hf_billing_total_usd": metrics.get("hf_billing_total_usd"), "usage_llm_calls": app.get("llm_calls") if isinstance(app, dict) else None, "usage_total_tokens": llm.get("total_tokens") if isinstance(llm, dict) else None, "usage_hf_job_submits": ( jobs.get("submits") if isinstance(jobs, dict) else None ), "usage_hf_job_status_snapshots": ( jobs.get("status_snapshots") if isinstance(jobs, dict) else None ), "usage_sandbox_creates": ( sandboxes.get("creates") if isinstance(sandboxes, dict) else None ), "usage_sandbox_pairs": ( sandboxes.get("matched_pairs") if isinstance(sandboxes, dict) else None ), } return {key: values.get(key) for key in _USAGE_SCALAR_KEYS}12345678910111213"""Helpers for session usage-threshold approval warnings."""from typing import Any, LiteralUSAGE_THRESHOLD_TOOL_NAME = "usage_threshold"USAGE_WARNING_FIRST_THRESHOLD_USD = 5.0USAGE_WARNING_MULTIPLIER = 2.0UsageApprovalContinuation = Literal["continue_agent", "complete_turn"]def normalize_usage_threshold(value: Any) -> float:"""Return a usable positive threshold, defaulting to the first warning."""1234567891011"""Helpers for session usage-threshold approval warnings."""from typing import AnyUSAGE_THRESHOLD_TOOL_NAME = "usage_threshold"USAGE_WARNING_FIRST_THRESHOLD_USD = 5.0USAGE_WARNING_MULTIPLIER = 2.0def normalize_usage_threshold(value: Any) -> float:"""Return a usable positive threshold, defaulting to the first warning."""
4 unmodified lines5678910111 unmodified line13141516171819204 unmodified lines"""import asynciofrom typing import Any, Dict, Literal, Optionalfrom huggingface_hub import HfApi, hf_hub_downloadfrom huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundError1 unmodified linefrom agent.core.hub_artifacts import is_known_hub_artifact, register_hub_artifactfrom agent.tools.types import ToolResultOperationType = Literal["list", "read", "upload", "delete"]async def _async_call(func, *args, **kwargs):"""Wrap synchronous HfApi calls for async context."""4 unmodified lines5678910111 unmodified line1314151617184 unmodified lines"""import asynciofrom typing import Any, Dict, Optionalfrom huggingface_hub import HfApi, hf_hub_downloadfrom huggingface_hub.utils import EntryNotFoundError, RepositoryNotFoundError1 unmodified linefrom agent.core.hub_artifacts import is_known_hub_artifact, register_hub_artifactfrom agent.tools.types import ToolResultasync def _async_call(func, *args, **kwargs):"""Wrap synchronous HfApi calls for async context."""
4 unmodified lines5678910111 unmodified line13141516171819202122232425262728293031323334354 unmodified lines"""import asynciofrom typing import Any, Dict, Literal, Optionalfrom huggingface_hub import HfApifrom huggingface_hub.utils import RepositoryNotFoundError1 unmodified linefrom agent.core.hub_artifacts import register_hub_artifactfrom agent.tools.types import ToolResultOperationType = Literal["create_branch","delete_branch","create_tag","delete_tag","list_refs","create_pr","list_prs","get_pr","merge_pr","close_pr","comment_pr","change_pr_status","create_repo","update_repo",]async def _async_call(func, *args, **kwargs):"""Wrap synchronous HfApi calls for async context."""4 unmodified lines5678910111 unmodified line1314151617184 unmodified lines"""import asynciofrom typing import Any, Dict, Optionalfrom huggingface_hub import HfApifrom huggingface_hub.utils import RepositoryNotFoundError1 unmodified linefrom agent.core.hub_artifacts import register_hub_artifactfrom agent.tools.types import ToolResultasync def _async_call(func, *args, **kwargs):"""Wrap synchronous HfApi calls for async context."""
9 unmodified lines1011121314151646 unmodified lines6364656667686970717273747576777879808182838485869 unmodified linesimport loggingimport reimport shlexfrom typing import Any, Awaitable, Callable, Dict, Literal, Optionalimport httpxfrom huggingface_hub import HfApi46 unmodified lines"l4x1(8vCPU/30GB/GPU 24GB), l4x4(48vCPU/186GB/GPU 96GB), ""l40sx1(8vCPU/62GB/GPU 48GB), l40sx4(48vCPU/382GB/GPU 192GB), l40sx8(192vCPU/1534GB/GPU 384GB)")SPECIALIZED_FLAVORS = ["inf2x6"]ALL_FLAVORS = CPU_FLAVORS + GPU_FLAVORS + SPECIALIZED_FLAVORS# Operation namesOperationType = Literal["run","ps","logs","inspect","cancel","scheduled run","scheduled ps","scheduled inspect","scheduled delete","scheduled suspend","scheduled resume",]# ConstantsUV_DEFAULT_IMAGE = "ghcr.io/astral-sh/uv:python3.12-bookworm"9 unmodified lines1011121314151646 unmodified lines6364656667689 unmodified linesimport loggingimport reimport shlexfrom typing import Any, Awaitable, Callable, Dict, Optionalimport httpxfrom huggingface_hub import HfApi46 unmodified lines"l4x1(8vCPU/30GB/GPU 24GB), l4x4(48vCPU/186GB/GPU 96GB), ""l40sx1(8vCPU/62GB/GPU 48GB), l40sx4(48vCPU/382GB/GPU 192GB), l40sx8(192vCPU/1534GB/GPU 384GB)")# ConstantsUV_DEFAULT_IMAGE = "ghcr.io/astral-sh/uv:python3.12-bookworm"
119 unmodified lines120121122123124125126127128129130131132133134135136137138119 unmodified linesreturn Noneasync def _s2_get_paper(client: httpx.AsyncClient,arxiv_id: str,fields: str,) -> dict | None:"""Fetch a single paper from S2 by arxiv ID. Returns None on failure."""return await _s2_get_json(client,f"/graph/v1/paper/{_s2_paper_id(arxiv_id)}",{"fields": fields},)# ---------------------------------------------------------------------------# HTML paper parsing# ---------------------------------------------------------------------------119 unmodified lines120121122123124125119 unmodified linesreturn None# ---------------------------------------------------------------------------# HTML paper parsing# ---------------------------------------------------------------------------
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650"""Private HF Repos Tool - Manage private Hugging Face repositories
PRIMARY USE: Store job outputs, training scripts, and logs from HF Jobs.Since job results are ephemeral, this tool provides persistent storage in private repos.
SECONDARY USE: Read back stored files and list repo contents."""
import asynciofrom typing import Any, Dict, Literal, Optional
from huggingface_hub import HfApi, hf_hub_downloadfrom huggingface_hub.utils import HfHubHTTPError
from agent.tools.types import ToolResult
# Operation namesOperationType = Literal[ "upload_file", "create_repo", "check_repo", "list_files", "read_file"]
async def _async_call(func, *args, **kwargs): """Wrap synchronous HfApi calls for async context.""" return await asyncio.to_thread(func, *args, **kwargs)
def _build_repo_url(repo_id: str, repo_type: str = "dataset") -> str: """Build the Hub URL for a repository.""" type_path = "" if repo_type == "model" else f"{repo_type}s" return f"https://huggingface.co/{type_path}/{repo_id}".replace("//", "/")
def _content_to_bytes(content: str | bytes) -> bytes: """Convert string or bytes content to bytes.""" if isinstance(content, str): return content.encode("utf-8") return content
class PrivateHfRepoTool: """Tool for managing private Hugging Face repositories."""
def __init__(self, hf_token: Optional[str] = None): self.api = HfApi(token=hf_token)
async def execute(self, params: Dict[str, Any]) -> ToolResult: """Execute the specified upload operation.""" operation = params.get("operation") args = params.get("args", {})
# If no operation provided, return usage instructions if not operation: return self._show_help()
# Normalize operation name operation = operation.lower()
# Check if help is requested if args.get("help"): return self._show_operation_help(operation)
try: # Route to appropriate handler if operation == "upload_file": return await self._upload_file(args) elif operation == "create_repo": return await self._create_repo(args) elif operation == "check_repo": return await self._check_repo(args) elif operation == "list_files": return await self._list_files(args) elif operation == "read_file": return await self._read_file(args) else: return { "formatted": f'Unknown operation: "{operation}"\n\n' "Available operations: upload_file, create_repo, check_repo, list_files, read_file\n\n" "Call this tool with no operation for full usage instructions.", "totalResults": 0, "resultsShared": 0, "isError": True, }
except HfHubHTTPError as e: return { "formatted": f"API Error: {str(e)}", "totalResults": 0, "resultsShared": 0, "isError": True, } except Exception as e: return { "formatted": f"Error executing {operation}: {str(e)}", "totalResults": 0, "resultsShared": 0, "isError": True, }
def _show_help(self) -> ToolResult: """Show usage instructions when tool is called with no arguments.""" usage_text = """# Private HF Repos Tool
**PRIMARY USE:** Store job outputs, scripts, and logs from HF Jobs to private repos.Since job results are ephemeral, use this tool for persistent storage.
**SECONDARY USE:** Read back stored files and list repo contents.
## Available Commands
### Write Operations- **upload_file** - Upload file content to a repository- **create_repo** - Create a new private repository
### Read Operations- **list_files** - List all files in a repository- **read_file** - Read content of a specific file from a repository- **check_repo** - Check if a repository exists
## Examples
### Upload a script to a dataset repoCall this tool with:```json{ "operation": "upload_file", "args": { "file_content": "import pandas as pd\\nprint('Hello from HF!')", "path_in_repo": "scripts/hello.py", "repo_id": "my-dataset", "repo_type": "dataset", "create_if_missing": true, "commit_message": "Add hello script" }}```
### Upload logs from a jobCall this tool with:```json{ "operation": "upload_file", "args": { "file_content": "Job started...\\nJob completed successfully!", "path_in_repo": "jobs/job-abc123/logs.txt", "repo_id": "job-results", "create_if_missing": true }}```
### Create a repositoryCall this tool with:```json{ "operation": "create_repo", "args": { "repo_id": "my-results", "repo_type": "dataset" }}```
### Create a SpaceCall this tool with:```json{ "operation": "create_repo", "args": { "repo_id": "my-gradio-app", "repo_type": "space", "space_sdk": "gradio" }}```Note: Repositories are always created as private. For spaces, `space_sdk` is required (gradio, streamlit, static, or docker).
### Check if a repository existsCall this tool with:```json{ "operation": "check_repo", "args": { "repo_id": "my-dataset", "repo_type": "dataset" }}```
### List files in a repositoryCall this tool with:```json{ "operation": "list_files", "args": { "repo_id": "job-results", "repo_type": "dataset" }}```
### Read a file from a repositoryCall this tool with:```json{ "operation": "read_file", "args": { "repo_id": "job-results", "path_in_repo": "jobs/job-abc123/script.py", "repo_type": "dataset" }}```
## Repository Types
- **dataset** (default) - For storing data, results, logs, scripts- **model** - For ML models and related artifacts- **space** - For Spaces and applications
## Tips
- **Content-based**: Pass file content directly as strings or bytes, not file paths- **Repo ID format**: Use just the repo name (e.g., "my-dataset"). Username is automatically inferred from HF_TOKEN- **Automatic repo creation**: Set `create_if_missing: true` to auto-create repos (requires user approval)- **Organization**: Use path_in_repo to organize files (e.g., "jobs/job-123/script.py")- **After jobs**: Upload job scripts and logs after compute jobs complete for reproducibility""" return {"formatted": usage_text, "totalResults": 1, "resultsShared": 1}
def _show_operation_help(self, operation: str) -> ToolResult: """Show help for a specific operation.""" help_text = f"Help for operation: {operation}\n\nCall with appropriate arguments. Use the main help for examples." return {"formatted": help_text, "totalResults": 1, "resultsShared": 1}
async def _upload_file(self, args: Dict[str, Any]) -> ToolResult: """Upload file content to a Hub repository.""" # Validate required arguments file_content = args.get("file_content") path_in_repo = args.get("path_in_repo") repo_id = args.get("repo_id")
if not file_content: return { "formatted": "file_content is required", "totalResults": 0, "resultsShared": 0, "isError": True, }
if not path_in_repo: return { "formatted": "path_in_repo is required", "totalResults": 0, "resultsShared": 0, "isError": True, }
if not repo_id: return { "formatted": "repo_id is required", "totalResults": 0, "resultsShared": 0, "isError": True, }
repo_type = args.get("repo_type", "dataset") create_if_missing = args.get("create_if_missing", False)
# Check if repo exists try: repo_exists = await _async_call( self.api.repo_exists, repo_id=repo_id, repo_type=repo_type )
# Create repo if needed if not repo_exists and create_if_missing: create_args = { "repo_id": repo_id, "repo_type": repo_type, "private": True, } # Pass through space_sdk if provided (required for spaces) if "space_sdk" in args: create_args["space_sdk"] = args["space_sdk"] await self._create_repo(create_args) elif not repo_exists: return { "formatted": f"Repository {repo_id} does not exist. Set create_if_missing: true to create it.", "totalResults": 0, "resultsShared": 0, "isError": True, }
except Exception as e: return { "formatted": f"Failed to check repository: {str(e)}", "totalResults": 0, "resultsShared": 0, "isError": True, }
# Convert content to bytes file_bytes = _content_to_bytes(file_content)
# Upload file try: await _async_call( self.api.upload_file, path_or_fileobj=file_bytes, path_in_repo=path_in_repo, repo_id=repo_id, repo_type=repo_type, commit_message=args.get("commit_message", f"Upload {path_in_repo}"), )
repo_url = _build_repo_url(repo_id, repo_type) file_url = f"{repo_url}/blob/main/{path_in_repo}"
response = f"""✓ File uploaded successfully!
**Repository:** {repo_id}**File:** {path_in_repo}**View at:** {file_url}**Browse repo:** {repo_url}"""
return {"formatted": response, "totalResults": 1, "resultsShared": 1}
except Exception as e: return { "formatted": f"Failed to upload file: {str(e)}", "totalResults": 0, "resultsShared": 0, "isError": True, }
async def _create_repo(self, args: Dict[str, Any]) -> ToolResult: """Create a new Hub repository.""" repo_id = args.get("repo_id")
if not repo_id: return { "formatted": "repo_id is required", "totalResults": 0, "resultsShared": 0, "isError": True, }
repo_type = args.get("repo_type", "dataset") private = True # Always create private repos space_sdk = args.get("space_sdk") # Required if repo_type is "space"
try: # Check if repo already exists repo_exists = await _async_call( self.api.repo_exists, repo_id=repo_id, repo_type=repo_type )
if repo_exists: repo_url = _build_repo_url(repo_id, repo_type) return { "formatted": f"Repository {repo_id} already exists.\n**View at:** {repo_url}", "totalResults": 1, "resultsShared": 1, }
# Validate space_sdk for spaces if repo_type == "space" and not space_sdk: return { "formatted": "space_sdk is required when creating a space. Valid values: gradio, streamlit, static, docker", "totalResults": 0, "resultsShared": 0, "isError": True, }
# Create repository create_kwargs = { "repo_id": repo_id, "repo_type": repo_type, "private": private, "exist_ok": True, } # Add space_sdk only for spaces if repo_type == "space" and space_sdk: create_kwargs["space_sdk"] = space_sdk
repo_url = await _async_call(self.api.create_repo, **create_kwargs)
response = f"""✓ Repository created successfully!
**Repository:** {repo_id}**Type:** {repo_type}**Private:** Yes**View at:** {repo_url}"""
return {"formatted": response, "totalResults": 1, "resultsShared": 1}
except Exception as e: return { "formatted": f"Failed to create repository: {str(e)}", "totalResults": 0, "resultsShared": 0, "isError": True, }
async def _check_repo(self, args: Dict[str, Any]) -> ToolResult: """Check if a Hub repository exists.""" repo_id = args.get("repo_id")
if not repo_id: return { "formatted": "repo_id is required", "totalResults": 0, "resultsShared": 0, "isError": True, }
repo_type = args.get("repo_type", "dataset")
try: repo_exists = await _async_call( self.api.repo_exists, repo_id=repo_id, repo_type=repo_type )
if repo_exists: repo_url = _build_repo_url(repo_id, repo_type) response = f"""✓ Repository exists!
**Repository:** {repo_id}**Type:** {repo_type}**View at:** {repo_url}""" else: response = f"""Repository does not exist: {repo_id}
To create it, call this tool with:```json{{ "operation": "create_repo", "args": {{ "repo_id": "{repo_id}", "repo_type": "{repo_type}" }}}}```"""
return { "formatted": response, "totalResults": 1 if repo_exists else 0, "resultsShared": 1 if repo_exists else 0, }
except Exception as e: return { "formatted": f"Failed to check repository: {str(e)}", "totalResults": 0, "resultsShared": 0, "isError": True, }
async def _list_files(self, args: Dict[str, Any]) -> ToolResult: """List all files in a Hub repository.""" repo_id = args.get("repo_id")
if not repo_id: return { "formatted": "repo_id is required", "totalResults": 0, "resultsShared": 0, "isError": True, }
repo_type = args.get("repo_type", "dataset")
try: # List all files in the repository files = await _async_call( self.api.list_repo_files, repo_id=repo_id, repo_type=repo_type )
if not files: return { "formatted": f"No files found in repository: {repo_id}", "totalResults": 0, "resultsShared": 0, }
# Format file list file_list = "\n".join(f"- {f}" for f in sorted(files)) repo_url = _build_repo_url(repo_id, repo_type)
response = f"""✓ Files in repository: {repo_id}
**Total files:** {len(files)}**Repository URL:** {repo_url}
**Files:**{file_list}"""
return { "formatted": response, "totalResults": len(files), "resultsShared": len(files), }
except Exception as e: return { "formatted": f"Failed to list files: {str(e)}", "totalResults": 0, "resultsShared": 0, "isError": True, }
async def _read_file(self, args: Dict[str, Any]) -> ToolResult: """Read content of a specific file from a Hub repository.""" repo_id = args.get("repo_id") path_in_repo = args.get("path_in_repo")
if not repo_id: return { "formatted": "repo_id is required", "totalResults": 0, "resultsShared": 0, "isError": True, }
if not path_in_repo: return { "formatted": "path_in_repo is required", "totalResults": 0, "resultsShared": 0, "isError": True, }
repo_type = args.get("repo_type", "dataset")
try: # Download file to cache and read it file_path = await _async_call( hf_hub_download, repo_id=repo_id, filename=path_in_repo, repo_type=repo_type, token=self.api.token, )
# Read file content with open(file_path, "r", encoding="utf-8") as f: content = f.read()
repo_url = _build_repo_url(repo_id, repo_type) file_url = f"{repo_url}/blob/main/{path_in_repo}"
response = f"""✓ File read successfully!
**Repository:** {repo_id}**File:** {path_in_repo}**Size:** {len(content)} characters**View at:** {file_url}
**Content:**```{content}```"""
return {"formatted": response, "totalResults": 1, "resultsShared": 1}
except UnicodeDecodeError: # If file is binary, return size info instead try: with open(file_path, "rb") as f: binary_content = f.read()
return { "formatted": f"File is binary ({len(binary_content)} bytes). Cannot display as text.", "totalResults": 1, "resultsShared": 1, } except Exception as e: return { "formatted": f"Failed to read binary file: {str(e)}", "totalResults": 0, "resultsShared": 0, "isError": True, } except Exception as e: return { "formatted": f"Failed to read file: {str(e)}", "totalResults": 0, "resultsShared": 0, "isError": True, }
# Tool specification for agent registrationPRIVATE_HF_REPO_TOOL_SPEC = { "name": "hf_private_repos", "description": ( "Manage private HF repositories - create, upload, read, list files in models/datasets/spaces. " "⚠️ PRIMARY USE: Store job outputs persistently (job storage is EPHEMERAL - everything deleted after completion). " "**Use when:** (1) Job completes and need to store logs/scripts/results, (2) Creating repos for training outputs, " "(3) Reading back stored files, (4) Managing Space files, (5) Organizing job artifacts by path. " "**Pattern:** hf_jobs (ephemeral) → hf_private_repos upload_file (persistent) → can read_file later. " "ALWAYS pass file_content as string/bytes (✓), never file paths (✗) - this is content-based, no filesystem access. " "**Operations:** create_repo (new private repo), upload_file (store content), read_file (retrieve content), list_files (browse), check_repo (verify exists). " "**Critical for reliability:** Jobs lose all files after completion - use this tool to preserve important outputs. " "Repositories created are ALWAYS private by default (good for sensitive training data/models). " "For Spaces: must provide space_sdk ('gradio', 'streamlit', 'static', 'docker') when creating. " "**Then:** After uploading, provide user with repository URL for viewing/sharing." ), "parameters": { "type": "object", "properties": { "operation": { "type": "string", "enum": [ "upload_file", "create_repo", "check_repo", "list_files", "read_file", ], "description": ( "Operation to execute. Valid values: [upload_file, create_repo, check_repo, list_files, read_file]" ), }, "args": { "type": "object", "description": ( "Operation-specific arguments as a JSON object. " "Write ops: file_content (string/bytes), path_in_repo (string), repo_id (string), " "repo_type (dataset/model/space), create_if_missing (boolean), commit_message (string), " "space_sdk (gradio/streamlit/static/docker - required when repo_type=space). " "Read ops: repo_id (string), path_in_repo (for read_file), repo_type (optional)." ), "additionalProperties": True, }, }, },}
async def private_hf_repo_handler(arguments: Dict[str, Any]) -> tuple[str, bool]: """Handler for agent tool router.""" try: tool = PrivateHfRepoTool() result = await tool.execute(arguments) return result["formatted"], not result.get("isError", False) except Exception as e: return f"Error executing Private HF Repo tool: {str(e)}", False47 unmodified lines4849505152535455565758596061626364432 unmodified lines497498499500501502503504505288 unmodified lines794795796797798799800801802803804805806807808322 unmodified lines113111321133113411351136113711381139114047 unmodified linesfrom huggingface_hub import CommitOperationAdd, HfApiTEMPLATE_SPACE = "burtenshaw/sandbox"HARDWARE_OPTIONS = ["cpu-basic","cpu-upgrade","t4-small","t4-medium","a10g-small","a10g-large","a100-large",]OUTPUT_LIMIT = 25000LINE_LIMIT = 4000DEFAULT_READ_LIMIT = 2000DEFAULT_TIMEOUT = 240MAX_TIMEOUT = 1200432 unmodified linesreturn self.output or "(no output)"return f"ERROR: {self.error}"def to_dict(self) -> dict:return {"success": self.success, "output": self.output, "error": self.error}@dataclassclass Sandbox:288 unmodified linesif log:log("Deleted.")def pause(self):"""Pause the Space (stops billing, preserves state)."""self._hf_api.pause_space(self.space_id)def restart(self):"""Restart the Space."""self._hf_api.restart_space(self.space_id)self._wait_for_api()@propertydef url(self) -> str:"""Public URL of the Space."""322 unmodified lines},}@classmethoddef tool_definitions(cls) -> list[dict]:return [{"name": name, **spec} for name, spec in cls.TOOLS.items()]def call_tool(self, name: str, arguments: dict[str, Any]) -> ToolResult:dispatch = {"bash": lambda a: self.bash(47 unmodified lines484950515253432 unmodified lines486487488489490491288 unmodified lines780781782783784785322 unmodified lines11081109111011111112111347 unmodified linesfrom huggingface_hub import CommitOperationAdd, HfApiTEMPLATE_SPACE = "burtenshaw/sandbox"DEFAULT_READ_LIMIT = 2000DEFAULT_TIMEOUT = 240MAX_TIMEOUT = 1200432 unmodified linesreturn self.output or "(no output)"return f"ERROR: {self.error}"@dataclassclass Sandbox:288 unmodified linesif log:log("Deleted.")@propertydef url(self) -> str:"""Public URL of the Space."""322 unmodified lines},}def call_tool(self, name: str, arguments: dict[str, Any]) -> ToolResult:dispatch = {"bash": lambda a: self.bash(
17 unmodified lines1819202122232417 unmodified lines4243444546474849505152291 unmodified lines34434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640717 unmodified linesimport uuidimport weakreffrom collections.abc import Callablefrom datetime import datetime, timedelta, timezonefrom typing import Anyfrom huggingface_hub import HfApi, SpaceHardware17 unmodified lines# user-renamed lookalikes).SANDBOX_SPACE_NAME_RE = re.compile(r"^sandbox-[a-f0-9]{8}$")# How stale a sandbox must be before we treat it as definitely orphan.# Anything more recent could be tied to a still-live session in another tab,# so we leave it alone._ORPHAN_STALE_AFTER = timedelta(hours=1)# HF Space duplication/build APIs can behave poorly when multiple private# sandboxes are created concurrently for the same namespace. Keep session# creation non-blocking, but serialize the actual Hub create path per owner.291 unmodified lines# ── Tool name mapping (short agent names → Sandbox client names) ──────def _cleanup_user_orphan_sandboxes(api: HfApi,owner: str,log: Any,) -> int:"""Delete stale ``sandbox-<8hex>`` Spaces in ``owner``'s account."Stale" = not modified in the last hour. The naming pattern + stalenessfilter together make this safe:* Naming: only matches ``sandbox-<exactly 8 lowercase hex>``, thepattern Sandbox.create produces. Won't touch user-renamed Spaces.* Staleness: anything modified in the last hour might still be tiedto a live session in another tab/replica, so we leave it alone.Runs blocking — call via ``asyncio.to_thread``. Best-effort: failuresare logged but never raised, so a flaky HF API never blocks creation."""cutoff = datetime.now(timezone.utc) - _ORPHAN_STALE_AFTERdeleted = 0try:spaces = list(api.list_spaces(author=owner, limit=200, full=True))except Exception as e:log(f"orphan sweep: list_spaces failed: {e}")return 0for space in spaces:space_name = space.id.rsplit("/", 1)[-1]if not SANDBOX_SPACE_NAME_RE.match(space_name):continuelast_mod = getattr(space, "lastModified", None) or getattr(space, "last_modified", None)if isinstance(last_mod, str):try:last_mod = datetime.fromisoformat(last_mod.replace("Z", "+00:00"))except ValueError:last_mod = Noneif last_mod is None:log(f"orphan sweep: skipping {space.id}; missing lastModified")continueif last_mod and last_mod > cutoff:# Recent — could be a concurrent live session. Skip.continuetry:api.delete_repo(repo_id=space.id, repo_type="space")deleted += 1log(f"orphan sweep: deleted {space.id}")except Exception as e:log(f"orphan sweep: failed to delete {space.id}: {e}")if deleted:log(f"orphan sweep: cleaned up {deleted} stale sandbox(es) before create")return deletedasync def _ensure_sandbox(session: Any,hardware: str = DEFAULT_CPU_SANDBOX_HARDWARE,17 unmodified lines1819202122232417 unmodified lines424344454647291 unmodified lines33934034134234334417 unmodified linesimport uuidimport weakreffrom collections.abc import Callablefrom datetime import datetime, timezonefrom typing import Anyfrom huggingface_hub import HfApi, SpaceHardware17 unmodified lines# user-renamed lookalikes).SANDBOX_SPACE_NAME_RE = re.compile(r"^sandbox-[a-f0-9]{8}$")# HF Space duplication/build APIs can behave poorly when multiple private# sandboxes are created concurrently for the same namespace. Keep session# creation non-blocking, but serialize the actual Hub create path per owner.291 unmodified lines# ── Tool name mapping (short agent names → Sandbox client names) ──────async def _ensure_sandbox(session: Any,hardware: str = DEFAULT_CPU_SANDBOX_HARDWARE,
58 unmodified lines5960616263646566676858 unmodified linesself.x += self.vxself.y += self.vy@propertydef at_target(self) -> bool:return abs(self.x - self.target_x) < 1.5 and abs(self.y - self.target_y) < 1.5def run_particle_logo(console: Console, hold_seconds: float = 1.5) -> None:"""Run the particle coalesce effect."""58 unmodified lines59606162636458 unmodified linesself.x += self.vxself.y += self.vydef run_particle_logo(console: Console, hold_seconds: float = 1.5) -> None:"""Run the particle coalesce effect."""
21 unmodified lines222324252627282930313233343536174 unmodified lines21121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024135 unmodified lines27727827928028128228328428528628728828929029129229329429529629729829930030130230321 unmodified linesOPENID_PROVIDER_URL = os.environ.get("OPENID_PROVIDER_URL", "https://huggingface.co")AUTH_ENABLED = bool(os.environ.get("OAUTH_CLIENT_ID", ""))HF_EMPLOYEE_ORG = os.environ.get("HF_EMPLOYEE_ORG", "huggingface")# Simple in-memory token cache: token -> (user_info, expiry_time)_token_cache: dict[str, tuple[dict[str, Any], float]] = {}TOKEN_CACHE_TTL = 300 # 5 minutes# Org membership cache: key -> expiry_time (only caches positive results)_org_member_cache: dict[str, float] = {}DEV_USER: dict[str, Any] = {"user_id": "dev","username": "dev",174 unmodified lines}async def check_org_membership(token: str, org_name: str) -> bool:"""Check if the token owner belongs to an HF org. Only caches positive results."""now = time.time()key = token + org_namecached = _org_member_cache.get(key)if cached and cached > now:return Trueasync with httpx.AsyncClient(timeout=10.0) as client:try:resp = await client.get(f"{OPENID_PROVIDER_URL}/api/whoami-v2",headers={"Authorization": f"Bearer {token}"},)if resp.status_code != 200:return Falseorgs = {o.get("name") for o in resp.json().get("orgs", [])}if org_name in orgs:_org_member_cache[key] = now + TOKEN_CACHE_TTLreturn Truereturn Falseexcept httpx.HTTPError:return Falseasync def get_current_user(request: Request) -> dict[str, Any]:"""FastAPI dependency: extract and validate the current user.35 unmodified linesdetail="Not authenticated. Please log in via /auth/login.",headers={"WWW-Authenticate": "Bearer"},)def _extract_token(request: Request) -> str | None:"""Pull the HF access token from the Authorization header or cookie.Mirrors the lookup order used by ``get_current_user``."""token = bearer_token_from_header(request.headers.get("Authorization", ""))if token:return tokenreturn request.cookies.get("hf_access_token")async def require_huggingface_org_member(request: Request) -> bool:"""Return True if the caller is a member of the ``huggingface`` org.Returns True unconditionally in dev mode so local testing isn't blocked."""if not AUTH_ENABLED:return Truetoken = _extract_token(request)if not token:return Falsereturn await check_org_membership(token, HF_EMPLOYEE_ORG)21 unmodified lines2223242526272829303132174 unmodified lines20720820921021121235 unmodified lines24824925021 unmodified linesOPENID_PROVIDER_URL = os.environ.get("OPENID_PROVIDER_URL", "https://huggingface.co")AUTH_ENABLED = bool(os.environ.get("OAUTH_CLIENT_ID", ""))# Simple in-memory token cache: token -> (user_info, expiry_time)_token_cache: dict[str, tuple[dict[str, Any], float]] = {}TOKEN_CACHE_TTL = 300 # 5 minutesDEV_USER: dict[str, Any] = {"user_id": "dev","username": "dev",174 unmodified lines}async def get_current_user(request: Request) -> dict[str, Any]:"""FastAPI dependency: extract and validate the current user.35 unmodified linesdetail="Not authenticated. Please log in via /auth/login.",headers={"WWW-Authenticate": "Bearer"},)
1234518 unmodified lines24252627282920 unmodified lines50515253545556575859606162636465"""FastAPI application for HF Agent web interface."""import loggingimport osfrom contextlib import asynccontextmanager18 unmodified linesformat="%(asctime)s - %(name)s - %(levelname)s - %(message)s",)logger = logging.getLogger(__name__)@asynccontextmanager20 unmodified lineslogger.warning("KPI scheduler shutdown failed: %s", e)# Final-flush: save every still-active session so we don't lose traces on# server restart. Uploads are detached subprocesses — this is fast.try:for sid, agent_session in list(session_manager.sessions.items()):sess = agent_session.sessionif sess.config.save_sessions:try:sess.save_and_upload_detached(sess.config.session_dataset_repo)logger.info("Flushed session %s on shutdown", sid)except Exception as e:logger.warning("Failed to flush session %s: %s", sid, e)except Exception as e:logger.warning("Lifespan final-flush skipped: %s", e)await session_manager.close()12345618 unmodified lines252627282930313233343536373839404142434445464720 unmodified lines68697071727374757677787980818283"""FastAPI application for HF Agent web interface."""import asyncioimport loggingimport osfrom contextlib import asynccontextmanager18 unmodified linesformat="%(asctime)s - %(name)s - %(levelname)s - %(message)s",)logger = logging.getLogger(__name__)SHUTDOWN_USAGE_REFRESH_CONCURRENCY = 32async def _flush_session_on_shutdown(sid: str, agent_session, semaphore) -> None:sess = agent_session.sessionif not sess.config.save_sessions:returntry:async with semaphore:await session_manager.refresh_session_usage_metrics(agent_session,error_code="lifespan_billing_snapshot_error",)sess.save_and_upload_detached(sess.config.session_dataset_repo)logger.info("Flushed session %s on shutdown", sid)except Exception as e:logger.warning("Failed to flush session %s: %s", sid, e)@asynccontextmanager20 unmodified lineslogger.warning("KPI scheduler shutdown failed: %s", e)# Final-flush: save every still-active session so we don't lose traces on# server restart. Billing refreshes are timeboxed and bounded; uploads are# detached subprocesses.try:semaphore = asyncio.Semaphore(SHUTDOWN_USAGE_REFRESH_CONCURRENCY)await asyncio.gather(*(_flush_session_on_shutdown(sid, agent_session, semaphore)for sid, agent_session in list(session_manager.sessions.items())))except Exception as e:logger.warning("Lifespan final-flush skipped: %s", e)await session_manager.close()
10 unmodified lines1112131415161710 unmodified linesUSER_INPUT = "user_input"EXEC_APPROVAL = "exec_approval"INTERRUPT = "interrupt"UNDO = "undo"COMPACT = "compact"SHUTDOWN = "shutdown"10 unmodified lines11121314151610 unmodified linesUSER_INPUT = "user_input"EXEC_APPROVAL = "exec_approval"UNDO = "undo"COMPACT = "compact"SHUTDOWN = "shutdown"
69 unmodified lines707172737475768 unmodified lines858687888990668 unmodified lines759760761762763764765766143 unmodified lines910911912913914915916917236 unmodified lines115411551156115711581159116069 unmodified lineslogger = logging.getLogger(__name__)router = APIRouter(prefix="/api", tags=["agent"])_background_teardown_tasks: set[asyncio.Task] = set()DEFAULT_OPUS_MODEL_ID = CLAUDE_OPUS_48_MODEL_IDDEFAULT_GPT_MODEL_ID = GPT_55_MODEL_ID8 unmodified lines)def _available_models() -> list[dict[str, Any]]:models = [{668 unmodified lines"""Best-effort sandbox teardown that preserves durable chat history."""await _check_session_access(session_id, user, preload_sandbox=False)task = asyncio.create_task(session_manager.teardown_sandbox(session_id))_background_teardown_tasks.add(task)task.add_done_callback(_background_teardown_tasks.discard)return {"status": "teardown_requested", "session_id": session_id}143 unmodified linestarget=str(body.get("target") or "pro_pricing"),)if agent_session.session.config.save_sessions:agent_session.session.save_and_upload_detached(agent_session.session.config.session_dataset_repo)return {"status": "ok"}236 unmodified lines# Fire-and-forget save so feedback reaches the dataset even if the user# closes the tab right after clicking.if agent_session.session.config.save_sessions:agent_session.session.save_and_upload_detached(agent_session.session.config.session_dataset_repo)return {"status": "ok"}69 unmodified lines707172737475768 unmodified lines858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122668 unmodified lines791792793794795796797798143 unmodified lines942943944945946947948949950236 unmodified lines1187118811891190119111921193119469 unmodified lineslogger = logging.getLogger(__name__)router = APIRouter(prefix="/api", tags=["agent"])_background_route_tasks: set[asyncio.Task] = set()DEFAULT_OPUS_MODEL_ID = CLAUDE_OPUS_48_MODEL_IDDEFAULT_GPT_MODEL_ID = GPT_55_MODEL_ID8 unmodified lines)async def _refresh_usage_and_upload(agent_session: AgentSession,*,error_code: str,) -> None:session = agent_session.sessiontry:await session_manager.refresh_session_usage_metrics(agent_session,error_code=error_code,)session.save_and_upload_detached(session.config.session_dataset_repo)except Exception as e:logger.warning("Background usage refresh/upload failed for %s: %s",agent_session.session_id,e,)def _schedule_usage_refresh_and_upload(agent_session: AgentSession,*,error_code: str,) -> None:task = asyncio.create_task(_refresh_usage_and_upload(agent_session, error_code=error_code))_background_route_tasks.add(task)task.add_done_callback(_background_route_tasks.discard)def _available_models() -> list[dict[str, Any]]:models = [{668 unmodified lines"""Best-effort sandbox teardown that preserves durable chat history."""await _check_session_access(session_id, user, preload_sandbox=False)task = asyncio.create_task(session_manager.teardown_sandbox(session_id))_background_route_tasks.add(task)task.add_done_callback(_background_route_tasks.discard)return {"status": "teardown_requested", "session_id": session_id}143 unmodified linestarget=str(body.get("target") or "pro_pricing"),)if agent_session.session.config.save_sessions:_schedule_usage_refresh_and_upload(agent_session,error_code="pro_click_billing_snapshot_error",)return {"status": "ok"}236 unmodified lines# Fire-and-forget save so feedback reaches the dataset even if the user# closes the tab right after clicking.if agent_session.session.config.save_sessions:_schedule_usage_refresh_and_upload(agent_session,error_code="feedback_billing_snapshot_error",)return {"status": "ok"}
41 unmodified lines424344454647519 unmodified lines5675685695705715721061 unmodified lines16341635163616371638163922 unmodified lines166216631664166516661667216 unmodified lines18841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191041 unmodified linesPROJECT_ROOT = Path(__file__).parent.parentDEFAULT_CONFIG_PATH = str(PROJECT_ROOT / "configs" / "frontend_agent_config.json")USAGE_WARNING_SPEND_CACHE_TTL_SECONDS = 30.0# These dataclasses match agent/main.py structure519 unmodified lines}return spend, billing_source@staticmethoddef _runtime_session_usage_spend(agent_session: AgentSession) -> float:from usage import aggregate_usage_events, event_created_at1061 unmodified lines# than the idle window would otherwise be reaped the# instant it completes.self._touch(agent_session)await self.persist_session_snapshot(agent_session)if not should_continue:break22 unmodified lines# Idempotent via session_id key; detached subprocess.if session.config.save_sessions:try:session.save_and_upload_detached(session.config.session_dataset_repo)216 unmodified linesself._touch(agent_session)return self._auto_approval_summary(session)def get_session_owner(self, session_id: str) -> str | None:"""Get the user_id that owns a session, or None if session doesn't exist."""agent_session = self.sessions.get(session_id)if not agent_session:return Nonereturn agent_session.user_iddef verify_session_access(self, session_id: str, user_id: str) -> bool:"""Check if a user has access to a session.Returns True if:- The session exists AND the user owns it- The user_id is "dev" (dev mode bypass)"""owner = self.get_session_owner(session_id)if owner is None:return Falseif user_id == "dev" or owner == "dev":return Truereturn owner == user_iddef get_session_info(self, session_id: str) -> dict[str, Any] | None:"""Get information about a session."""agent_session = self.sessions.get(session_id)41 unmodified lines42434445464748519 unmodified lines5685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386391061 unmodified lines1701170217031704170517061707170822 unmodified lines1731173217331734173517361737173817391740216 unmodified lines19571958195919601961196241 unmodified linesPROJECT_ROOT = Path(__file__).parent.parentDEFAULT_CONFIG_PATH = str(PROJECT_ROOT / "configs" / "frontend_agent_config.json")USAGE_WARNING_SPEND_CACHE_TTL_SECONDS = 30.0USAGE_BILLING_REFRESH_TIMEOUT_SECONDS = 2.0# These dataclasses match agent/main.py structure519 unmodified lines}return spend, billing_source@staticmethoddef _fallback_hf_billing_snapshot(error: str) -> dict[str, Any]:return {"billing_scope": "account_window_delta","hf_billing": {"source": "hf_billing_usage_v2","available": False,"error": error,"current_session": None,},}async def refresh_session_usage_metrics(self,agent_session: AgentSession,*,error_code: str = "billing_snapshot_error",billing_timeout_s: float | None = USAGE_BILLING_REFRESH_TIMEOUT_SECONDS,) -> dict[str, Any]:"""Refresh the dataset usage snapshot stored on the runtime session."""from agent.core.usage_metrics import (normalize_hf_billing_snapshot,summarize_usage_events,)from usage import build_hf_billing_snapshotsession = agent_session.sessiontry:billing_snapshot = build_hf_billing_snapshot(self,hf_token=agent_session.hf_token or getattr(session, "hf_token", None),session_id=agent_session.session_id,timezone_name="UTC",)if billing_timeout_s is not None and billing_timeout_s > 0:hf_billing_snapshot = await asyncio.wait_for(billing_snapshot,timeout=billing_timeout_s,)else:hf_billing_snapshot = await billing_snapshotexcept TimeoutError:logger.debug("HF billing snapshot refresh timed out for %s after %.2fs",agent_session.session_id,billing_timeout_s or 0,)hf_billing_snapshot = self._fallback_hf_billing_snapshot(error_code)except Exception as e:logger.debug("HF billing snapshot refresh failed for %s: %s",agent_session.session_id,e,)hf_billing_snapshot = self._fallback_hf_billing_snapshot(error_code)hf_billing_snapshot = normalize_hf_billing_snapshot(hf_billing_snapshot)session.usage_hf_billing_snapshot = hf_billing_snapshotmetrics = summarize_usage_events(getattr(session, "logged_events", []) or [],session_id=agent_session.session_id,hf_billing_snapshot=hf_billing_snapshot,)session.usage_metrics = metricsreturn metrics@staticmethoddef _runtime_session_usage_spend(agent_session: AgentSession) -> float:from usage import aggregate_usage_events, event_created_at1061 unmodified lines# than the idle window would otherwise be reaped the# instant it completes.self._touch(agent_session)if session.config.save_sessions:await self.refresh_session_usage_metrics(agent_session)await self.persist_session_snapshot(agent_session)if not should_continue:break22 unmodified lines# Idempotent via session_id key; detached subprocess.if session.config.save_sessions:try:await self.refresh_session_usage_metrics(agent_session,error_code="final_billing_snapshot_error",)session.save_and_upload_detached(session.config.session_dataset_repo)216 unmodified linesself._touch(agent_session)return self._auto_approval_summary(session)def get_session_info(self, session_id: str) -> dict[str, Any] | None:"""Get information about a session."""agent_session = self.sessions.get(session_id)
7 unmodified lines891011121314224 unmodified lines2392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842853 unmodified lines289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329298 unmodified lines6286296306316326337 unmodified linesimport httpxfrom agent.core.cost_estimation import SPACE_PRICE_USD_PER_HOURUSAGE_EVENT_TYPES = ("llm_call",224 unmodified linesreturn bucketdef _event_sort_key(indexed_event: tuple[int, dict[str, Any]],) -> tuple[bool, datetime, int]:index, event = indexed_eventcreated_at = event_created_at(event)return (created_at is None,created_at or datetime.min.replace(tzinfo=UTC),index,)def _sandbox_id(event: dict[str, Any]) -> str | None:data = event.get("data") or {}sandbox_id = data.get("sandbox_id")return sandbox_id if isinstance(sandbox_id, str) and sandbox_id else Nonedef _sandbox_duration_seconds(create_event: dict[str, Any],destroy_event: dict[str, Any],) -> int:create_data = create_event.get("data") or {}destroy_data = destroy_event.get("data") or {}lifetime_s = _coerce_int(destroy_data.get("lifetime_s"))if lifetime_s > 0:# Telemetry starts the lifetime clock before create latency elapses.return lifetime_screate_at = event_created_at(create_event)destroy_at = event_created_at(destroy_event)if create_at is None or destroy_at is None:return 0create_latency_s = max(0, _coerce_int(create_data.get("create_latency_s")))interval_start = create_at - timedelta(seconds=create_latency_s)if destroy_at <= interval_start:return 0return int((destroy_at - interval_start).total_seconds())def _aggregate_sandbox_usage(events: list[dict[str, Any]],bucket: dict[str, Any],3 unmodified linesfor index, event in enumerate(events)if event.get("event_type") in {"sandbox_create", "sandbox_destroy"}]ordered_events = [eventfor _, event in sorted(lifecycle_events,key=_event_sort_key,)]active_creates: dict[str, dict[str, Any]] = {}for event in ordered_events:event_type = event.get("event_type")sandbox_id = _sandbox_id(event)if sandbox_id is None:continueif event_type == "sandbox_create":active_creates[sandbox_id] = eventcontinueif event_type != "sandbox_destroy":continuecreate_event = active_creates.pop(sandbox_id, None)if create_event is None:continuecreate_data = create_event.get("data") or {}hardware = str(create_data.get("hardware") or "cpu-basic")price_usd_per_hour = SPACE_PRICE_USD_PER_HOUR.get(hardware, 0.0)seconds = _sandbox_duration_seconds(create_event, event)bucket["sandbox_count"] += 1if price_usd_per_hour > 0:bucket["sandbox_billable_seconds_estimate"] += secondsbucket["sandbox_estimated_usd"] += price_usd_per_hour * (seconds / 3600)def _account_bucket_from_billing_usage(298 unmodified linesreturn account_usagedef _event_in_window(event: dict[str, Any],*,7 unmodified lines891011121314224 unmodified lines2392402412422432443 unmodified lines248249250251252253254255256257298 unmodified lines5565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236247 unmodified linesimport httpxfrom agent.core.usage_metrics import summarize_sandbox_lifecycleUSAGE_EVENT_TYPES = ("llm_call",224 unmodified linesreturn bucketdef _aggregate_sandbox_usage(events: list[dict[str, Any]],bucket: dict[str, Any],3 unmodified linesfor index, event in enumerate(events)if event.get("event_type") in {"sandbox_create", "sandbox_destroy"}]sandbox = summarize_sandbox_lifecycle(lifecycle_events)bucket["sandbox_count"] += sandbox["matched_pairs"]bucket["sandbox_billable_seconds_estimate"] += sandbox["billable_seconds_estimate"]bucket["sandbox_estimated_usd"] += sandbox["estimated_usd"]def _account_bucket_from_billing_usage(298 unmodified linesreturn account_usageasync def build_hf_billing_snapshot(manager: Any,*,hf_token: str | None,session_id: str | None,timezone_name: str | None = None,now: datetime | None = None,) -> dict[str, Any]:"""Return a dataset-safe HF billing rollup for the session window.This intentionally omits monthly account totals and credit-limit details.The snapshot is an account-window delta, not per-call attribution."""windows = resolve_usage_windows(timezone_name, now=now)timezone = str(windows["timezone"])now_utc = windows["now_utc"]snapshot: dict[str, Any] = {"billing_scope": "account_window_delta","hf_billing": {"source": "hf_billing_usage_v2","available": False,"error": None,"current_session": None,},}hf_billing = snapshot["hf_billing"]if not hf_token:hf_billing["error"] = "missing_hf_token"return snapshotif not session_id:hf_billing["error"] = "missing_session_id"return snapshotsession_start = _session_usage_window_started_at(manager, session_id)if session_start is None:session_start, _ = await _load_persisted_session_usage_window_metadata(manager,session_id,)if session_start is None:hf_billing["error"] = "missing_session_window"return snapshotpayload = await _fetch_hf_billing_usage_v2(hf_token,start=session_start,end=now_utc,)if not isinstance(payload, dict):hf_billing["error"] = "billing_usage_unavailable"return snapshothf_billing["available"] = Truehf_billing["current_session"] = _account_bucket_from_billing_usage(payload,window_start=session_start,window_end=now_utc,timezone=timezone,)return snapshotdef _event_in_window(event: dict[str, Any],*,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748import { Box, Typography } from '@mui/material';
/** Pulsing dots shown while the agent is processing. */export default function ThinkingIndicator() { return ( <Box sx={{ pt: 0.75 }}> <Typography variant="caption" sx={{ fontWeight: 700, fontSize: '0.72rem', color: 'var(--muted-text)', textTransform: 'uppercase', letterSpacing: '0.04em', display: 'flex', alignItems: 'center', gap: 0.75, }} > Thinking <Box component="span" sx={{ display: 'inline-flex', gap: '3px', '& span': { width: 4, height: 4, borderRadius: '50%', bgcolor: 'primary.main', animation: 'dotPulse 1.4s ease-in-out infinite', }, '& span:nth-of-type(2)': { animationDelay: '0.2s' }, '& span:nth-of-type(3)': { animationDelay: '0.4s' }, '@keyframes dotPulse': { '0%, 80%, 100%': { opacity: 0.25, transform: 'scale(0.8)' }, '40%': { opacity: 1, transform: 'scale(1)' }, }, }} > <span /> <span /> <span /> </Box> </Typography> </Box> );}119 unmodified lines120121122123124125126119 unmodified linesstrong/><UsageRowlabel={useJobEstimate ? 'HF Jobs estimated' : 'HF Jobs'}value={formatUsd(useJobEstimate ? telemetry?.hf_jobs_estimated_usd : account?.hf_jobs_usd,)}119 unmodified lines120121122123124125126119 unmodified linesstrong/><UsageRowlabel="HF Jobs"value={formatUsd(useJobEstimate ? telemetry?.hf_jobs_estimated_usd : account?.hf_jobs_usd,)}
217 unmodified lines218219220221222223217 unmodified lines},shape: sharedShape,});// Keep default export for backwards compatexport default darkTheme;217 unmodified lines218219220217 unmodified lines},shape: sharedShape,});
35 unmodified lines3637383940414243444546474835 unmodified linesautoApprovalRemainingUsd?: number | null;}export interface ToolApproval {tool_call_id: string;approved: boolean;feedback?: string | null;namespace?: string | null;}export interface User {authenticated: boolean;username?: string;35 unmodified lines36373839404135 unmodified linesautoApprovalRemainingUsd?: number | null;}export interface User {authenticated: boolean;username?: string;
30 unmodified lines313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979830 unmodified linesdata?: Record<string, unknown>;seq?: number;}export interface ReadyEventData {message: string;}export interface ProcessingEventData {message: string;}export interface AssistantMessageEventData {content: string;}export interface ToolCallEventData {tool: string;arguments: Record<string, unknown>;}export interface ToolOutputEventData {tool: string;output: string;success: boolean;}export interface ToolLogEventData {tool: string;log: string;}export interface PlanUpdateEventData {plan: Array<{ id: string; content: string; status: 'pending' | 'in_progress' | 'completed' }>;}export interface ApprovalRequiredEventData {tools: ApprovalToolItem[];count: number;yolo_budget?: boolean;auto_approval_blocked?: boolean;block_reason?: string | null;estimated_cost_usd?: number | null;remaining_cap_usd?: number | null;}export interface ApprovalToolItem {tool: string;arguments: Record<string, unknown>;tool_call_id: string;auto_approval_blocked?: boolean;block_reason?: string | null;estimated_cost_usd?: number | null;remaining_cap_usd?: number | null;}export interface TurnCompleteEventData {history_size: number;}export interface CompactedEventData {old_tokens: number;new_tokens: number;}export interface ErrorEventData {error: string;}30 unmodified lines31323330 unmodified linesdata?: Record<string, unknown>;seq?: number;}
11 unmodified lines1213141516171811 unmodified lines# Agent runtime dependencies"requests>=2.33.0","litellm>=1.83.0","boto3>=1.35.0","huggingface-hub>=1.12.0","fastmcp>=3.2.0","prompt-toolkit>=3.0.0",11 unmodified lines12131415161711 unmodified lines# Agent runtime dependencies"requests>=2.33.0","litellm>=1.83.0","huggingface-hub>=1.12.0","fastmcp>=3.2.0","prompt-toolkit>=3.0.0",
68 unmodified lines6970717273747568 unmodified linesfrom huggingface_hub.utils import HfHubHTTPErrorSANDBOX_NAME_RE = re.compile(r"^[^/]+/sandbox-[a-f0-9]{8}$")TEMPLATE_REPO = "burtenshaw/sandbox"def log(record: dict) -> None:68 unmodified lines69707172737468 unmodified linesfrom huggingface_hub.utils import HfHubHTTPErrorSANDBOX_NAME_RE = re.compile(r"^[^/]+/sandbox-[a-f0-9]{8}$")def log(record: dict) -> None:
19 unmodified lines2021222324252650 unmodified lines77787980818283848519 unmodified lines_call_llm_streaming,)from agent.core.llm_params import _resolve_llm_paramsfrom agent.core.model_ids import DEFAULT_MODEL_IDif env_file := os.environ.get("ML_INTERN_LIVE_ENV_FILE"):50 unmodified lines_skip_without_live_flag()_skip_without_hf_token()session = _session(DEFAULT_MODEL_ID)llm_params = _resolve_llm_params(DEFAULT_MODEL_ID,os.environ["HF_TOKEN"],reasoning_effort="low",)19 unmodified lines2021222324252650 unmodified lines77787980818283848519 unmodified lines_call_llm_streaming,)from agent.core.llm_params import _resolve_llm_paramsfrom agent.core.model_ids import CLAUDE_OPUS_48_MODEL_IDif env_file := os.environ.get("ML_INTERN_LIVE_ENV_FILE"):50 unmodified lines_skip_without_live_flag()_skip_without_hf_token()session = _session(CLAUDE_OPUS_48_MODEL_ID)llm_params = _resolve_llm_params(CLAUDE_OPUS_48_MODEL_ID,os.environ["HF_TOKEN"],reasoning_effort="low",)
73 unmodified lines74757677787980818273 unmodified linesassert decision.requires_approval is Trueassert decision.auto_approval_blocked is Trueassert "Scheduled HF jobs" in decision.block_reasonassert agent_loop._needs_approval("hf_jobs", {"operation": operation}, session.config)@pytest.mark.asyncio73 unmodified lines74757677787973 unmodified linesassert decision.requires_approval is Trueassert decision.auto_approval_blocked is Trueassert "Scheduled HF jobs" in decision.block_reason@pytest.mark.asyncio
123456789 unmodified lines979899100101102103104105106107108109110111112113114115116117118119120121122123124import pytestfrom agent.core.hf_access import (fetch_hf_user_plan,is_billing_error,is_inference_billing_error,jobs_access_from_whoami,89 unmodified linesassert normalize_hf_user_plan({"isPro": False}) == "free"assert normalize_hf_user_plan({"plan": "HF Pro"}) == "free"assert normalize_hf_user_plan(None) is None@pytest.mark.asyncioasync def test_fetch_hf_user_plan_returns_unknown_without_token():assert await fetch_hf_user_plan(None) == "unknown"@pytest.mark.asyncioasync def test_fetch_hf_user_plan_returns_unknown_when_whoami_unavailable(monkeypatch):async def fake_fetch_whoami_v2(_token, timeout=5.0):return Nonemonkeypatch.setattr("agent.core.hf_access.fetch_whoami_v2", fake_fetch_whoami_v2)assert await fetch_hf_user_plan("hf-token") == "unknown"@pytest.mark.asyncioasync def test_fetch_hf_user_plan_normalizes_whoami(monkeypatch):async def fake_fetch_whoami_v2(_token, timeout=5.0):return {"isPro": True}monkeypatch.setattr("agent.core.hf_access.fetch_whoami_v2", fake_fetch_whoami_v2)assert await fetch_hf_user_plan("hf-token") == "pro"123489 unmodified lines949596from agent.core.hf_access import (is_billing_error,is_inference_billing_error,jobs_access_from_whoami,89 unmodified linesassert normalize_hf_user_plan({"isPro": False}) == "free"assert normalize_hf_user_plan({"plan": "HF Pro"}) == "free"assert normalize_hf_user_plan(None) is None
5 unmodified lines67891011123 unmodified lines16171819202122232425262728293031325 unmodified linesfrom agent.config import Configfrom agent.core import agent_loopfrom agent.core.agent_loop import _needs_approvalfrom agent.core.session import OpTypefrom agent.core.tools import create_builtin_toolsfrom agent.tools.jobs_tool import HF_JOBS_TOOL_SPEC3 unmodified linesdef test_default_cpu_sandbox_create_does_not_require_approval():config = SimpleNamespace(yolo_mode=False)assert _needs_approval("sandbox_create", {}, config) is Falseassert _needs_approval("sandbox_create", {"hardware": "cpu-basic"}, config) is Falsedef test_non_default_sandbox_create_still_requires_approval():config = SimpleNamespace(yolo_mode=False)assert (_needs_approval("sandbox_create", {"hardware": "cpu-upgrade"}, config) is True)assert _needs_approval("sandbox_create", {"hardware": "t4-small"}, config) is Truedef test_prompt_and_tool_specs_do_not_require_cpu_sandbox_create():5 unmodified lines67891011123 unmodified lines16171819202122232425262728293031323334353637385 unmodified linesfrom agent.config import Configfrom agent.core import agent_loopfrom agent.core.agent_loop import _base_needs_approvalfrom agent.core.session import OpTypefrom agent.core.tools import create_builtin_toolsfrom agent.tools.jobs_tool import HF_JOBS_TOOL_SPEC3 unmodified linesdef test_default_cpu_sandbox_create_does_not_require_approval():config = SimpleNamespace(yolo_mode=False)assert _base_needs_approval("sandbox_create", {}, config) is Falseassert (_base_needs_approval("sandbox_create", {"hardware": "cpu-basic"}, config)is False)def test_non_default_sandbox_create_still_requires_approval():config = SimpleNamespace(yolo_mode=False)assert (_base_needs_approval("sandbox_create", {"hardware": "cpu-upgrade"}, config)is True)assert (_base_needs_approval("sandbox_create", {"hardware": "t4-small"}, config) is True)def test_prompt_and_tool_specs_do_not_require_cpu_sandbox_create():
331 unmodified lines33233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136235 unmodified lines398399400401402403404119 unmodified lines524525526527528529530331 unmodified linesassert "Visibility: private" in outdef test_orphan_sweep_preserves_spaces_without_last_modified():deleted: list[str] = []logs: list[str] = []class FakeApi:def list_spaces(self, **kwargs):assert kwargs["full"] is Truereturn [SimpleNamespace(id="alice/sandbox-12345678")]def delete_repo(self, repo_id, repo_type):deleted.append(repo_id)count = sandbox_tool._cleanup_user_orphan_sandboxes(FakeApi(),"alice",logs.append,)assert count == 0assert deleted == []assert logs == ["orphan sweep: skipping alice/sandbox-12345678; missing lastModified"]def test_ensure_sandbox_overrides_private_argument(monkeypatch):captured_kwargs = {}persisted: list[dict] = []35 unmodified linespassmonkeypatch.setattr(sandbox_tool, "HfApi", FakeApi)monkeypatch.setattr(sandbox_tool, "_cleanup_user_orphan_sandboxes", lambda *args: 0)monkeypatch.setattr(Sandbox, "create", staticmethod(fake_create))monkeypatch.setattr(telemetry, "record_sandbox_create", fake_record_sandbox_create)monkeypatch.setattr("huggingface_hub.metadata_update", _fail_metadata_update)119 unmodified linespassmonkeypatch.setattr(sandbox_tool, "HfApi", FakeApi)monkeypatch.setattr(sandbox_tool, "_cleanup_user_orphan_sandboxes", lambda *args: 0)monkeypatch.setattr(Sandbox, "create", staticmethod(fake_create))monkeypatch.setattr(telemetry, "record_sandbox_create", fake_record_sandbox_create)monkeypatch.setattr("huggingface_hub.metadata_update", _fail_metadata_update)331 unmodified lines33233333433533633735 unmodified lines373374375376377378119 unmodified lines498499500501502503331 unmodified linesassert "Visibility: private" in outdef test_ensure_sandbox_overrides_private_argument(monkeypatch):captured_kwargs = {}persisted: list[dict] = []35 unmodified linespassmonkeypatch.setattr(sandbox_tool, "HfApi", FakeApi)monkeypatch.setattr(Sandbox, "create", staticmethod(fake_create))monkeypatch.setattr(telemetry, "record_sandbox_create", fake_record_sandbox_create)monkeypatch.setattr("huggingface_hub.metadata_update", _fail_metadata_update)119 unmodified linespassmonkeypatch.setattr(sandbox_tool, "HfApi", FakeApi)monkeypatch.setattr(Sandbox, "create", staticmethod(fake_create))monkeypatch.setattr(telemetry, "record_sandbox_create", fake_record_sandbox_create)monkeypatch.setattr("huggingface_hub.metadata_update", _fail_metadata_update)
323 unmodified lines324325326327328329323 unmodified linesassert source == "app_telemetry_session"@pytest.mark.asyncioasync def test_usage_threshold_checker_creates_synthetic_pending_approval(monkeypatch):manager = _manager_with_store(NoopSessionStore())323 unmodified lines324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506323 unmodified linesassert source == "app_telemetry_session"@pytest.mark.asyncioasync def test_refresh_usage_metrics_uses_hf_billing_plus_sandbox(monkeypatch):manager = _manager_with_store(NoopSessionStore())agent_session = _runtime_agent_session("s1", hf_token="owner-token")agent_session.session.logged_events = [{"timestamp": "2026-06-01T12:00:00+00:00","event_type": "llm_call","data": {"cost_usd": 0.5, "total_tokens": 42},},{"timestamp": "2026-06-01T12:05:00+00:00","event_type": "hf_job_complete","data": {"estimated_cost_usd": 1.0},},{"timestamp": "2026-06-01T12:10:00+00:00","event_type": "sandbox_create","data": {"sandbox_id": "owner/sandbox-1", "hardware": "t4-small"},},{"timestamp": "2026-06-01T12:40:00+00:00","event_type": "sandbox_destroy","data": {"sandbox_id": "owner/sandbox-1", "lifetime_s": 1800},},]async def fake_billing_snapshot(_manager, *, hf_token, session_id, timezone_name):assert hf_token == "owner-token"assert session_id == "s1"assert timezone_name == "UTC"return {"billing_scope": "account_window_delta","hf_billing": {"source": "hf_billing_usage_v2","available": True,"current_session": {"window_start": "2026-06-01T12:00:00Z","window_end": "2026-06-01T12:40:00Z","timezone": "UTC","total_usd": 4.0,"inference_providers_usd": 3.0,"hf_jobs_usd": 1.0,"inference_provider_requests": 6,"hf_jobs_minutes": 2.0,"access_token": "must-not-persist",},},"month": {"total_usd": 999},"inference_providers_credits": {"limit_usd": 999},}monkeypatch.setattr("usage.build_hf_billing_snapshot", fake_billing_snapshot)metrics = await manager.refresh_session_usage_metrics(agent_session)assert metrics["total_usd"] == 4.3assert metrics["total_usd_source"] == "hf_billing_plus_sandbox_estimate"assert metrics["app_total_usd"] == 1.8assert metrics["hf_billing_total_usd"] == 4.0assert agent_session.session.usage_metrics == metricsassert agent_session.session.usage_hf_billing_snapshot == {"billing_scope": "account_window_delta","hf_billing": {"source": "hf_billing_usage_v2","available": True,"error": None,"current_session": {"window_start": "2026-06-01T12:00:00Z","window_end": "2026-06-01T12:40:00Z","timezone": "UTC","total_usd": 4.0,"inference_providers_usd": 3.0,"hf_jobs_usd": 1.0,"inference_provider_requests": 6,"hf_jobs_minutes": 2.0,},},}@pytest.mark.asyncioasync def test_refresh_usage_metrics_missing_token_falls_back_to_app_telemetry():manager = _manager_with_store(NoopSessionStore())agent_session = _runtime_agent_session("s1", hf_token=None)agent_session.session.hf_token = Noneagent_session.session.logged_events = [{"timestamp": "2026-06-01T12:00:00+00:00","event_type": "llm_call","data": {"cost_usd": 2.0, "total_tokens": 10},}]metrics = await manager.refresh_session_usage_metrics(agent_session)assert metrics["total_usd"] == 2.0assert metrics["total_usd_source"] == "app_telemetry_fallback"assert metrics["hf_billing"] == {"source": "hf_billing_usage_v2","available": False,"error": "missing_hf_token","current_session": None,}@pytest.mark.asyncioasync def test_refresh_usage_metrics_failure_records_error_code(monkeypatch):manager = _manager_with_store(NoopSessionStore())agent_session = _runtime_agent_session("s1", hf_token="owner-token")agent_session.session.logged_events = [{"timestamp": "2026-06-01T12:00:00+00:00","event_type": "llm_call","data": {"cost_usd": 2.0, "total_tokens": 10},}]async def fail_billing_snapshot(*_args, **_kwargs):raise RuntimeError("boom")monkeypatch.setattr("usage.build_hf_billing_snapshot", fail_billing_snapshot)metrics = await manager.refresh_session_usage_metrics(agent_session,error_code="unit_billing_error",)assert metrics["total_usd"] == 2.0assert metrics["total_usd_source"] == "app_telemetry_fallback"assert metrics["hf_billing"] == {"source": "hf_billing_usage_v2","available": False,"error": "unit_billing_error","current_session": None,}@pytest.mark.asyncioasync def test_refresh_usage_metrics_timeout_records_error_code(monkeypatch):manager = _manager_with_store(NoopSessionStore())agent_session = _runtime_agent_session("s1", hf_token="owner-token")agent_session.session.logged_events = [{"timestamp": "2026-06-01T12:00:00+00:00","event_type": "llm_call","data": {"cost_usd": 2.0, "total_tokens": 10},}]async def slow_billing_snapshot(*_args, **_kwargs):await asyncio.sleep(0.05)return {"hf_billing": {"available": True,"current_session": {"total_usd": 999},}}monkeypatch.setattr("usage.build_hf_billing_snapshot", slow_billing_snapshot)metrics = await manager.refresh_session_usage_metrics(agent_session,error_code="unit_billing_timeout",billing_timeout_s=0.001,)assert metrics["total_usd"] == 2.0assert metrics["total_usd_source"] == "app_telemetry_fallback"assert metrics["hf_billing"] == {"source": "hf_billing_usage_v2","available": False,"error": "unit_billing_timeout","current_session": None,}@pytest.mark.asyncioasync def test_usage_threshold_checker_creates_synthetic_pending_approval(monkeypatch):manager = _manager_with_store(NoopSessionStore())
157 unmodified lines15815916016116216338 unmodified lines202203204157 unmodified linesassert "GITHUB_TOKEN=[REDACTED]" in payloaddef test_claude_code_payload_scrubs_messages_before_conversion(tmp_path):tmp_file = tmp_path / "claude_code.jsonl"data = {38 unmodified linesassert "[REDACTED_HF_TOKEN]" in payloadassert "[REDACTED_PROVIDER_API_KEY]" in payloadassert "GITHUB_TOKEN=[REDACTED]" in payload157 unmodified lines15815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322438 unmodified lines263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302157 unmodified linesassert "GITHUB_TOKEN=[REDACTED]" in payloaddef test_row_payload_includes_usage_scalars_and_parseable_metrics(tmp_path):tmp_file = tmp_path / "row.jsonl"data = {"session_id": "session-123","user_id": "lewtun","session_start_time": "2026-01-01T00:00:00","session_end_time": "2026-01-01T00:30:00","model_name": "anthropic/claude-opus-4.8:fal-ai","total_cost_usd": 0.01,"messages": [{"role": "user", "content": "hello"}],"events": [{"timestamp": "2026-01-01T00:00:01+00:00","event_type": "llm_call","data": {"cost_usd": 0.01, "total_tokens": 42},},{"timestamp": "2026-01-01T00:00:02+00:00","event_type": "hf_job_submit","data": {"flavor": "cpu-basic"},},{"timestamp": "2026-01-01T00:00:03+00:00","event_type": "turn_complete","data": {},},],"tools": [{"name": "bash"}],}_write_row_payload(data, str(tmp_file))row = json.loads(tmp_file.read_text())assert row["session_id"] == "session-123"assert row["user_id"] == "lewtun"assert row["session_start_time"] == "2026-01-01T00:00:00"assert row["session_end_time"] == "2026-01-01T00:30:00"assert row["model_name"] == "anthropic/claude-opus-4.8:fal-ai"assert row["total_cost_usd"] == 0.01assert json.loads(row["messages"]) == data["messages"]assert json.loads(row["events"]) == data["events"]assert json.loads(row["tools"]) == data["tools"]metrics = json.loads(row["usage_metrics"])assert metrics["version"] == 1assert metrics["llm"]["calls"] == 1assert metrics["llm"]["total_tokens"] == 42assert metrics["hf_jobs"]["submits"] == 1assert metrics["turns"]["turn_complete_count"] == 1assert row["usage_total_usd"] == 0.01assert row["usage_total_usd_source"] == "app_telemetry_fallback"assert row["usage_app_total_usd"] == 0.01assert row["usage_hf_billing_total_usd"] is Noneassert row["usage_llm_calls"] == 1assert row["usage_total_tokens"] == 42assert row["usage_hf_job_submits"] == 1assert row["usage_hf_job_status_snapshots"] == 0assert row["usage_sandbox_creates"] == 0assert row["usage_sandbox_pairs"] == 0def test_claude_code_payload_scrubs_messages_before_conversion(tmp_path):tmp_file = tmp_path / "claude_code.jsonl"data = {38 unmodified linesassert "[REDACTED_HF_TOKEN]" in payloadassert "[REDACTED_PROVIDER_API_KEY]" in payloadassert "GITHUB_TOKEN=[REDACTED]" in payloaddef test_claude_code_payload_ignores_usage_metrics(tmp_path):base = {"session_id": "session-123","model_name": "anthropic/claude-opus-4.8:fal-ai","session_start_time": "2026-01-01T00:00:00","messages": [{"role": "user","content": "hello","timestamp": "2026-01-01T00:00:01",},{"role": "assistant","content": "hi","timestamp": "2026-01-01T00:00:02",},],}without_metrics = tmp_path / "without.jsonl"with_metrics = tmp_path / "with.jsonl"_write_claude_code_payload(base, str(without_metrics))_write_claude_code_payload({**base,"usage_metrics": {"version": 1,"total_usd": 123,"hf_billing": {"available": True},},},str(with_metrics),)assert with_metrics.read_text() == without_metrics.read_text()
13 unmodified lines14151617181920212223149 unmodified lines1731741751761771782 unmodified lines181182183184185186130 unmodified lines31731831932032132213 unmodified lines_account_bucket_from_billing_usage,_session_bucket_from_inference_session_usage,aggregate_usage_events,build_usage_response,resolve_usage_windows,)from agent.core import session_persistence # noqa: E402BILLING_SESSION_ID = "00000000-0000-4000-8000-000000000001"149 unmodified linesassert usage["total_usd"] == 0.3def test_usage_event_type_allowlists_include_sandbox_lifecycle():assert set(USAGE_EVENT_TYPES) >= {"sandbox_create", "sandbox_destroy"}assert set(session_persistence.USAGE_EVENT_TYPES) >= {2 unmodified lines}def test_account_bucket_from_hf_billing_usage_v2():usage = _account_bucket_from_billing_usage({130 unmodified lines)@pytest.mark.asyncioasync def test_usage_response_omits_app_rollups_without_session():manager = _Manager(13 unmodified lines141516171819202122232425262728149 unmodified lines1781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192 unmodified lines222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415130 unmodified lines54654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361413 unmodified lines_account_bucket_from_billing_usage,_session_bucket_from_inference_session_usage,aggregate_usage_events,build_hf_billing_snapshot,build_usage_response,resolve_usage_windows,)from agent.core import session_persistence # noqa: E402from agent.core.usage_metrics import ( # noqa: E402summarize_usage_events,usage_metric_scalar_fields,)BILLING_SESSION_ID = "00000000-0000-4000-8000-000000000001"149 unmodified linesassert usage["total_usd"] == 0.3def test_sandbox_lifecycle_pairing_is_shared_for_duplicate_creates():events = [_event("sandbox_create",{"sandbox_id": "alice/sandbox-reused", "hardware": "t4-small"},created_at="2026-06-01T12:00:00+00:00",),_event("sandbox_create",{"sandbox_id": "alice/sandbox-reused", "hardware": "cpu-basic"},created_at="2026-06-01T12:05:00+00:00",),_event("sandbox_destroy",{"sandbox_id": "alice/sandbox-reused", "lifetime_s": 300},created_at="2026-06-01T12:10:00+00:00",),_event("sandbox_destroy",{"sandbox_id": "alice/sandbox-reused", "lifetime_s": 1200},created_at="2026-06-01T12:20:00+00:00",),]usage = aggregate_usage_events(events, session_id="s1")metrics = summarize_usage_events(events, session_id="s1")assert usage["sandbox_count"] == 2assert usage["sandbox_billable_seconds_estimate"] == 1200assert usage["sandbox_estimated_usd"] == 0.2assert metrics["sandboxes"]["matched_pairs"] == usage["sandbox_count"]assert metrics["sandboxes"]["unpaired_creates"] == 0assert metrics["sandboxes"]["unpaired_destroys"] == 0assert metrics["sandboxes"]["estimated_usd"] == usage["sandbox_estimated_usd"]def test_usage_event_type_allowlists_include_sandbox_lifecycle():assert set(USAGE_EVENT_TYPES) >= {"sandbox_create", "sandbox_destroy"}assert set(session_persistence.USAGE_EVENT_TYPES) >= {2 unmodified lines}def test_summarize_usage_events_aggregates_dataset_analytics():events = [_event("llm_call",{"model": "model-a","kind": "main","cost_usd": 0,"prompt_tokens": 10,"completion_tokens": 5,"cache_read_tokens": 2,},),_event("llm_call",{"model": "model-b","kind": "research","cost_usd": 0.125,"prompt_tokens": 20,"completion_tokens": 10,"cache_creation_tokens": 3,"total_tokens": 40,},),_event("hf_job_submit", {"flavor": "a10g-small"}),_event("hf_job_complete",{"flavor": "a10g-small","final_status": "succeeded","estimated_cost_usd": 0.5,"billable_seconds_estimate": 600,},),_event("hf_job_complete",{"flavor": "cpu-basic","final_status": "failed","wall_time_s": 30,},),_event("sandbox_create",{"sandbox_id": "alice/sandbox-1", "hardware": "t4-small"},created_at="2026-06-01T12:00:00+00:00",),_event("sandbox_destroy",{"sandbox_id": "alice/sandbox-1", "lifetime_s": 1800},created_at="2026-06-01T12:30:00+00:00",),_event("sandbox_create",{"sandbox_id": "alice/sandbox-2", "hardware": "a100-large"},created_at="2026-06-01T13:00:00+00:00",),_event("sandbox_destroy",{"sandbox_id": "alice/sandbox-missing", "lifetime_s": 60},created_at="2026-06-01T13:05:00+00:00",),_event("turn_complete"),_event("assistant_stream_end"),{"event_type": "debug", "data": {}},]metrics = summarize_usage_events(events, session_id="s1")assert metrics["version"] == 1assert metrics["total_usd_source"] == "app_telemetry_fallback"assert metrics["total_usd"] == 0.925assert metrics["llm"] == {"calls": 2,"calls_by_kind": {"main": 1, "research": 1},"calls_by_model": {"model-a": 1, "model-b": 1},"prompt_tokens": 30,"completion_tokens": 15,"cache_read_tokens": 2,"cache_creation_tokens": 3,"total_tokens": 57,}assert metrics["turns"] == {"turn_complete_count": 1,"assistant_stream_end_count": 1,}assert metrics["hf_jobs"]["submits"] == 1assert metrics["hf_jobs"]["status_snapshots"] == 2assert metrics["hf_jobs"]["statuses"] == {"failed": 1, "succeeded": 1}assert metrics["hf_jobs"]["flavors"] == {"a10g-small": 2,"cpu-basic": 1,}assert metrics["hf_jobs"]["estimated_usd"] == 0.5assert metrics["hf_jobs"]["billable_seconds_estimate"] == 630assert metrics["sandboxes"]["creates"] == 2assert metrics["sandboxes"]["destroys"] == 2assert metrics["sandboxes"]["matched_pairs"] == 1assert metrics["sandboxes"]["unpaired_creates"] == 1assert metrics["sandboxes"]["unpaired_destroys"] == 1assert metrics["sandboxes"]["hardware"] == {"a100-large": 1, "t4-small": 1}assert metrics["sandboxes"]["estimated_usd"] == 0.3assert metrics["sandboxes"]["billable_seconds_estimate"] == 1800assert metrics["data_quality"] == {"event_count": 12,"events_without_timestamp": 1,"llm_calls_with_cost_usd": 2,"llm_calls_with_nonzero_cost_usd": 1,"job_snapshots_with_estimated_cost": 1,"job_snapshots_missing_estimated_cost": 1,}assert usage_metric_scalar_fields(metrics) == {"usage_total_usd": 0.925,"usage_total_usd_source": "app_telemetry_fallback","usage_app_total_usd": 0.925,"usage_hf_billing_total_usd": None,"usage_llm_calls": 2,"usage_total_tokens": 57,"usage_hf_job_submits": 1,"usage_hf_job_status_snapshots": 2,"usage_sandbox_creates": 2,"usage_sandbox_pairs": 1,}def test_summarize_usage_events_uses_hf_billing_plus_sandbox_when_available():events = [_event("llm_call", {"cost_usd": 99.0, "total_tokens": 10}),_event("hf_job_complete", {"estimated_cost_usd": 99.0}),_event("sandbox_create",{"sandbox_id": "alice/sandbox-1", "hardware": "t4-small"},created_at="2026-06-01T12:00:00+00:00",),_event("sandbox_destroy",{"sandbox_id": "alice/sandbox-1", "lifetime_s": 1800},created_at="2026-06-01T12:30:00+00:00",),]metrics = summarize_usage_events(events,session_id="s1",hf_billing_snapshot={"hf_billing": {"source": "hf_billing_usage_v2","available": True,"current_session": {"window_start": "2026-06-01T12:00:00Z","window_end": "2026-06-01T12:30:00Z","timezone": "UTC","total_usd": 1.25,"inference_providers_usd": 1.0,"hf_jobs_usd": 0.25,"inference_provider_requests": 3,"hf_jobs_minutes": 1.5,"unexpected": "dropped",},},"month": {"total_usd": 999},"inference_providers_credits": {"limit_usd": 999},},)assert metrics["total_usd"] == 1.55assert metrics["total_usd_source"] == "hf_billing_plus_sandbox_estimate"assert metrics["app_total_usd"] == 198.3assert metrics["hf_billing_total_usd"] == 1.25assert metrics["hf_billing"] == {"source": "hf_billing_usage_v2","available": True,"error": None,"current_session": {"window_start": "2026-06-01T12:00:00Z","window_end": "2026-06-01T12:30:00Z","timezone": "UTC","total_usd": 1.25,"inference_providers_usd": 1.0,"hf_jobs_usd": 0.25,"inference_provider_requests": 3,"hf_jobs_minutes": 1.5,},}def test_account_bucket_from_hf_billing_usage_v2():usage = _account_bucket_from_billing_usage({130 unmodified lines)@pytest.mark.asyncioasync def test_hf_billing_snapshot_uses_session_window_without_account_totals(monkeypatch,):usage_window_started_at = datetime(2026, 6, 5, 12, 30, tzinfo=UTC)manager = _Manager({"s1": SimpleNamespace(session_id="s1",user_id="owner",created_at=datetime(2026, 6, 5, 12, 0, tzinfo=UTC),usage_window_started_at=usage_window_started_at,session=SimpleNamespace(logged_events=[]),)})calls = []async def fake_usage_v2(_token, *, start, end):calls.append((start, end))return {"usage": {"inferenceProviders": {"usedNanoUsd": 1_500_000_000,"includedNanoUsd": 2_000_000_000,"limitNanoUsd": 5_000_000_000,"numRequests": 4,},"jobs": {"usedMicroUsd": 250_000, "totalMinutes": 3.5},}}monkeypatch.setattr("usage._fetch_hf_billing_usage_v2", fake_usage_v2)snapshot = await build_hf_billing_snapshot(manager,hf_token="hf_fake",session_id="s1",timezone_name="UTC",now=datetime(2026, 6, 5, 13, 0, tzinfo=UTC),)assert calls == [(usage_window_started_at, datetime(2026, 6, 5, 13, 0, tzinfo=UTC))]assert snapshot == {"billing_scope": "account_window_delta","hf_billing": {"source": "hf_billing_usage_v2","available": True,"error": None,"current_session": {"window_start": "2026-06-05T12:30:00Z","window_end": "2026-06-05T13:00:00Z","timezone": "UTC","total_usd": 1.75,"inference_providers_usd": 1.5,"hf_jobs_usd": 0.25,"inference_provider_requests": 4,"hf_jobs_minutes": 3.5,},},}@pytest.mark.asyncioasync def test_usage_response_omits_app_rollups_without_session():manager = _Manager(
1774 unmodified lines177517761777177817791780178140 unmodified lines18221823182418251826182718281774 unmodified linessource = { editable = "." }dependencies = [{ name = "apscheduler" },{ name = "boto3" },{ name = "datasets" },{ name = "fastapi" },{ name = "fastmcp" },40 unmodified lines[package.metadata]requires-dist = [{ name = "apscheduler", specifier = ">=3.10,<4" },{ name = "boto3", specifier = ">=1.35.0" },{ name = "datasets", specifier = ">=4.4.1" },{ name = "datasets", marker = "extra == 'eval'", specifier = ">=4.3.0" },{ name = "fastapi", specifier = ">=0.115.0" },1774 unmodified lines17751776177717781779178040 unmodified lines1821182218231824182518261774 unmodified linessource = { editable = "." }dependencies = [{ name = "apscheduler" },{ name = "datasets" },{ name = "fastapi" },{ name = "fastmcp" },40 unmodified lines[package.metadata]requires-dist = [{ name = "apscheduler", specifier = ">=3.10,<4" },{ name = "datasets", specifier = ">=4.4.1" },{ name = "datasets", marker = "extra == 'eval'", specifier = ">=4.3.0" },{ name = "fastapi", specifier = ">=0.115.0" },
AGENTS.md+1
agent/README.md+1-1
agent/core/agent_loop.py-11
agent/core/hf_access.py-13
agent/core/hf_router_catalog.py-14
agent/core/model_ids.py-2
agent/core/session.py+17-21
agent/core/session_persistence.py-7
agent/core/session_uploader.py+25
agent/core/telemetry.py-24
agent/core/tools.py-6
agent/core/usage_metrics.pyAdded+448
agent/core/usage_thresholds.py+1-3
agent/tools/hf_repo_files_tool.py+1-3
agent/tools/hf_repo_git_tool.py+1-18
agent/tools/jobs_tool.py+1-19
agent/tools/papers_tool.py-13
agent/tools/private_hf_repo_tools.pyDeleted-650
agent/tools/sandbox_client.py-27
agent/tools/sandbox_tool.py+1-64
agent/utils/particle_logo.py-4
backend/dependencies.py-53
backend/main.py+27-9
backend/models.py-1
backend/routes/agent.py+41-7
backend/session_manager.py+73-21
backend/usage.py+68-77
frontend/src/components/Chat/ThinkingIndicator.tsxDeleted-48
frontend/src/components/UsageMeter.tsx+1-1
frontend/src/theme.ts-3
frontend/src/types/agent.ts-7
frontend/src/types/events.ts-65
pyproject.toml-1
scripts/sweep_orphan_sandboxes.py-1
tests/integration/test_live_thinking_models.py+3-3
tests/unit/test_auto_approval_policy.py-3
tests/unit/test_hf_access.py-28
tests/unit/test_sandbox_auto_start.py+11-5
tests/unit/test_sandbox_private_spaces.py-27
tests/unit/test_session_manager_persistence.py+177
tests/unit/test_session_uploader.py+98
tests/unit/test_usage.py+292
uv.lock-2