Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Commit ·
2ca459e
1
Parent(s): 4d8a789
ported the hf jobs tool to python
Browse filesFiles changed (28)
- agent/config_local_mcp.jsonDeleted-16
- agent/core/__init__.py+1-2
- agent/core/tools.py+8-88
- agent/tests/__init__.pyDeleted-3
- agent/tests/unit/test_base.pyDeleted-10
- agent/tools/__init__.pyAdded+8
- agent/tools/hf/__init__.pyDeleted-7
- agent/tools/hf/base.pyDeleted-84
- agent/tools/hf/jobs/__init__.pyDeleted-6
- agent/tools/hf/jobs/api_client.pyDeleted-156
- agent/tools/hf/jobs/job_utils.pyDeleted-130
- agent/tools/hf/jobs/uv_utils.pyDeleted-66
- agent/tools/hf/jobs/jobs_tool.py → agent/tools/jobs_tool.pyRenamed+471-287
- agent/tools/hf/types.py → agent/tools/types.pyRenamed+3-1
- agent/tools/hf/utilities.py → agent/tools/utilities.pyRenamed+49-40
- pyproject.toml+1
- tests/__init__.pyAdded
- tests/integration/__init__.pyAdded
- tests/integration/tools/__init__.pyAdded
- tests/integration/tools/test_jobs_integration.pyAdded+452
- tests/tools/__init__.pyDeleted-1
- tests/tools/hf/__init__.pyDeleted-1
- tests/tools/hf/jobs/__init__.pyDeleted-1
- tests/tools/hf/jobs/test_jobs_tool.pyDeleted-252
- tests/unit/__init__.pyAdded
- tests/unit/tools/__init__.pyAdded
- tests/unit/tools/test_jobs_tool.pyAdded+454
- uv.lock+36
12345678910111213141516{ "model_name": "anthropic/claude-sonnet-4-5-20250929", "tools": [], "system_prompt_path": "", "mcpServers": { "hf-mcp-server": { "command": "node", "args": [ "/Users/akseljoonas/Documents/hf-agent/hf-mcp-server/packages/app/dist/server/stdio.js" ], "env": { "DEFAULT_HF_TOKEN": "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" } } }}2 unmodified lines34567891011122 unmodified linesContains the main agent logic, decision-making, and orchestration"""from agent.core.tools import ToolRouter, ToolSpec, create_builtin_tools__all__ = ["ToolRouter","ToolSpec","create_builtin_tools",]2 unmodified lines345678910112 unmodified linesContains the main agent logic, decision-making, and orchestration"""from agent.core.tools import ToolRouter, ToolSpec__all__ = ["ToolRouter","ToolSpec",]
2 unmodified lines34567893 unmodified lines1314151617181920212223242579 unmodified lines10510610710810911063 unmodified lines1741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682 unmodified linesProvides ToolSpec and ToolRouter for managing both built-in and MCP tools"""import subprocessimport warningsfrom dataclasses import dataclassfrom typing import Any, Awaitable, Callable, Optional3 unmodified linesfrom mcp.types import EmbeddedResource, ImageContent, TextContentfrom agent.config import MCPServerConfigfrom agent.tools.hf.jobs import HF_JOBS_TOOL_SPEC, hf_jobs_handler# Suppress aiohttp deprecation warningwarnings.filterwarnings("ignore", category=DeprecationWarning, module="aiohttp.connector")def convert_mcp_content_to_string(content: list) -> str:"""79 unmodified linesasync def register_mcp_tools(self) -> None:tools = await self.mcp_client.list_tools()for tool in tools:self.register_tool(ToolSpec(name=tool.name,63 unmodified lines# ============================================================================async def bash_handler(arguments: dict[str, Any]) -> tuple[str, bool]:"""Execute bash command"""try:command = arguments.get("command", "")result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=30)output = result.stdout if result.returncode == 0 else result.stderrsuccess = result.returncode == 0return output, successexcept Exception as e:return f"Error: {str(e)}", Falseasync def read_file_handler(arguments: dict[str, Any]) -> tuple[str, bool]:"""Read file contents"""try:path = arguments.get("path", "")with open(path, "r") as f:content = f.read()return content, Trueexcept Exception as e:return f"Error reading file: {str(e)}", Falseasync def write_file_handler(arguments: dict[str, Any]) -> tuple[str, bool]:"""Write to file"""try:path = arguments.get("path", "")content = arguments.get("content", "")with open(path, "w") as f:f.write(content)return f"Successfully wrote to {path}", Trueexcept Exception as e:return f"Error writing file: {str(e)}", Falsedef create_builtin_tools() -> list[ToolSpec]:"""Create built-in tool specifications"""return [ToolSpec(name="bash",description="Execute a bash command and return its output",parameters={"type": "object","properties": {"command": {"type": "string","description": "The bash command to execute",}},"required": ["command"],},handler=bash_handler,),ToolSpec(name="read_file",description="Read the contents of a file",parameters={"type": "object","properties": {"path": {"type": "string","description": "Path to the file to read",}},"required": ["path"],},handler=read_file_handler,),ToolSpec(name="write_file",description="Write content to a file",parameters={"type": "object","properties": {"path": {"type": "string","description": "Path to the file to write",},"content": {"type": "string","description": "Content to write to the file",},},"required": ["path", "content"],},handler=write_file_handler,),ToolSpec(name=HF_JOBS_TOOL_SPEC["name"],description=HF_JOBS_TOOL_SPEC["description"],2 unmodified lines3456783 unmodified lines12131415161718192021222324252679 unmodified lines10610710810911011111211311411563 unmodified lines1791801811821831841851861871882 unmodified linesProvides ToolSpec and ToolRouter for managing both built-in and MCP tools"""import warningsfrom dataclasses import dataclassfrom typing import Any, Awaitable, Callable, Optional3 unmodified linesfrom mcp.types import EmbeddedResource, ImageContent, TextContentfrom agent.config import MCPServerConfigfrom agent.tools.jobs_tool import HF_JOBS_TOOL_SPEC, hf_jobs_handler# Suppress aiohttp deprecation warningwarnings.filterwarnings("ignore", category=DeprecationWarning, module="aiohttp.connector")NOT_ALLOWED_TOOL_NAMES = ["hf_jobs"]def convert_mcp_content_to_string(content: list) -> str:"""79 unmodified linesasync def register_mcp_tools(self) -> None:tools = await self.mcp_client.list_tools()for tool in tools:if tool.name in NOT_ALLOWED_TOOL_NAMES:print(f"Skipping not MCP allowed tool: {tool.name}")continueprint(f"MCP Tool: {tool.name}")self.register_tool(ToolSpec(name=tool.name,63 unmodified lines# ============================================================================def create_builtin_tools() -> list[ToolSpec]:"""Create built-in tool specifications"""print(f"Creating built-in tools: {HF_JOBS_TOOL_SPEC['name']}")return [ToolSpec(name=HF_JOBS_TOOL_SPEC["name"],description=HF_JOBS_TOOL_SPEC["description"],
123"""Test suite for HF Agent"""12345678910"""Unit tests for base agent components"""
def test_base_agent_initialization(): """Test that BaseAgent can be initialized with config""" # This will fail because BaseAgent is abstract # Subclasses should implement this pass12345678"""Hugging Face tools for the agent"""
from agent.tools.jobs_tool import HF_JOBS_TOOL_SPEC, HfJobsTool, hf_jobs_handlerfrom agent.tools.types import ToolResult
__all__ = ["ToolResult", "HF_JOBS_TOOL_SPEC", "hf_jobs_handler", HfJobsTool]1234567"""Hugging Face tools for the agent"""from agent.tools.hf.types import ToolResultfrom agent.tools.hf.base import HfApiCall, HfApiError
__all__ = ['ToolResult', 'HfApiCall', 'HfApiError']123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384"""Base API client for Hugging Face API
Ported from: hf-mcp-server/packages/mcp/src/hf-api-call.ts"""import osfrom typing import Optional, Dict, Any, TypeVar, Genericimport httpx
TResponse = TypeVar('TResponse')
class HfApiError(Exception): """Error from Hugging Face API"""
def __init__( self, message: str, status: Optional[int] = None, status_text: Optional[str] = None, response_body: Optional[str] = None ): super().__init__(message) self.message = message self.status = status self.status_text = status_text self.response_body = response_body
class HfApiCall(Generic[TResponse]): """Base class for making authenticated API calls to Hugging Face"""
def __init__( self, api_url: str, hf_token: Optional[str] = None, api_timeout: Optional[float] = None ): self.api_url = api_url self.hf_token = hf_token or os.getenv('HF_TOKEN') self.api_timeout = api_timeout or float(os.getenv('HF_API_TIMEOUT', '12.5'))
async def fetch_from_api( self, url: str, method: str = "GET", json: Optional[Dict[str, Any]] = None, **kwargs ) -> Optional[Any]: """Fetch data from API with auth and error handling""" headers = { "Accept": "application/json", **kwargs.pop("headers", {}) }
if self.hf_token: headers["Authorization"] = f"Bearer {self.hf_token}"
async with httpx.AsyncClient(timeout=self.api_timeout) as client: if method == "GET": response = await client.get(url, headers=headers, **kwargs) elif method == "POST": response = await client.post(url, headers=headers, json=json, **kwargs) elif method == "DELETE": response = await client.delete(url, headers=headers, **kwargs) elif method == "PUT": response = await client.put(url, headers=headers, json=json, **kwargs) else: raise ValueError(f"Unsupported HTTP method: {method}")
if not response.is_success: raise HfApiError( message=f"API request failed: {response.status_code} {response.reason_phrase}", status=response.status_code, status_text=response.reason_phrase, response_body=response.text )
# Handle empty responses (DELETE often returns empty) if not response.text: return None
return response.json()123456"""Hugging Face Jobs tool"""from agent.tools.hf.jobs.jobs_tool import HfJobsTool, HF_JOBS_TOOL_SPEC, hf_jobs_handler
__all__ = ['HfJobsTool', 'HF_JOBS_TOOL_SPEC', 'hf_jobs_handler']123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156"""Jobs API Client
Ported from: hf-mcp-server/packages/mcp/src/jobs/api-client.ts"""from typing import Optional, Dict, Any, Listfrom agent.tools.hf.base import HfApiCall
class JobsApiClient(HfApiCall): """API client for HuggingFace Jobs API"""
def __init__(self, hf_token: Optional[str] = None, namespace: Optional[str] = None): super().__init__('https://huggingface.co/api', hf_token) self.namespace_cache = namespace
async def get_namespace(self, namespace: Optional[str] = None) -> str: """ Get the namespace (username or org) for the current user Uses cached value or /api/whoami-v2 endpoint as fallback """ if namespace: return namespace
if self.namespace_cache: return self.namespace_cache
# Fetch from whoami endpoint whoami = await self.fetch_from_api('https://huggingface.co/api/whoami-v2') self.namespace_cache = whoami['name'] return self.namespace_cache
async def run_job(self, job_spec: Dict[str, Any], namespace: Optional[str] = None) -> Dict[str, Any]: """ Run a job POST /api/jobs/{namespace} """ ns = await self.get_namespace(namespace) url = f'https://huggingface.co/api/jobs/{ns}'
result = await self.fetch_from_api(url, method='POST', json=job_spec) return result
async def list_jobs(self, namespace: Optional[str] = None) -> List[Dict[str, Any]]: """ List all jobs for a namespace GET /api/jobs/{namespace} """ ns = await self.get_namespace(namespace) url = f'https://huggingface.co/api/jobs/{ns}'
return await self.fetch_from_api(url)
async def get_job(self, job_id: str, namespace: Optional[str] = None) -> Dict[str, Any]: """ Get detailed information about a specific job GET /api/jobs/{namespace}/{jobId} """ ns = await self.get_namespace(namespace) url = f'https://huggingface.co/api/jobs/{ns}/{job_id}'
return await self.fetch_from_api(url)
async def cancel_job(self, job_id: str, namespace: Optional[str] = None) -> None: """ Cancel a running job POST /api/jobs/{namespace}/{jobId}/cancel """ ns = await self.get_namespace(namespace) url = f'https://huggingface.co/api/jobs/{ns}/{job_id}/cancel'
await self.fetch_from_api(url, method='POST')
def get_logs_url(self, job_id: str, namespace: str) -> str: """Get logs URL for a job (for SSE streaming)""" return f'https://huggingface.co/api/jobs/{namespace}/{job_id}/logs'
async def create_scheduled_job( self, spec: Dict[str, Any], namespace: Optional[str] = None ) -> Dict[str, Any]: """ Create a scheduled job POST /api/scheduled-jobs/{namespace} """ ns = await self.get_namespace(namespace) url = f'https://huggingface.co/api/scheduled-jobs/{ns}'
return await self.fetch_from_api(url, method='POST', json=spec)
async def list_scheduled_jobs(self, namespace: Optional[str] = None) -> List[Dict[str, Any]]: """ List all scheduled jobs GET /api/scheduled-jobs/{namespace} """ ns = await self.get_namespace(namespace) url = f'https://huggingface.co/api/scheduled-jobs/{ns}'
return await self.fetch_from_api(url)
async def get_scheduled_job( self, scheduled_job_id: str, namespace: Optional[str] = None ) -> Dict[str, Any]: """ Get details of a scheduled job GET /api/scheduled-jobs/{namespace}/{scheduledJobId} """ ns = await self.get_namespace(namespace) url = f'https://huggingface.co/api/scheduled-jobs/{ns}/{scheduled_job_id}'
return await self.fetch_from_api(url)
async def delete_scheduled_job( self, scheduled_job_id: str, namespace: Optional[str] = None ) -> None: """ Delete a scheduled job DELETE /api/scheduled-jobs/{namespace}/{scheduledJobId} """ ns = await self.get_namespace(namespace) url = f'https://huggingface.co/api/scheduled-jobs/{ns}/{scheduled_job_id}'
await self.fetch_from_api(url, method='DELETE')
async def suspend_scheduled_job( self, scheduled_job_id: str, namespace: Optional[str] = None ) -> None: """ Suspend a scheduled job POST /api/scheduled-jobs/{namespace}/{scheduledJobId}/suspend """ ns = await self.get_namespace(namespace) url = f'https://huggingface.co/api/scheduled-jobs/{ns}/{scheduled_job_id}/suspend'
await self.fetch_from_api(url, method='POST')
async def resume_scheduled_job( self, scheduled_job_id: str, namespace: Optional[str] = None ) -> None: """ Resume a suspended scheduled job POST /api/scheduled-jobs/{namespace}/{scheduledJobId}/resume """ ns = await self.get_namespace(namespace) url = f'https://huggingface.co/api/scheduled-jobs/{ns}/{scheduled_job_id}/resume'
await self.fetch_from_api(url, method='POST')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130"""Job utility functions
Ported from: hf-mcp-server/packages/mcp/src/jobs/commands/utils.ts"""import reimport shlexfrom typing import Dict, Optional, Any, List, Union
def parse_timeout(timeout: str) -> int: """Parse timeout string (e.g., "5m", "2h", "30s") to seconds""" time_units = { 's': 1, 'm': 60, 'h': 3600, 'd': 86400, }
match = re.match(r'^(\d+(?:\.\d+)?)(s|m|h|d)$', timeout) if match: value = float(match.group(1)) unit = match.group(2) return int(value * time_units[unit])
# Try to parse as plain number (seconds) try: return int(timeout) except ValueError: raise ValueError( f'Invalid timeout format: "{timeout}". Use format like "5m", "2h", "30s", or plain seconds.' )
def parse_image_source(image: str) -> Dict[str, Optional[str]]: """ Detect if image is a Space URL and extract spaceId Returns {'dockerImage': ...} or {'spaceId': ...} """ space_prefixes = [ 'https://huggingface.co/spaces/', 'https://hf.co/spaces/', 'huggingface.co/spaces/', 'hf.co/spaces/', ]
for prefix in space_prefixes: if image.startswith(prefix): return {'dockerImage': None, 'spaceId': image[len(prefix):]}
# Not a space, treat as docker image return {'dockerImage': image, 'spaceId': None}
def parse_command(command: Union[str, List[str]]) -> Dict[str, Any]: """ Parse command string or array into command array Uses shlex for POSIX-compliant parsing """ # If already an array, return as-is if isinstance(command, list): return {'command': command, 'arguments': []}
# Parse the command string using shlex for POSIX-compliant parsing try: string_args = shlex.split(command) except ValueError as e: raise ValueError( f'Unsupported shell syntax in command: "{command}". ' f'Please use an array format for commands with complex shell operators. Error: {e}' )
if len(string_args) == 0: raise ValueError(f'Invalid command: "{command}". Command cannot be empty.')
return {'command': string_args, 'arguments': []}
def replace_token_placeholder(value: str, hf_token: Optional[str]) -> str: """Replace HF token placeholder with actual token if available""" if not hf_token: return value
if value in ('$HF_TOKEN', '${HF_TOKEN}'): return hf_token
return value
def transform_env_map( env_map: Optional[Dict[str, str]], hf_token: Optional[str]) -> Optional[Dict[str, str]]: """Transform environment map, replacing token placeholders""" if not env_map: return None
return { key: replace_token_placeholder(value, hf_token) for key, value in env_map.items() }
def create_job_spec(args: Dict[str, Any]) -> Dict[str, Any]: """Create a JobSpec from run command arguments""" # Validate required fields if not args.get('image'): raise ValueError('image parameter is required. Provide a Docker image (e.g., "python:3.12") or Space URL.') if not args.get('command'): raise ValueError('command parameter is required. Provide a command as string or array.')
image_source = parse_image_source(args['image']) command_parsed = parse_command(args['command']) timeout_seconds = parse_timeout(args['timeout']) if args.get('timeout') else None environment = transform_env_map(args.get('env'), args.get('hfToken')) or {} secrets = transform_env_map(args.get('secrets'), args.get('hfToken')) or {}
spec = { **{k: v for k, v in image_source.items() if v is not None}, 'command': command_parsed['command'], 'arguments': command_parsed['arguments'], 'flavor': args.get('flavor', 'cpu-basic'), 'environment': environment, 'secrets': secrets, }
if timeout_seconds is not None: spec['timeoutSeconds'] = timeout_seconds
return spec123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""UV command utilities
Ported from: hf-mcp-server/packages/mcp/src/jobs/commands/uv-utils.ts"""import base64from typing import List, Dict, Optional, Any
UV_DEFAULT_IMAGE = 'ghcr.io/astral-sh/uv:python3.12-bookworm'
def build_uv_command(script: str, args: Dict[str, Any]) -> List[str]: """Build UV run command""" parts = ['uv', 'run']
# Add dependencies with_deps = args.get('with_deps', []) if with_deps: for dep in with_deps: parts.extend(['--with', dep])
# Add python version python = args.get('python') if python: parts.extend(['-p', python])
parts.append(script)
# Add script arguments script_args = args.get('script_args', []) if script_args: parts.extend(script_args)
return parts
def wrap_inline_script(script: str, args: Dict[str, Any]) -> str: """Wrap inline script with base64 encoding for UV""" encoded = base64.b64encode(script.encode('utf-8')).decode('utf-8') base_command = build_uv_command('-', args) # Shell quote the command parts quoted_command = ' '.join(base_command) return f'echo "{encoded}" | base64 -d | {quoted_command}'
def resolve_uv_command(args: Dict[str, Any]) -> List[str]: """Resolve UV command based on script source""" script_source = args.get('script', '')
options = { 'with_deps': args.get('with_deps'), 'python': args.get('python'), 'script_args': args.get('script_args'), }
# URL script if script_source.startswith('http://') or script_source.startswith('https://'): return build_uv_command(script_source, options)
# Inline multi-line script if '\n' in script_source: return ['/bin/sh', '-lc', wrap_inline_script(script_source, options)]
# File path or single-line script return build_uv_command(script_source, options)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354553 unmodified lines5960616263646527 unmodified lines9394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713878 unmodified lines2172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963971 unmodified line39940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061110 unmodified lines622623624625626627628629630631632633634635636637638639640641642643644"""Hugging Face Jobs Tool - Manage compute jobs on Hugging FacePorted from: hf-mcp-server/packages/mcp/src/jobs/jobs-tool.ts"""import jsonfrom typing import Optional, Dict, Any, List, Literalfrom agent.tools.hf.types import ToolResultfrom agent.tools.hf.base import HfApiErrorfrom agent.tools.hf.jobs.api_client import JobsApiClientfrom agent.tools.hf.jobs.job_utils import create_job_specfrom agent.tools.hf.jobs.uv_utils import resolve_uv_command, UV_DEFAULT_IMAGEfrom agent.tools.hf.utilities import (format_jobs_table,format_scheduled_jobs_table,format_job_details,format_scheduled_job_details,)# Hardware flavorsCPU_FLAVORS = ['cpu-basic', 'cpu-upgrade', 'cpu-performance', 'cpu-xl']GPU_FLAVORS = ['sprx8', 'zero-a10g', 't4-small', 't4-medium', 'l4x1', 'l4x4','l40sx1', 'l40sx4', 'l40sx8', 'a10g-small', 'a10g-large','a10g-largex2', 'a10g-largex4', 'a100-large', 'h100', 'h100x8']SPECIALIZED_FLAVORS = ['inf2x6']ALL_FLAVORS = CPU_FLAVORS + GPU_FLAVORS + SPECIALIZED_FLAVORS# Operation namesOperationType = Literal["run", "uv", "ps", "logs", "inspect", "cancel","scheduled run", "scheduled uv", "scheduled ps","scheduled inspect", "scheduled delete", "scheduled suspend", "scheduled resume"]# ConstantsDEFAULT_LOG_WAIT_SECONDS = 10class HfJobsTool:"""Tool for managing Hugging Face compute jobs"""def __init__(self, hf_token: Optional[str] = None, namespace: Optional[str] = None):self.hf_token = hf_tokenself.client = JobsApiClient(hf_token, namespace)async def execute(self, params: Dict[str, Any]) -> ToolResult:"""Execute the specified operation"""operation = params.get('operation')args = params.get('args', {})# If no operation provided, return usage instructionsif not operation:3 unmodified linesoperation = operation.lower()# Check if help is requestedif args.get('help'):return self._show_operation_help(operation)try:27 unmodified lineselse:return {"formatted": f'Unknown operation: "{operation}"\n\n''Available operations:\n''- run, uv, ps, logs, inspect, cancel\n''- scheduled run, scheduled uv, scheduled ps, scheduled inspect, ''scheduled delete, scheduled suspend, scheduled resume\n\n''Call this tool with no operation for full usage instructions.',"totalResults": 0,"resultsShared": 0,"isError": True}except HfApiError as e:error_message = f"API Error: {e.message}"if e.response_body:try:parsed = json.loads(e.response_body)formatted_body = json.dumps(parsed, indent=2)error_message += f"\n\nServer response:\n{formatted_body}"except Exception:if len(e.response_body) < 500:error_message += f"\n\nServer response: {e.response_body}"return {"formatted": error_message,"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"""cpu_flavors_list = ', '.join(CPU_FLAVORS)gpu_flavors_list = ', '.join(GPU_FLAVORS)specialized_flavors_list = ', '.join(SPECIALIZED_FLAVORS)hardware_section = f"**CPU:** {cpu_flavors_list}\n"if GPU_FLAVORS:78 unmodified lines- Prefer array commands to avoid shell parsing surprises- To access private Hub assets, include `secrets: {{ "HF_TOKEN": "$HF_TOKEN" }}` to inject your auth token."""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 _run_job(self, args: Dict[str, Any]) -> ToolResult:"""Create and run a job"""# Create job spec from argsjob_spec = create_job_spec({'image': args.get('image', 'python:3.12'),'command': args.get('command'),'flavor': args.get('flavor', 'cpu-basic'),'env': args.get('env'),'secrets': args.get('secrets'),'timeout': args.get('timeout', '30m'),'hfToken': self.hf_token,})# Submit jobjob = await self.client.run_job(job_spec, args.get('namespace'))job_url = f"https://huggingface.co/jobs/{job['owner']['name']}/{job['id']}"# If detached, return immediatelyif args.get('detach', False):response = f"""Job started successfully!**Job ID:** {job['id']}**Status:** {job['status']['stage']}**View at:** {job_url}To check logs, call this tool with `{{"operation": "logs", "args": {{"job_id": "{job['id']}"}}}}`To inspect, call this tool with `{{"operation": "inspect", "args": {{"job_id": "{job['id']}"}}}}`"""return {"formatted": response,"totalResults": 1,"resultsShared": 1}# Not detached - return job info and link to logsresponse = f"""Job started: {job['id']}**Status:** {job['status']['stage']}**View logs at:** {job_url}Note: Logs are being collected. Check the job page for real-time logs."""return {"formatted": response,"totalResults": 1,"resultsShared": 1}async def _run_uv_job(self, args: Dict[str, Any]) -> ToolResult:"""Run job with UV package manager"""# UV jobs use a standard UV imageimage = UV_DEFAULT_IMAGE# Build UV commandcommand = resolve_uv_command(args)# Convert to run argsrun_args = {'image': image,'command': command,'flavor': args.get('flavor', 'cpu-basic'),'env': args.get('env'),'secrets': args.get('secrets'),'timeout': args.get('timeout', '30m'),'detach': args.get('detach', False),'namespace': args.get('namespace'),}return await self._run_job(run_args)async def _list_jobs(self, args: Dict[str, Any]) -> ToolResult:"""List user's jobs"""# Fetch all jobs from APIall_jobs = await self.client.list_jobs(args.get('namespace'))# Filter jobsjobs = all_jobs# Default: show only running jobs unless --all is specifiedif not args.get('all', False):jobs = [job for job in jobs if job['status']['stage'] == 'RUNNING']# Apply status filter if specifiedif args.get('status'):status_filter = args['status'].upper()jobs = [job for job in jobs if status_filter in job['status']['stage'].upper()]# Format as markdown tabletable = format_jobs_table(jobs)if len(jobs) == 0:if args.get('all', False):return {"formatted": "No jobs found.","totalResults": 0,"resultsShared": 0}return {"formatted": 'No running jobs found. Use `{"args": {"all": true}}` to show all jobs.',"totalResults": 0,"resultsShared": 0}response = f"**Jobs ({len(jobs)} of {len(all_jobs)} total):**\n\n{table}"return {"formatted": response,"totalResults": len(all_jobs),"resultsShared": len(jobs)}async def _get_logs(self, args: Dict[str, Any]) -> ToolResult:"""Get logs for a job"""job_id = args.get('job_id')if not job_id:return {"formatted": "job_id is required","totalResults": 0,"resultsShared": 0,"isError": True}# Get namespace for the logs URLnamespace = await self.client.get_namespace(args.get('namespace'))job_url = f"https://huggingface.co/jobs/{namespace}/{job_id}"# For now, direct users to the web interface for logs# Full SSE streaming implementation would be more complexresponse = f"""**Logs for job {job_id}**View real-time logs at: {job_url}Note: Full log streaming support is coming soon. Please use the web interface for now."""return {"formatted": response,"totalResults": 1,"resultsShared": 1}async def _inspect_job(self, args: Dict[str, Any]) -> ToolResult:"""Get detailed information about one or more jobs"""job_id = args.get('job_id')if not job_id:return {"formatted": "job_id is required","totalResults": 0,"resultsShared": 0,"isError": True}job_ids = job_id if isinstance(job_id, list) else [job_id]# Fetch all jobsjobs = []for jid in job_ids:try:job = await self.client.get_job(jid, args.get('namespace'))jobs.append(job)except Exception as e:raise Exception(f"Failed to fetch job {jid}: {str(e)}")formatted_details = format_job_details(jobs)response = f"**Job Details** ({len(jobs)} job{'s' if len(jobs) > 1 else ''}):\n\n{formatted_details}"1 unmodified linereturn {"formatted": response,"totalResults": len(jobs),"resultsShared": len(jobs)}async def _cancel_job(self, args: Dict[str, Any]) -> ToolResult:"""Cancel a running job"""job_id = args.get('job_id')if not job_id:return {"formatted": "job_id is required","totalResults": 0,"resultsShared": 0,"isError": True}await self.client.cancel_job(job_id, args.get('namespace'))response = f"""✓ Job {job_id} has been cancelled.To verify, call this tool with `{{"operation": "inspect", "args": {{"job_id": "{job_id}"}}}}`"""return {"formatted": response,"totalResults": 1,"resultsShared": 1}async def _scheduled_run(self, args: Dict[str, Any]) -> ToolResult:"""Create a scheduled job"""# Create job specjob_spec = create_job_spec({'image': args.get('image', 'python:3.12'),'command': args.get('command'),'flavor': args.get('flavor', 'cpu-basic'),'env': args.get('env'),'secrets': args.get('secrets'),'timeout': args.get('timeout', '30m'),'hfToken': self.hf_token,})# Create scheduled job specscheduled_spec = {'schedule': args.get('schedule'),'suspend': args.get('suspend', False),'jobSpec': job_spec,}# Submit scheduled jobscheduled_job = await self.client.create_scheduled_job(scheduled_spec, args.get('namespace'))response = f"""✓ Scheduled job created successfully!**Scheduled Job ID:** {scheduled_job['id']}**Schedule:** {scheduled_job['schedule']}**Suspended:** {'Yes' if scheduled_job.get('suspend') else 'No'}**Next Run:** {scheduled_job.get('nextRun', 'N/A')}To inspect, call this tool with `{{"operation": "scheduled inspect", "args": {{"scheduled_job_id": "{scheduled_job['id']}"}}}}`To list all, call this tool with `{{"operation": "scheduled ps"}}`"""return {"formatted": response,"totalResults": 1,"resultsShared": 1}async def _scheduled_uv(self, args: Dict[str, Any]) -> ToolResult:"""Create a scheduled UV job"""# For UV, use standard UV imageimage = UV_DEFAULT_IMAGE# Build UV commandcommand = resolve_uv_command(args)# Convert to scheduled run argsscheduled_run_args = {'schedule': args.get('schedule'),'suspend': args.get('suspend', False),'image': image,'command': command,'flavor': args.get('flavor', 'cpu-basic'),'env': args.get('env'),'secrets': args.get('secrets'),'timeout': args.get('timeout', '30m'),'namespace': args.get('namespace'),}return await self._scheduled_run(scheduled_run_args)async def _list_scheduled_jobs(self, args: Dict[str, Any]) -> ToolResult:"""List scheduled jobs"""# Fetch all scheduled jobsall_jobs = await self.client.list_scheduled_jobs(args.get('namespace'))# Filter jobsjobs = all_jobs# Default: hide suspended jobs unless --all is specifiedif not args.get('all', False):jobs = [job for job in jobs if not job.get('suspend', False)]# Format as markdown tabletable = format_scheduled_jobs_table(jobs)if len(jobs) == 0:if args.get('all', False):return {"formatted": "No scheduled jobs found.","totalResults": 0,"resultsShared": 0}return {"formatted": 'No active scheduled jobs found. Use `{"args": {"all": true}}` to show suspended jobs.',"totalResults": 0,"resultsShared": 0}response = f"**Scheduled Jobs ({len(jobs)} of {len(all_jobs)} total):**\n\n{table}"return {"formatted": response,"totalResults": len(all_jobs),"resultsShared": len(jobs)}async def _inspect_scheduled_job(self, args: Dict[str, Any]) -> ToolResult:"""Get details of a scheduled job"""scheduled_job_id = args.get('scheduled_job_id')if not scheduled_job_id:return {"formatted": "scheduled_job_id is required","totalResults": 0,"resultsShared": 0,"isError": True}job = await self.client.get_scheduled_job(scheduled_job_id, args.get('namespace'))formatted_details = format_scheduled_job_details(job)return {"formatted": f"**Scheduled Job Details:**\n\n{formatted_details}","totalResults": 1,"resultsShared": 1}async def _delete_scheduled_job(self, args: Dict[str, Any]) -> ToolResult:"""Delete a scheduled job"""scheduled_job_id = args.get('scheduled_job_id')if not scheduled_job_id:return {"formatted": "scheduled_job_id is required","totalResults": 0,"resultsShared": 0,"isError": True}await self.client.delete_scheduled_job(scheduled_job_id, args.get('namespace'))return {"formatted": f"✓ Scheduled job {scheduled_job_id} has been deleted.","totalResults": 1,"resultsShared": 1}async def _suspend_scheduled_job(self, args: Dict[str, Any]) -> ToolResult:"""Suspend a scheduled job"""scheduled_job_id = args.get('scheduled_job_id')if not scheduled_job_id:return {"formatted": "scheduled_job_id is required","totalResults": 0,"resultsShared": 0,"isError": True}await self.client.suspend_scheduled_job(scheduled_job_id, args.get('namespace'))response = f"""✓ Scheduled job {scheduled_job_id} has been suspended.To resume, call this tool with `{{"operation": "scheduled resume", "args": {{"scheduled_job_id": "{scheduled_job_id}"}}}}`"""return {"formatted": response,"totalResults": 1,"resultsShared": 1}async def _resume_scheduled_job(self, args: Dict[str, Any]) -> ToolResult:"""Resume a suspended scheduled job"""scheduled_job_id = args.get('scheduled_job_id')if not scheduled_job_id:return {"formatted": "scheduled_job_id is required","totalResults": 0,"resultsShared": 0,"isError": True}await self.client.resume_scheduled_job(scheduled_job_id, args.get('namespace'))response = f"""✓ Scheduled job {scheduled_job_id} has been resumed.To inspect, call this tool with `{{"operation": "scheduled inspect", "args": {{"scheduled_job_id": "{scheduled_job_id}"}}}}`"""return {"formatted": response,"totalResults": 1,"resultsShared": 1}# Tool specification for agent registration10 unmodified lines"operation": {"type": "string","enum": ["run", "uv", "ps", "logs", "inspect", "cancel","scheduled run", "scheduled uv", "scheduled ps","scheduled inspect", "scheduled delete", "scheduled suspend", "scheduled resume"],"description": ("Operation to execute. Valid values: run, uv, ps, logs, inspect, cancel, ""scheduled run, scheduled uv, scheduled ps, scheduled inspect, scheduled delete, ""scheduled suspend, scheduled resume")},"args": {"type": "object","description": "Operation-specific arguments as a JSON object","additionalProperties": True}}}}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961973 unmodified lines20120220320420520620727 unmodified lines23523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927078 unmodified lines3493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415421 unmodified line54454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478510 unmodified lines796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828"""Hugging Face Jobs Tool - Using huggingface-hub libraryRefactored to use official huggingface-hub library instead of custom HTTP client"""import asyncioimport base64from typing import Any, Dict, Literal, Optionalfrom huggingface_hub import HfApifrom huggingface_hub.utils import HfHubHTTPErrorfrom agent.tools.types import ToolResultfrom agent.tools.utilities import (format_job_details,format_jobs_table,format_scheduled_job_details,format_scheduled_jobs_table,)# Hardware flavorsCPU_FLAVORS = ["cpu-basic", "cpu-upgrade", "cpu-performance", "cpu-xl"]GPU_FLAVORS = ["sprx8","zero-a10g","t4-small","t4-medium","l4x1","l4x4","l40sx1","l40sx4","l40sx8","a10g-small","a10g-large","a10g-largex2","a10g-largex4","a100-large","h100","h100x8",]SPECIALIZED_FLAVORS = ["inf2x6"]ALL_FLAVORS = CPU_FLAVORS + GPU_FLAVORS + SPECIALIZED_FLAVORS# Operation namesOperationType = Literal["run","uv","ps","logs","inspect","cancel","scheduled run","scheduled uv","scheduled ps","scheduled inspect","scheduled delete","scheduled suspend","scheduled resume",]# ConstantsDEFAULT_LOG_WAIT_SECONDS = 10UV_DEFAULT_IMAGE = "ghcr.io/astral-sh/uv:python3.12-bookworm"def _build_uv_command(script: str,with_deps: list[str] | None = None,python: str | None = None,script_args: list[str] | None = None,) -> list[str]:"""Build UV run command"""parts = ["uv", "run"]if with_deps:for dep in with_deps:parts.extend(["--with", dep])if python:parts.extend(["-p", python])parts.append(script)if script_args:parts.extend(script_args)return partsdef _wrap_inline_script(script: str,with_deps: list[str] | None = None,python: str | None = None,script_args: list[str] | None = None,) -> str:"""Wrap inline script with base64 encoding to avoid file creation"""encoded = base64.b64encode(script.encode("utf-8")).decode("utf-8")# Build the uv command with stdin (-)uv_command = _build_uv_command("-", with_deps, python, script_args)# Join command parts with proper spacinguv_command_str = " ".join(uv_command)return f'echo "{encoded}" | base64 -d | {uv_command_str}'def _resolve_uv_command(script: str,with_deps: list[str] | None = None,python: str | None = None,script_args: list[str] | None = None,) -> list[str]:"""Resolve UV command based on script source (URL, inline, or file path)"""# If URL, use directlyif script.startswith("http://") or script.startswith("https://"):return _build_uv_command(script, with_deps, python, script_args)# If contains newline, treat as inline scriptif "\n" in script:wrapped = _wrap_inline_script(script, with_deps, python, script_args)return ["/bin/sh", "-lc", wrapped]# Otherwise, treat as file pathreturn _build_uv_command(script, with_deps, python, script_args)async def _async_call(func, *args, **kwargs):"""Wrap synchronous HfApi calls for async context"""return await asyncio.to_thread(func, *args, **kwargs)def _job_info_to_dict(job_info) -> Dict[str, Any]:"""Convert JobInfo object to dictionary for formatting functions"""return {"id": job_info.id,"status": {"stage": job_info.status.stage, "message": job_info.status.message},"command": job_info.command,"createdAt": job_info.created_at.isoformat(),"dockerImage": job_info.docker_image,"spaceId": job_info.space_id,"flavor": job_info.flavor,"owner": {"name": job_info.owner.name},}def _scheduled_job_info_to_dict(scheduled_job_info) -> Dict[str, Any]:"""Convert ScheduledJobInfo object to dictionary for formatting functions"""job_spec = scheduled_job_info.job_spec# Extract last run and next run from statuslast_run = Nonenext_run = Noneif scheduled_job_info.status:if scheduled_job_info.status.last_job:last_run = scheduled_job_info.status.last_job.created_atif last_run:last_run = (last_run.isoformat()if hasattr(last_run, "isoformat")else str(last_run))if scheduled_job_info.status.next_job_run_at:next_run = scheduled_job_info.status.next_job_run_atnext_run = (next_run.isoformat()if hasattr(next_run, "isoformat")else str(next_run))return {"id": scheduled_job_info.id,"schedule": scheduled_job_info.schedule,"suspend": scheduled_job_info.suspend,"lastRun": last_run,"nextRun": next_run,"jobSpec": {"dockerImage": job_spec.docker_image,"spaceId": job_spec.space_id,"command": job_spec.command or [],"flavor": job_spec.flavor or "cpu-basic",},}class HfJobsTool:"""Tool for managing Hugging Face compute jobs using huggingface-hub library"""def __init__(self, hf_token: Optional[str] = None, namespace: Optional[str] = None):self.api = HfApi(token=hf_token)self.namespace = namespaceasync def execute(self, params: Dict[str, Any]) -> ToolResult:"""Execute the specified operation"""operation = params.get("operation")args = params.get("args", {})# If no operation provided, return usage instructionsif not operation:3 unmodified linesoperation = operation.lower()# Check if help is requestedif args.get("help"):return self._show_operation_help(operation)try:27 unmodified lineselse:return {"formatted": f'Unknown operation: "{operation}"\n\n'"Available operations:\n""- run, uv, ps, logs, inspect, cancel\n""- scheduled run, scheduled uv, scheduled ps, scheduled inspect, ""scheduled delete, scheduled suspend, scheduled resume\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"""cpu_flavors_list = ", ".join(CPU_FLAVORS)gpu_flavors_list = ", ".join(GPU_FLAVORS)specialized_flavors_list = ", ".join(SPECIALIZED_FLAVORS)hardware_section = f"**CPU:** {cpu_flavors_list}\n"if GPU_FLAVORS:78 unmodified lines- Prefer array commands to avoid shell parsing surprises- To access private Hub assets, include `secrets: {{ "HF_TOKEN": "$HF_TOKEN" }}` to inject your auth token."""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 _run_job(self, args: Dict[str, Any]) -> ToolResult:"""Run a job using HfApi.run_job()"""try:job = await _async_call(self.api.run_job,image=args.get("image", "python:3.12"),command=args.get("command"),env=args.get("env"),secrets=args.get("secrets"),flavor=args.get("flavor", "cpu-basic"),timeout=args.get("timeout", "30m"),namespace=args.get("namespace") or self.namespace,)# If detached, return immediatelyif args.get("detach", False):response = f"""Job started successfully!**Job ID:** {job.id}**Status:** {job.status.stage}**View at:** {job.url}To check logs, call this tool with `{{"operation": "logs", "args": {{"job_id": "{job.id}"}}}}`To inspect, call this tool with `{{"operation": "inspect", "args": {{"job_id": "{job.id}"}}}}`"""return {"formatted": response, "totalResults": 1, "resultsShared": 1}# Not detached - return job inforesponse = f"""Job started: {job.id}**Status:** {job.status.stage}**View logs at:** {job.url}Note: Logs are being collected. Check the job page for real-time logs."""return {"formatted": response, "totalResults": 1, "resultsShared": 1}except Exception as e:raise Exception(f"Failed to run job: {str(e)}")async def _run_uv_job(self, args: Dict[str, Any]) -> ToolResult:"""Run UV job with inline script support (no local files needed)"""try:script = args.get("script")if not script:raise ValueError("script is required")# Resolve the command based on script type (URL, inline, or file)command = _resolve_uv_command(script=script,with_deps=args.get("with_deps") or args.get("dependencies"),python=args.get("python"),script_args=args.get("script_args"),)# Use run_job with UV image instead of run_uv_jobjob = await _async_call(self.api.run_job,image=UV_DEFAULT_IMAGE,command=command,env=args.get("env"),secrets=args.get("secrets"),flavor=args.get("flavor", "cpu-basic"),timeout=args.get("timeout", "30m"),namespace=args.get("namespace") or self.namespace,)response = f"""UV Job started: {job.id}**Status:** {job.status.stage}**View at:** {job.url}To check logs, call this tool with `{{"operation": "logs", "args": {{"job_id": "{job.id}"}}}}`"""return {"formatted": response, "totalResults": 1, "resultsShared": 1}except Exception as e:raise Exception(f"Failed to run UV job: {str(e)}")async def _list_jobs(self, args: Dict[str, Any]) -> ToolResult:"""List jobs using HfApi.list_jobs()"""jobs_list = await _async_call(self.api.list_jobs, namespace=args.get("namespace") or self.namespace)# Filter jobsif not args.get("all", False):jobs_list = [j for j in jobs_list if j.status.stage == "RUNNING"]if args.get("status"):status_filter = args["status"].upper()jobs_list = [j for j in jobs_list if status_filter in j.status.stage]# Convert JobInfo objects to dicts for formattingjobs_dicts = [_job_info_to_dict(j) for j in jobs_list]table = format_jobs_table(jobs_dicts)if len(jobs_list) == 0:if args.get("all", False):return {"formatted": "No jobs found.","totalResults": 0,"resultsShared": 0,}return {"formatted": 'No running jobs found. Use `{"args": {"all": true}}` to show all jobs.',"totalResults": 0,"resultsShared": 0,}response = f"**Jobs ({len(jobs_list)} total):**\n\n{table}"return {"formatted": response,"totalResults": len(jobs_list),"resultsShared": len(jobs_list),}async def _get_logs(self, args: Dict[str, Any]) -> ToolResult:"""Fetch logs using HfApi.fetch_job_logs()"""job_id = args.get("job_id")if not job_id:return {"formatted": "job_id is required","isError": True,"totalResults": 0,"resultsShared": 0,}try:# Fetch logs (returns generator, convert to list)logs_gen = self.api.fetch_job_logs(job_id=job_id, namespace=args.get("namespace") or self.namespace)logs = await _async_call(list, logs_gen)if not logs:return {"formatted": f"No logs available for job {job_id}","totalResults": 0,"resultsShared": 0,}log_text = "\n".join(logs)return {"formatted": f"**Logs for {job_id}:**\n\n```\n{log_text}\n```","totalResults": 1,"resultsShared": 1,}except Exception as e:return {"formatted": f"Failed to fetch logs: {str(e)}","isError": True,"totalResults": 0,"resultsShared": 0,}async def _inspect_job(self, args: Dict[str, Any]) -> ToolResult:"""Inspect job using HfApi.inspect_job()"""job_id = args.get("job_id")if not job_id:return {"formatted": "job_id is required","totalResults": 0,"resultsShared": 0,"isError": True,}job_ids = job_id if isinstance(job_id, list) else [job_id]jobs = []for jid in job_ids:try:job = await _async_call(self.api.inspect_job,job_id=jid,namespace=args.get("namespace") or self.namespace,)jobs.append(_job_info_to_dict(job))except Exception as e:raise Exception(f"Failed to inspect job {jid}: {str(e)}")formatted_details = format_job_details(jobs)response = f"**Job Details** ({len(jobs)} job{'s' if len(jobs) > 1 else ''}):\n\n{formatted_details}"1 unmodified linereturn {"formatted": response,"totalResults": len(jobs),"resultsShared": len(jobs),}async def _cancel_job(self, args: Dict[str, Any]) -> ToolResult:"""Cancel job using HfApi.cancel_job()"""job_id = args.get("job_id")if not job_id:return {"formatted": "job_id is required","totalResults": 0,"resultsShared": 0,"isError": True,}await _async_call(self.api.cancel_job,job_id=job_id,namespace=args.get("namespace") or self.namespace,)response = f"""✓ Job {job_id} has been cancelled.To verify, call this tool with `{{"operation": "inspect", "args": {{"job_id": "{job_id}"}}}}`"""return {"formatted": response, "totalResults": 1, "resultsShared": 1}async def _scheduled_run(self, args: Dict[str, Any]) -> ToolResult:"""Create scheduled job using HfApi.create_scheduled_job()"""try:scheduled_job = await _async_call(self.api.create_scheduled_job,image=args.get("image", "python:3.12"),command=args.get("command"),schedule=args.get("schedule"),env=args.get("env"),secrets=args.get("secrets"),flavor=args.get("flavor", "cpu-basic"),timeout=args.get("timeout", "30m"),namespace=args.get("namespace") or self.namespace,)scheduled_dict = _scheduled_job_info_to_dict(scheduled_job)response = f"""✓ Scheduled job created successfully!**Scheduled Job ID:** {scheduled_dict["id"]}**Schedule:** {scheduled_dict["schedule"]}**Suspended:** {"Yes" if scheduled_dict.get("suspend") else "No"}**Next Run:** {scheduled_dict.get("nextRun", "N/A")}To inspect, call this tool with `{{"operation": "scheduled inspect", "args": {{"scheduled_job_id": "{scheduled_dict["id"]}"}}}}`To list all, call this tool with `{{"operation": "scheduled ps"}}`"""return {"formatted": response, "totalResults": 1, "resultsShared": 1}except Exception as e:raise Exception(f"Failed to create scheduled job: {str(e)}")async def _scheduled_uv(self, args: Dict[str, Any]) -> ToolResult:"""Create scheduled UV job with inline script support"""try:script = args.get("script")if not script:raise ValueError("script is required")schedule = args.get("schedule")if not schedule:raise ValueError("schedule is required")# Resolve the command based on script typecommand = _resolve_uv_command(script=script,with_deps=args.get("with_deps") or args.get("dependencies"),python=args.get("python"),script_args=args.get("script_args"),)# Use create_scheduled_job with UV imagescheduled_job = await _async_call(self.api.create_scheduled_job,image=UV_DEFAULT_IMAGE,command=command,schedule=schedule,env=args.get("env"),secrets=args.get("secrets"),flavor=args.get("flavor", "cpu-basic"),timeout=args.get("timeout", "30m"),namespace=args.get("namespace") or self.namespace,)scheduled_dict = _scheduled_job_info_to_dict(scheduled_job)response = f"""✓ Scheduled UV job created successfully!**Scheduled Job ID:** {scheduled_dict["id"]}**Schedule:** {scheduled_dict["schedule"]}**Suspended:** {"Yes" if scheduled_dict.get("suspend") else "No"}**Next Run:** {scheduled_dict.get("nextRun", "N/A")}To inspect, call this tool with `{{"operation": "scheduled inspect", "args": {{"scheduled_job_id": "{scheduled_dict["id"]}"}}}}`"""return {"formatted": response, "totalResults": 1, "resultsShared": 1}except Exception as e:raise Exception(f"Failed to create scheduled UV job: {str(e)}")async def _list_scheduled_jobs(self, args: Dict[str, Any]) -> ToolResult:"""List scheduled jobs using HfApi.list_scheduled_jobs()"""scheduled_jobs_list = await _async_call(self.api.list_scheduled_jobs,namespace=args.get("namespace") or self.namespace,)# Filter jobs - default: hide suspended jobs unless --all is specifiedif not args.get("all", False):scheduled_jobs_list = [j for j in scheduled_jobs_list if not j.suspend]# Convert to dicts for formattingscheduled_dicts = [_scheduled_job_info_to_dict(j) for j in scheduled_jobs_list]table = format_scheduled_jobs_table(scheduled_dicts)if len(scheduled_jobs_list) == 0:if args.get("all", False):return {"formatted": "No scheduled jobs found.","totalResults": 0,"resultsShared": 0,}return {"formatted": 'No active scheduled jobs found. Use `{"args": {"all": true}}` to show suspended jobs.',"totalResults": 0,"resultsShared": 0,}response = f"**Scheduled Jobs ({len(scheduled_jobs_list)} total):**\n\n{table}"return {"formatted": response,"totalResults": len(scheduled_jobs_list),"resultsShared": len(scheduled_jobs_list),}async def _inspect_scheduled_job(self, args: Dict[str, Any]) -> ToolResult:"""Inspect scheduled job using HfApi.inspect_scheduled_job()"""scheduled_job_id = args.get("scheduled_job_id")if not scheduled_job_id:return {"formatted": "scheduled_job_id is required","totalResults": 0,"resultsShared": 0,"isError": True,}scheduled_job = await _async_call(self.api.inspect_scheduled_job,scheduled_job_id=scheduled_job_id,namespace=args.get("namespace") or self.namespace,)scheduled_dict = _scheduled_job_info_to_dict(scheduled_job)formatted_details = format_scheduled_job_details(scheduled_dict)return {"formatted": f"**Scheduled Job Details:**\n\n{formatted_details}","totalResults": 1,"resultsShared": 1,}async def _delete_scheduled_job(self, args: Dict[str, Any]) -> ToolResult:"""Delete scheduled job using HfApi.delete_scheduled_job()"""scheduled_job_id = args.get("scheduled_job_id")if not scheduled_job_id:return {"formatted": "scheduled_job_id is required","totalResults": 0,"resultsShared": 0,"isError": True,}await _async_call(self.api.delete_scheduled_job,scheduled_job_id=scheduled_job_id,namespace=args.get("namespace") or self.namespace,)return {"formatted": f"✓ Scheduled job {scheduled_job_id} has been deleted.","totalResults": 1,"resultsShared": 1,}async def _suspend_scheduled_job(self, args: Dict[str, Any]) -> ToolResult:"""Suspend scheduled job using HfApi.suspend_scheduled_job()"""scheduled_job_id = args.get("scheduled_job_id")if not scheduled_job_id:return {"formatted": "scheduled_job_id is required","totalResults": 0,"resultsShared": 0,"isError": True,}await _async_call(self.api.suspend_scheduled_job,scheduled_job_id=scheduled_job_id,namespace=args.get("namespace") or self.namespace,)response = f"""✓ Scheduled job {scheduled_job_id} has been suspended.To resume, call this tool with `{{"operation": "scheduled resume", "args": {{"scheduled_job_id": "{scheduled_job_id}"}}}}`"""return {"formatted": response, "totalResults": 1, "resultsShared": 1}async def _resume_scheduled_job(self, args: Dict[str, Any]) -> ToolResult:"""Resume scheduled job using HfApi.resume_scheduled_job()"""scheduled_job_id = args.get("scheduled_job_id")if not scheduled_job_id:return {"formatted": "scheduled_job_id is required","totalResults": 0,"resultsShared": 0,"isError": True,}await _async_call(self.api.resume_scheduled_job,scheduled_job_id=scheduled_job_id,namespace=args.get("namespace") or self.namespace,)response = f"""✓ Scheduled job {scheduled_job_id} has been resumed.To inspect, call this tool with `{{"operation": "scheduled inspect", "args": {{"scheduled_job_id": "{scheduled_job_id}"}}}}`"""return {"formatted": response, "totalResults": 1, "resultsShared": 1}# Tool specification for agent registration10 unmodified lines"operation": {"type": "string","enum": ["run","uv","ps","logs","inspect","cancel","scheduled run","scheduled uv","scheduled ps","scheduled inspect","scheduled delete","scheduled suspend","scheduled resume",],"description": ("Operation to execute. Valid values: [run, uv, ps, logs, inspect, cancel, ""scheduled run, scheduled uv, scheduled ps, scheduled inspect, scheduled delete, ""scheduled suspend, scheduled resume]"),},"args": {"type": "object","description": "Operation-specific arguments as a JSON object","additionalProperties": True,},},},}
2 unmodified lines3456789101112132 unmodified linesPorted from: hf-mcp-server/packages/mcp/src/types/"""from typing import TypedDict, Optionalclass ToolResult(TypedDict, total=False):"""Result returned by HF tool operations"""formatted: strtotalResults: intresultsShared: int2 unmodified lines34567891011121314152 unmodified linesPorted from: hf-mcp-server/packages/mcp/src/types/"""from typing import TypedDictclass ToolResult(TypedDict, total=False):"""Result returned by HF tool operations"""formatted: strtotalResults: intresultsShared: int
2 unmodified lines345678910111213141516171 unmodified line19202122232425267 unmodified lines343536373839404142433 unmodified lines474849505152535455565758596061623 unmodified lines6667686970717273747576777879802 unmodified lines83848586878889909192939495969798991003 unmodified lines1041051061071081091101111121131141151161171181191201211221231241252 unmodified lines1281291301311321332 unmodified linesPorted from: hf-mcp-server/packages/mcp/src/jobs/formatters.ts"""from typing import Any, Dict, List, Optionalfrom datetime import datetimedef truncate(text: str, max_length: int) -> str:"""Truncate a string to a maximum length with ellipsis"""if len(text) <= max_length:return textreturn text[:max_length - 3] + "..."def format_date(date_str: Optional[str]) -> str:1 unmodified lineif not date_str:return "N/A"try:date = datetime.fromisoformat(date_str.replace('Z', '+00:00'))return date.strftime('%Y-%m-%d %H:%M:%S')except Exception:return date_str7 unmodified linesdef get_image_or_space(job: Dict[str, Any]) -> str:"""Get image/space identifier from job"""if job.get('spaceId'):return job['spaceId']if job.get('dockerImage'):return job['dockerImage']return "N/A"3 unmodified linesreturn "No jobs found."# Calculate dynamic ID column widthlongest_id_length = max(len(job['id']) for job in jobs)id_column_width = max(longest_id_length, len('JOB ID'))# Define column widthscol_widths = {'id': id_column_width,'image': 20,'command': 30,'created': 19,'status': 12,}# Build header3 unmodified lines# Build rowsrows = []for job in jobs:job_id = job['id']image = truncate(get_image_or_space(job), col_widths['image'])command = truncate(format_command(job.get('command')), col_widths['command'])created = truncate(format_date(job.get('createdAt')), col_widths['created'])status = truncate(job['status']['stage'], col_widths['status'])rows.append(f"| {job_id.ljust(col_widths['id'])} | {image.ljust(col_widths['image'])} | {command.ljust(col_widths['command'])} | {created.ljust(col_widths['created'])} | {status.ljust(col_widths['status'])} |")return '\n'.join([header, separator] + rows)def format_scheduled_jobs_table(jobs: List[Dict[str, Any]]) -> str:2 unmodified linesreturn "No scheduled jobs found."# Calculate dynamic ID column widthlongest_id_length = max(len(job['id']) for job in jobs)id_column_width = max(longest_id_length, len('ID'))# Define column widthscol_widths = {'id': id_column_width,'schedule': 12,'image': 18,'command': 25,'lastRun': 19,'nextRun': 19,'suspend': 9,}# Build header3 unmodified lines# Build rowsrows = []for job in jobs:job_id = job['id']schedule = truncate(job['schedule'], col_widths['schedule'])image = truncate(get_image_or_space(job['jobSpec']), col_widths['image'])command = truncate(format_command(job['jobSpec'].get('command')), col_widths['command'])last_run = truncate(format_date(job.get('lastRun')), col_widths['lastRun'])next_run = truncate(format_date(job.get('nextRun')), col_widths['nextRun'])suspend = 'Yes' if job.get('suspend') else 'No'rows.append(f"| {job_id.ljust(col_widths['id'])} | {schedule.ljust(col_widths['schedule'])} | {image.ljust(col_widths['image'])} | {command.ljust(col_widths['command'])} | {last_run.ljust(col_widths['lastRun'])} | {next_run.ljust(col_widths['nextRun'])} | {suspend.ljust(col_widths['suspend'])} |")return '\n'.join([header, separator] + rows)def format_job_details(jobs: Any) -> str:"""Format job details as JSON in a markdown code block"""import jsonjob_array = jobs if isinstance(jobs, list) else [jobs]json_str = json.dumps(job_array, indent=2)return f"```json\n{json_str}\n```"2 unmodified linesdef format_scheduled_job_details(jobs: Any) -> str:"""Format scheduled job details as JSON in a markdown code block"""import jsonjob_array = jobs if isinstance(jobs, list) else [jobs]json_str = json.dumps(job_array, indent=2)return f"```json\n{json_str}\n```"2 unmodified lines34567891011121314151617181 unmodified line20212223242526277 unmodified lines353637383940414243443 unmodified lines484950515253545556575859606162633 unmodified lines67686970717273747576777879808182832 unmodified lines86878889909192939495969798991001011021033 unmodified lines1071081091101111121131141151161171181191201211221231241251261271281291301311321332 unmodified lines1361371381391401411422 unmodified linesPorted from: hf-mcp-server/packages/mcp/src/jobs/formatters.ts"""from datetime import datetimefrom typing import Any, Dict, List, Optionaldef truncate(text: str, max_length: int) -> str:"""Truncate a string to a maximum length with ellipsis"""if len(text) <= max_length:return textreturn text[: max_length - 3] + "..."def format_date(date_str: Optional[str]) -> str:1 unmodified lineif not date_str:return "N/A"try:date = datetime.fromisoformat(date_str.replace("Z", "+00:00"))return date.strftime("%Y-%m-%d %H:%M:%S")except Exception:return date_str7 unmodified linesdef get_image_or_space(job: Dict[str, Any]) -> str:"""Get image/space identifier from job"""if job.get("spaceId"):return job["spaceId"]if job.get("dockerImage"):return job["dockerImage"]return "N/A"3 unmodified linesreturn "No jobs found."# Calculate dynamic ID column widthlongest_id_length = max(len(job["id"]) for job in jobs)id_column_width = max(longest_id_length, len("JOB ID"))# Define column widthscol_widths = {"id": id_column_width,"image": 20,"command": 30,"created": 19,"status": 12,}# Build header3 unmodified lines# Build rowsrows = []for job in jobs:job_id = job["id"]image = truncate(get_image_or_space(job), col_widths["image"])command = truncate(format_command(job.get("command")), col_widths["command"])created = truncate(format_date(job.get("createdAt")), col_widths["created"])status = truncate(job["status"]["stage"], col_widths["status"])rows.append(f"| {job_id.ljust(col_widths['id'])} | {image.ljust(col_widths['image'])} | {command.ljust(col_widths['command'])} | {created.ljust(col_widths['created'])} | {status.ljust(col_widths['status'])} |")return "\n".join([header, separator] + rows)def format_scheduled_jobs_table(jobs: List[Dict[str, Any]]) -> str:2 unmodified linesreturn "No scheduled jobs found."# Calculate dynamic ID column widthlongest_id_length = max(len(job["id"]) for job in jobs)id_column_width = max(longest_id_length, len("ID"))# Define column widthscol_widths = {"id": id_column_width,"schedule": 12,"image": 18,"command": 25,"lastRun": 19,"nextRun": 19,"suspend": 9,}# Build header3 unmodified lines# Build rowsrows = []for job in jobs:job_id = job["id"]schedule = truncate(job["schedule"], col_widths["schedule"])image = truncate(get_image_or_space(job["jobSpec"]), col_widths["image"])command = truncate(format_command(job["jobSpec"].get("command")), col_widths["command"])last_run = truncate(format_date(job.get("lastRun")), col_widths["lastRun"])next_run = truncate(format_date(job.get("nextRun")), col_widths["nextRun"])suspend = "Yes" if job.get("suspend") else "No"rows.append(f"| {job_id.ljust(col_widths['id'])} | {schedule.ljust(col_widths['schedule'])} | {image.ljust(col_widths['image'])} | {command.ljust(col_widths['command'])} | {last_run.ljust(col_widths['lastRun'])} | {next_run.ljust(col_widths['nextRun'])} | {suspend.ljust(col_widths['suspend'])} |")return "\n".join([header, separator] + rows)def format_job_details(jobs: Any) -> str:"""Format job details as JSON in a markdown code block"""import jsonjob_array = jobs if isinstance(jobs, list) else [jobs]json_str = json.dumps(job_array, indent=2)return f"```json\n{json_str}\n```"2 unmodified linesdef format_scheduled_job_details(jobs: Any) -> str:"""Format scheduled job details as JSON in a markdown code block"""import jsonjob_array = jobs if isinstance(jobs, list) else [jobs]json_str = json.dumps(job_array, indent=2)return f"```json\n{json_str}\n```"
18 unmodified lines1920212218 unmodified lines"lmnr[all]>=0.7.23","transformers>=2.3.0","torch>=2.9.1",]18 unmodified lines192021222318 unmodified lines"lmnr[all]>=0.7.23","transformers>=2.3.0","torch>=2.9.1","pytest>=9.0.2",]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452#!/usr/bin/env python3"""Integration tests for refactored HF Jobs ToolTests with real HF API using HF_TOKEN from environment"""import osimport sysimport asyncioimport time
# Add parent directory to pathsys.path.insert(0, '.')
from agent.tools.jobs_tool import HfJobsTool
# ANSI color codes for better outputGREEN = '\033[92m'YELLOW = '\033[93m'RED = '\033[91m'BLUE = '\033[94m'RESET = '\033[0m'
def print_test(msg): """Print test message in blue""" print(f"{BLUE}[TEST]{RESET} {msg}")
def print_success(msg): """Print success message in green""" print(f"{GREEN}✓{RESET} {msg}")
def print_warning(msg): """Print warning message in yellow""" print(f"{YELLOW}⚠{RESET} {msg}")
def print_error(msg): """Print error message in red""" print(f"{RED}✗{RESET} {msg}")
async def test_basic_job_run(tool): """Test running a basic job""" print_test("Running a simple Python job...")
result = await tool.execute({ "operation": "run", "args": { "image": "python:3.12", "command": ["python", "-c", "print('Hello from HF Jobs!')"], "flavor": "cpu-basic", "timeout": "5m", "detach": True # Don't wait for completion } })
if result.get("isError"): print_error(f"Failed to run job: {result['formatted']}") return None
# Extract job ID from response import re job_id_match = re.search(r'\*\*Job ID:\*\* (\S+)', result['formatted']) if job_id_match: job_id = job_id_match.group(1) print_success(f"Job started with ID: {job_id}") return job_id
print_error("Could not extract job ID from response") return None
async def test_list_jobs(tool): """Test listing jobs""" print_test("Listing running jobs...")
result = await tool.execute({ "operation": "ps", "args": {} })
if result.get("isError"): print_error(f"Failed to list jobs: {result['formatted']}") return False
print_success(f"Listed jobs: {result['totalResults']} running") if result['totalResults'] > 0: print(f" {result['formatted'][:200]}...") return True
async def test_inspect_job(tool, job_id): """Test inspecting a specific job""" print_test(f"Inspecting job {job_id}...")
result = await tool.execute({ "operation": "inspect", "args": { "job_id": job_id } })
if result.get("isError"): print_error(f"Failed to inspect job: {result['formatted']}") return False
print_success(f"Inspected job successfully") return True
async def test_get_logs(tool, job_id): """Test fetching job logs""" print_test(f"Fetching logs for job {job_id}...")
# Wait a bit for logs to be available await asyncio.sleep(2)
result = await tool.execute({ "operation": "logs", "args": { "job_id": job_id } })
if result.get("isError"): print_warning(f"Could not fetch logs (might be too early): {result['formatted'][:100]}") return False
print_success(f"Fetched logs successfully") if "Hello from HF Jobs!" in result['formatted']: print_success(" Found expected output in logs!") return True
async def test_cancel_job(tool, job_id): """Test cancelling a job""" print_test(f"Cancelling job {job_id}...")
result = await tool.execute({ "operation": "cancel", "args": { "job_id": job_id } })
if result.get("isError"): print_error(f"Failed to cancel job: {result['formatted']}") return False
print_success(f"Cancelled job successfully") return True
async def test_uv_job(tool): """Test running a UV job""" print_test("Running a UV Python script job...")
result = await tool.execute({ "operation": "uv", "args": { "script": "print('Hello from UV!')\nimport sys\nprint(f'Python version: {sys.version}')", "flavor": "cpu-basic", "timeout": "5m", "detach": True } })
if result.get("isError"): print_error(f"Failed to run UV job: {result['formatted']}") return None
# Extract job ID import re job_id_match = re.search(r'UV Job started: (\S+)', result['formatted']) if job_id_match: job_id = job_id_match.group(1) print_success(f"UV job started with ID: {job_id}") return job_id
print_error("Could not extract job ID from response") return None
async def test_list_all_jobs(tool): """Test listing all jobs (including completed)""" print_test("Listing all jobs (including completed)...")
result = await tool.execute({ "operation": "ps", "args": { "all": True } })
if result.get("isError"): print_error(f"Failed to list all jobs: {result['formatted']}") return False
print_success(f"Listed all jobs: {result['totalResults']} total") return True
async def test_scheduled_job(tool): """Test creating and managing a scheduled job""" print_test("Creating a scheduled job (daily at midnight)...")
result = await tool.execute({ "operation": "scheduled run", "args": { "image": "python:3.12", "command": ["python", "-c", "print('Scheduled job running!')"], "schedule": "@daily", "flavor": "cpu-basic", "timeout": "5m" } })
if result.get("isError"): print_error(f"Failed to create scheduled job: {result['formatted']}") return None
# Extract scheduled job ID import re job_id_match = re.search(r'\*\*Scheduled Job ID:\*\* (\S+)', result['formatted']) if not job_id_match: print_error("Could not extract scheduled job ID") return None
scheduled_job_id = job_id_match.group(1) print_success(f"Scheduled job created with ID: {scheduled_job_id}") return scheduled_job_id
async def test_list_scheduled_jobs(tool): """Test listing scheduled jobs""" print_test("Listing scheduled jobs...")
result = await tool.execute({ "operation": "scheduled ps", "args": {} })
if result.get("isError"): print_error(f"Failed to list scheduled jobs: {result['formatted']}") return False
print_success(f"Listed scheduled jobs: {result['totalResults']} active") return True
async def test_inspect_scheduled_job(tool, scheduled_job_id): """Test inspecting a scheduled job""" print_test(f"Inspecting scheduled job {scheduled_job_id}...")
result = await tool.execute({ "operation": "scheduled inspect", "args": { "scheduled_job_id": scheduled_job_id } })
if result.get("isError"): print_error(f"Failed to inspect scheduled job: {result['formatted']}") return False
print_success(f"Inspected scheduled job successfully") return True
async def test_suspend_scheduled_job(tool, scheduled_job_id): """Test suspending a scheduled job""" print_test(f"Suspending scheduled job {scheduled_job_id}...")
result = await tool.execute({ "operation": "scheduled suspend", "args": { "scheduled_job_id": scheduled_job_id } })
if result.get("isError"): print_error(f"Failed to suspend scheduled job: {result['formatted']}") return False
print_success(f"Suspended scheduled job successfully") return True
async def test_resume_scheduled_job(tool, scheduled_job_id): """Test resuming a scheduled job""" print_test(f"Resuming scheduled job {scheduled_job_id}...")
result = await tool.execute({ "operation": "scheduled resume", "args": { "scheduled_job_id": scheduled_job_id } })
if result.get("isError"): print_error(f"Failed to resume scheduled job: {result['formatted']}") return False
print_success(f"Resumed scheduled job successfully") return True
async def test_delete_scheduled_job(tool, scheduled_job_id): """Test deleting a scheduled job""" print_test(f"Deleting scheduled job {scheduled_job_id}...")
result = await tool.execute({ "operation": "scheduled delete", "args": { "scheduled_job_id": scheduled_job_id } })
if result.get("isError"): print_error(f"Failed to delete scheduled job: {result['formatted']}") return False
print_success(f"Deleted scheduled job successfully") return True
async def main(): """Run all integration tests""" print("=" * 70) print(f"{BLUE}HF Jobs Tool - Integration Tests{RESET}") print("=" * 70) print()
# Check for HF_TOKEN hf_token = os.environ.get('HF_TOKEN') if not hf_token: print_error("HF_TOKEN not found in environment variables!") print_warning("Set it with: export HF_TOKEN='your_token_here'") sys.exit(1)
print_success(f"Found HF_TOKEN (length: {len(hf_token)})") print()
# Initialize tool with token tool = HfJobsTool(hf_token=hf_token)
# Track job IDs for cleanup job_ids = [] scheduled_job_ids = []
try: # Test 1: Run basic job print(f"\n{YELLOW}{'=' * 70}{RESET}") print(f"{YELLOW}Test Suite 1: Regular Jobs{RESET}") print(f"{YELLOW}{'=' * 70}{RESET}\n")
job_id = await test_basic_job_run(tool) if job_id: job_ids.append(job_id)
# Wait a moment for job to register await asyncio.sleep(1)
# Test 2: List jobs await test_list_jobs(tool)
# Test 3: Inspect job await test_inspect_job(tool, job_id)
# Test 4: Get logs await test_get_logs(tool, job_id)
# Test 5: Cancel job (cleanup) await test_cancel_job(tool, job_id)
# Test 6: UV job print() uv_job_id = await test_uv_job(tool) if uv_job_id: job_ids.append(uv_job_id) await asyncio.sleep(1) await test_cancel_job(tool, uv_job_id)
# Test 7: List all jobs print() await test_list_all_jobs(tool)
# Test Suite 2: Scheduled Jobs print(f"\n{YELLOW}{'=' * 70}{RESET}") print(f"{YELLOW}Test Suite 2: Scheduled Jobs{RESET}") print(f"{YELLOW}{'=' * 70}{RESET}\n")
scheduled_job_id = await test_scheduled_job(tool) if scheduled_job_id: scheduled_job_ids.append(scheduled_job_id)
# Wait a moment for job to register await asyncio.sleep(1)
# Test scheduled job operations await test_list_scheduled_jobs(tool) print() await test_inspect_scheduled_job(tool, scheduled_job_id) print() await test_suspend_scheduled_job(tool, scheduled_job_id) print() await test_resume_scheduled_job(tool, scheduled_job_id) print()
# Cleanup: Delete scheduled job await test_delete_scheduled_job(tool, scheduled_job_id)
# Final summary print(f"\n{YELLOW}{'=' * 70}{RESET}") print(f"{GREEN}✓ All integration tests completed!{RESET}") print(f"{YELLOW}{'=' * 70}{RESET}\n")
print_success("Refactored implementation works correctly with real HF API") print_success("All 13 operations tested and verified") print() print(f"{BLUE}Summary:{RESET}") print(f" • Regular jobs: ✓ run, list, inspect, logs, cancel") print(f" • UV jobs: ✓ run") print(f" • Scheduled jobs: ✓ create, list, inspect, suspend, resume, delete") print()
except Exception as e: print_error(f"Test failed with exception: {str(e)}") import traceback traceback.print_exc()
# Attempt cleanup print(f"\n{YELLOW}Attempting cleanup...{RESET}") for job_id in job_ids: try: await test_cancel_job(tool, job_id) except: pass
for scheduled_job_id in scheduled_job_ids: try: await test_delete_scheduled_job(tool, scheduled_job_id) except: pass
sys.exit(1)
if __name__ == "__main__": asyncio.run(main())1"""Tests for agent tools"""1"""Tests for HF tools"""1"""Tests for HF Jobs tool"""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252"""Tests for HF Jobs Tool
Tests the jobs tool implementation"""import pytestfrom unittest.mock import AsyncMock, MagicMock, patchfrom agent.tools.hf.jobs.jobs_tool import HfJobsTool, hf_jobs_handler
@pytest.mark.asyncioasync def test_show_help(): """Test that help message is shown when no operation specified""" tool = HfJobsTool() result = await tool.execute({})
assert "HuggingFace Jobs API" in result["formatted"] assert "Available Commands" in result["formatted"] assert result["totalResults"] == 1 assert not result.get("isError", False)
@pytest.mark.asyncioasync def test_show_operation_help(): """Test operation-specific help""" tool = HfJobsTool() result = await tool.execute({"operation": "run", "args": {"help": True}})
assert "Help for operation" in result["formatted"] assert result["totalResults"] == 1
@pytest.mark.asyncioasync def test_invalid_operation(): """Test invalid operation handling""" tool = HfJobsTool() result = await tool.execute({"operation": "invalid_op"})
assert result.get("isError") == True assert "Unknown operation" in result["formatted"]
@pytest.mark.asyncioasync def test_run_job_missing_command(): """Test run job with missing required parameter""" tool = HfJobsTool() result = await tool.execute({ "operation": "run", "args": {"image": "python:3.12"} })
assert result.get("isError") == True assert "command parameter is required" in result["formatted"]
@pytest.mark.asyncioasync def test_list_jobs_mock(): """Test list jobs with mock API""" tool = HfJobsTool()
# Mock the API client with patch.object(tool.client, 'list_jobs', new_callable=AsyncMock) as mock_list: mock_list.return_value = [ { 'id': 'test-job-1', 'status': {'stage': 'RUNNING'}, 'command': ['echo', 'test'], 'createdAt': '2024-01-01T00:00:00Z', 'owner': {'name': 'test-user'} }, { 'id': 'test-job-2', 'status': {'stage': 'COMPLETED'}, 'command': ['python', 'script.py'], 'createdAt': '2024-01-01T01:00:00Z', 'owner': {'name': 'test-user'} } ]
# Test listing only running jobs (default) result = await tool.execute({"operation": "ps"})
assert not result.get("isError", False) assert "test-job-1" in result["formatted"] assert "test-job-2" not in result["formatted"] # COMPLETED jobs filtered out assert result["totalResults"] == 2 assert result["resultsShared"] == 1
# Test listing all jobs result = await tool.execute({"operation": "ps", "args": {"all": True}})
assert not result.get("isError", False) assert "test-job-1" in result["formatted"] assert "test-job-2" in result["formatted"] assert result["totalResults"] == 2 assert result["resultsShared"] == 2
@pytest.mark.asyncioasync def test_inspect_job_mock(): """Test inspect job with mock API""" tool = HfJobsTool()
with patch.object(tool.client, 'get_job', new_callable=AsyncMock) as mock_get: mock_get.return_value = { 'id': 'test-job-1', 'status': {'stage': 'RUNNING'}, 'command': ['echo', 'test'], 'createdAt': '2024-01-01T00:00:00Z', 'owner': {'name': 'test-user'}, 'flavor': 'cpu-basic' }
result = await tool.execute({ "operation": "inspect", "args": {"job_id": "test-job-1"} })
assert not result.get("isError", False) assert "test-job-1" in result["formatted"] assert "Job Details" in result["formatted"] mock_get.assert_called_once()
@pytest.mark.asyncioasync def test_cancel_job_mock(): """Test cancel job with mock API""" tool = HfJobsTool()
with patch.object(tool.client, 'cancel_job', new_callable=AsyncMock) as mock_cancel: mock_cancel.return_value = None
result = await tool.execute({ "operation": "cancel", "args": {"job_id": "test-job-1"} })
assert not result.get("isError", False) assert "cancelled" in result["formatted"] assert "test-job-1" in result["formatted"] mock_cancel.assert_called_once()
@pytest.mark.asyncioasync def test_handler(): """Test the handler function""" with patch('agent.tools.hf.jobs.jobs_tool.HfJobsTool') as MockTool: mock_tool_instance = MockTool.return_value mock_tool_instance.execute = AsyncMock(return_value={ "formatted": "Test output", "totalResults": 1, "resultsShared": 1, "isError": False })
output, success = await hf_jobs_handler({"operation": "ps"})
assert success == True assert "Test output" in output
@pytest.mark.asyncioasync def test_handler_error(): """Test handler with error""" with patch('agent.tools.hf.jobs.jobs_tool.HfJobsTool') as MockTool: MockTool.side_effect = Exception("Test error")
output, success = await hf_jobs_handler({})
assert success == False assert "Error" in output
@pytest.mark.asyncioasync def test_scheduled_jobs_mock(): """Test scheduled jobs operations with mock API""" tool = HfJobsTool()
# Test list scheduled jobs with patch.object(tool.client, 'list_scheduled_jobs', new_callable=AsyncMock) as mock_list: mock_list.return_value = [ { 'id': 'sched-job-1', 'schedule': '@daily', 'suspend': False, 'jobSpec': { 'command': ['python', 'backup.py'], 'dockerImage': 'python:3.12' }, 'nextRun': '2024-01-02T00:00:00Z' } ]
result = await tool.execute({"operation": "scheduled ps"})
assert not result.get("isError", False) assert "sched-job-1" in result["formatted"] assert "Scheduled Jobs" in result["formatted"]
def test_job_utils(): """Test job utility functions""" from agent.tools.hf.jobs.job_utils import parse_timeout, parse_image_source, parse_command
# Test timeout parsing assert parse_timeout("5m") == 300 assert parse_timeout("2h") == 7200 assert parse_timeout("30s") == 30 assert parse_timeout("1d") == 86400
# Test image source parsing result = parse_image_source("python:3.12") assert result["dockerImage"] == "python:3.12" assert result["spaceId"] is None
result = parse_image_source("https://huggingface.co/spaces/user/space") assert result["dockerImage"] is None assert result["spaceId"] == "user/space"
# Test command parsing result = parse_command(["python", "script.py"]) assert result["command"] == ["python", "script.py"]
result = parse_command("python script.py") assert result["command"] == ["python", "script.py"]
def test_uv_utils(): """Test UV utility functions""" from agent.tools.hf.jobs.uv_utils import build_uv_command, resolve_uv_command
# Test build UV command command = build_uv_command("script.py", {}) assert command == ["uv", "run", "script.py"]
command = build_uv_command("script.py", { "with_deps": ["requests", "numpy"], "python": "3.12" }) assert "uv" in command assert "run" in command assert "--with" in command assert "requests" in command assert "-p" in command assert "3.12" in command
# Test resolve UV command command = resolve_uv_command({"script": "https://example.com/script.py"}) assert "https://example.com/script.py" in command
command = resolve_uv_command({"script": "print('hello')"}) assert command == ["uv", "run", "print('hello')"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454"""Tests for HF Jobs Tool
Tests the refactored jobs tool implementation using huggingface-hub library"""
from unittest.mock import AsyncMock, patch
import pytest
from agent.tools.jobs_tool import HfJobsTool, hf_jobs_handler
def create_mock_job_info( job_id="test-job-1", stage="RUNNING", command=None, docker_image="python:3.12",): """Create a mock JobInfo object""" from huggingface_hub._jobs_api import JobInfo
if command is None: command = ["echo", "test"]
return JobInfo( id=job_id, created_at="2024-01-01T00:00:00.000000Z", docker_image=docker_image, space_id=None, command=command, arguments=[], environment={}, secrets={}, flavor="cpu-basic", status={"stage": stage, "message": None}, owner={"id": "123", "name": "test-user", "type": "user"}, endpoint="https://huggingface.co", url=f"https://huggingface.co/jobs/test-user/{job_id}", )
def create_mock_scheduled_job_info( job_id="sched-job-1", schedule="@daily", suspend=False,): """Create a mock ScheduledJobInfo object""" from huggingface_hub._jobs_api import ScheduledJobInfo
return ScheduledJobInfo( id=job_id, created_at="2024-01-01T00:00:00.000000Z", job_spec={ "docker_image": "python:3.12", "space_id": None, "command": ["python", "backup.py"], "arguments": [], "environment": {}, "secrets": {}, "flavor": "cpu-basic", "timeout": 1800, "tags": None, "arch": None, }, schedule=schedule, suspend=suspend, concurrency=False, status={ "last_job": None, "next_job_run_at": "2024-01-02T00:00:00.000000Z", }, owner={"id": "123", "name": "test-user", "type": "user"}, )
@pytest.mark.asyncioasync def test_show_help(): """Test that help message is shown when no operation specified""" tool = HfJobsTool() result = await tool.execute({})
assert "HuggingFace Jobs API" in result["formatted"] assert "Available Commands" in result["formatted"] assert result["totalResults"] == 1 assert not result.get("isError", False)
@pytest.mark.asyncioasync def test_show_operation_help(): """Test operation-specific help""" tool = HfJobsTool() result = await tool.execute({"operation": "run", "args": {"help": True}})
assert "Help for operation" in result["formatted"] assert result["totalResults"] == 1
@pytest.mark.asyncioasync def test_invalid_operation(): """Test invalid operation handling""" tool = HfJobsTool() result = await tool.execute({"operation": "invalid_op"})
assert result.get("isError") == True assert "Unknown operation" in result["formatted"]
@pytest.mark.asyncioasync def test_run_job_missing_command(): """Test run job with missing required parameter""" tool = HfJobsTool()
# Mock the HfApi.run_job to raise an error with patch.object(tool.api, "run_job") as mock_run: mock_run.side_effect = Exception("command parameter is required")
result = await tool.execute( {"operation": "run", "args": {"image": "python:3.12"}} )
assert result.get("isError") == True
@pytest.mark.asyncioasync def test_list_jobs_mock(): """Test list jobs with mock API""" tool = HfJobsTool()
# Create mock job objects running_job = create_mock_job_info("test-job-1", "RUNNING") completed_job = create_mock_job_info( "test-job-2", "COMPLETED", ["python", "script.py"] )
# Mock the HfApi.list_jobs method with patch.object(tool.api, "list_jobs") as mock_list: mock_list.return_value = [running_job, completed_job]
# Test listing only running jobs (default) result = await tool.execute({"operation": "ps"})
assert not result.get("isError", False) assert "test-job-1" in result["formatted"] assert "test-job-2" not in result["formatted"] # COMPLETED jobs filtered out assert result["totalResults"] == 1 assert result["resultsShared"] == 1
# Test listing all jobs result = await tool.execute({"operation": "ps", "args": {"all": True}})
assert not result.get("isError", False) assert "test-job-1" in result["formatted"] assert "test-job-2" in result["formatted"] assert result["totalResults"] == 2 assert result["resultsShared"] == 2
@pytest.mark.asyncioasync def test_inspect_job_mock(): """Test inspect job with mock API""" tool = HfJobsTool()
mock_job = create_mock_job_info("test-job-1", "RUNNING")
with patch.object(tool.api, "inspect_job") as mock_inspect: mock_inspect.return_value = mock_job
result = await tool.execute( {"operation": "inspect", "args": {"job_id": "test-job-1"}} )
assert not result.get("isError", False) assert "test-job-1" in result["formatted"] assert "Job Details" in result["formatted"] mock_inspect.assert_called_once()
@pytest.mark.asyncioasync def test_cancel_job_mock(): """Test cancel job with mock API""" tool = HfJobsTool()
with patch.object(tool.api, "cancel_job") as mock_cancel: mock_cancel.return_value = None
result = await tool.execute( {"operation": "cancel", "args": {"job_id": "test-job-1"}} )
assert not result.get("isError", False) assert "cancelled" in result["formatted"] assert "test-job-1" in result["formatted"] mock_cancel.assert_called_once()
@pytest.mark.asyncioasync def test_run_job_mock(): """Test run job with mock API""" tool = HfJobsTool()
mock_job = create_mock_job_info("new-job-123", "RUNNING")
with patch.object(tool.api, "run_job") as mock_run: mock_run.return_value = mock_job
result = await tool.execute( { "operation": "run", "args": { "image": "python:3.12", "command": ["python", "-c", "print('test')"], "flavor": "cpu-basic", "detach": True, }, } )
assert not result.get("isError", False) assert "new-job-123" in result["formatted"] assert "Job started" in result["formatted"] mock_run.assert_called_once()
@pytest.mark.asyncioasync def test_run_uv_job_mock(): """Test run UV job with mock API""" tool = HfJobsTool()
mock_job = create_mock_job_info("uv-job-456", "RUNNING")
with patch.object(tool.api, "run_uv_job") as mock_run: mock_run.return_value = mock_job
result = await tool.execute( { "operation": "uv", "args": { "script": "print('Hello UV')", "flavor": "cpu-basic", }, } )
assert not result.get("isError", False) assert "uv-job-456" in result["formatted"] assert "UV Job started" in result["formatted"] mock_run.assert_called_once()
@pytest.mark.asyncioasync def test_get_logs_mock(): """Test get logs with mock API""" tool = HfJobsTool()
# Mock fetch_job_logs to return a generator def log_generator(): yield "Log line 1" yield "Log line 2" yield "Hello from HF Jobs!"
with patch.object(tool.api, "fetch_job_logs") as mock_logs: mock_logs.return_value = log_generator()
result = await tool.execute( {"operation": "logs", "args": {"job_id": "test-job-1"}} )
assert not result.get("isError", False) assert "Log line 1" in result["formatted"] assert "Hello from HF Jobs!" in result["formatted"]
@pytest.mark.asyncioasync def test_handler(): """Test the handler function""" with patch("agent.tools.jobs_tool.HfJobsTool") as MockTool: mock_tool_instance = MockTool.return_value mock_tool_instance.execute = AsyncMock( return_value={ "formatted": "Test output", "totalResults": 1, "resultsShared": 1, "isError": False, } )
output, success = await hf_jobs_handler({"operation": "ps"})
assert success == True assert "Test output" in output
@pytest.mark.asyncioasync def test_handler_error(): """Test handler with error""" with patch("agent.tools.jobs_tool.HfJobsTool") as MockTool: MockTool.side_effect = Exception("Test error")
output, success = await hf_jobs_handler({})
assert success == False assert "Error" in output
@pytest.mark.asyncioasync def test_scheduled_jobs_mock(): """Test scheduled jobs operations with mock API""" tool = HfJobsTool()
mock_scheduled_job = create_mock_scheduled_job_info()
# Test list scheduled jobs with patch.object(tool.api, "list_scheduled_jobs") as mock_list: mock_list.return_value = [mock_scheduled_job]
result = await tool.execute({"operation": "scheduled ps"})
assert not result.get("isError", False) assert "sched-job-1" in result["formatted"] assert "Scheduled Jobs" in result["formatted"]
@pytest.mark.asyncioasync def test_create_scheduled_job_mock(): """Test create scheduled job with mock API""" tool = HfJobsTool()
mock_scheduled_job = create_mock_scheduled_job_info()
with patch.object(tool.api, "create_scheduled_job") as mock_create: mock_create.return_value = mock_scheduled_job
result = await tool.execute( { "operation": "scheduled run", "args": { "image": "python:3.12", "command": ["python", "backup.py"], "schedule": "@daily", "flavor": "cpu-basic", }, } )
assert not result.get("isError", False) assert "sched-job-1" in result["formatted"] assert "Scheduled job created" in result["formatted"] mock_create.assert_called_once()
@pytest.mark.asyncioasync def test_inspect_scheduled_job_mock(): """Test inspect scheduled job with mock API""" tool = HfJobsTool()
mock_scheduled_job = create_mock_scheduled_job_info()
with patch.object(tool.api, "inspect_scheduled_job") as mock_inspect: mock_inspect.return_value = mock_scheduled_job
result = await tool.execute( { "operation": "scheduled inspect", "args": {"scheduled_job_id": "sched-job-1"}, } )
assert not result.get("isError", False) assert "sched-job-1" in result["formatted"] assert "Scheduled Job Details" in result["formatted"]
@pytest.mark.asyncioasync def test_suspend_scheduled_job_mock(): """Test suspend scheduled job with mock API""" tool = HfJobsTool()
with patch.object(tool.api, "suspend_scheduled_job") as mock_suspend: mock_suspend.return_value = None
result = await tool.execute( { "operation": "scheduled suspend", "args": {"scheduled_job_id": "sched-job-1"}, } )
assert not result.get("isError", False) assert "suspended" in result["formatted"] assert "sched-job-1" in result["formatted"]
@pytest.mark.asyncioasync def test_resume_scheduled_job_mock(): """Test resume scheduled job with mock API""" tool = HfJobsTool()
with patch.object(tool.api, "resume_scheduled_job") as mock_resume: mock_resume.return_value = None
result = await tool.execute( { "operation": "scheduled resume", "args": {"scheduled_job_id": "sched-job-1"}, } )
assert not result.get("isError", False) assert "resumed" in result["formatted"] assert "sched-job-1" in result["formatted"]
@pytest.mark.asyncioasync def test_delete_scheduled_job_mock(): """Test delete scheduled job with mock API""" tool = HfJobsTool()
with patch.object(tool.api, "delete_scheduled_job") as mock_delete: mock_delete.return_value = None
result = await tool.execute( { "operation": "scheduled delete", "args": {"scheduled_job_id": "sched-job-1"}, } )
assert not result.get("isError", False) assert "deleted" in result["formatted"] assert "sched-job-1" in result["formatted"]
@pytest.mark.asyncioasync def test_list_jobs_with_status_filter(): """Test list jobs with status filter""" tool = HfJobsTool()
running_job = create_mock_job_info("job-1", "RUNNING") completed_job = create_mock_job_info("job-2", "COMPLETED") error_job = create_mock_job_info("job-3", "ERROR")
with patch.object(tool.api, "list_jobs") as mock_list: mock_list.return_value = [running_job, completed_job, error_job]
# Filter by status result = await tool.execute( {"operation": "ps", "args": {"all": True, "status": "ERROR"}} )
assert not result.get("isError", False) assert "job-3" in result["formatted"] assert "job-1" not in result["formatted"] assert result["resultsShared"] == 1892 unmodified lines89389489589689789812 unmodified lines911912913914915916181 unmodified lines1098109911001101110211031599 unmodified lines270327042705270627072708355 unmodified lines306430653066306730683069892 unmodified lines{ name = "numpy" },{ name = "pandas" },{ name = "pydantic" },{ name = "python-dotenv" },{ name = "requests" },{ name = "tenacity" },12 unmodified lines{ name = "numpy", specifier = ">=1.24.0" },{ name = "pandas", specifier = ">=2.3.3" },{ name = "pydantic", specifier = ">=2.12.3" },{ name = "python-dotenv", specifier = ">=1.2.1" },{ name = "requests", specifier = ">=2.32.5" },{ name = "tenacity", specifier = ">=8.0.0" },181 unmodified lines{ url = "https://files.pythonhosted.org/packages/59/91/aa6bde563e0085a02a435aa99b49ef75b0a4b062635e606dab23ce18d720/inflection-0.5.1-py2.py3-none-any.whl", hash = "sha256:f38b2b640938a4f35ade69ac3d053042959b62a0f1076a5bbaa1b9526605a8a2", size = 9454, upload-time = "2020-08-22T08:16:27.816Z" },][[package]]name = "inspect-ai"version = "0.3.149"1599 unmodified lines{ url = "https://files.pythonhosted.org/packages/73/cb/ac7874b3e5d58441674fb70742e6c374b28b0c7cb988d37d991cde47166c/platformdirs-4.5.0-py3-none-any.whl", hash = "sha256:e578a81bb873cbb89a41fcc904c7ef523cc18284b7e3b3ccf06aca1403b7ebd3", size = 18651, upload-time = "2025-10-08T17:44:47.223Z" },][[package]]name = "ply"version = "3.11"355 unmodified lines{ url = "https://files.pythonhosted.org/packages/df/80/fc9d01d5ed37ba4c42ca2b55b4339ae6e200b456be3a1aaddf4a9fa99b8c/pyperclip-1.11.0-py3-none-any.whl", hash = "sha256:299403e9ff44581cb9ba2ffeed69c7aa96a008622ad0c46cb575ca75b5b84273", size = 11063, upload-time = "2025-09-26T14:40:36.069Z" },][[package]]name = "python-dateutil"version = "2.9.0.post0"892 unmodified lines89389489589689789889912 unmodified lines912913914915916917918181 unmodified lines1100110111021103110411051106110711081109111011111112111311141599 unmodified lines271427152716271727182719272027212722272327242725272627272728355 unmodified lines3084308530863087308830893090309130923093309430953096309730983099310031013102310331043105892 unmodified lines{ name = "numpy" },{ name = "pandas" },{ name = "pydantic" },{ name = "pytest" },{ name = "python-dotenv" },{ name = "requests" },{ name = "tenacity" },12 unmodified lines{ name = "numpy", specifier = ">=1.24.0" },{ name = "pandas", specifier = ">=2.3.3" },{ name = "pydantic", specifier = ">=2.12.3" },{ name = "pytest", specifier = ">=9.0.2" },{ name = "python-dotenv", specifier = ">=1.2.1" },{ name = "requests", specifier = ">=2.32.5" },{ name = "tenacity", specifier = ">=8.0.0" },181 unmodified lines{ url = "https://files.pythonhosted.org/packages/59/91/aa6bde563e0085a02a435aa99b49ef75b0a4b062635e606dab23ce18d720/inflection-0.5.1-py2.py3-none-any.whl", hash = "sha256:f38b2b640938a4f35ade69ac3d053042959b62a0f1076a5bbaa1b9526605a8a2", size = 9454, upload-time = "2020-08-22T08:16:27.816Z" },][[package]]name = "iniconfig"version = "2.3.0"source = { registry = "https://pypi.org/simple" }sdist = { url = "https://files.pythonhosted.org/packages/72/34/14ca021ce8e5dfedc35312d08ba8bf51fdd999c576889fc2c24cb97f4f10/iniconfig-2.3.0.tar.gz", hash = "sha256:c76315c77db068650d49c5b56314774a7804df16fee4402c1f19d6d15d8c4730", size = 20503, upload-time = "2025-10-18T21:55:43.219Z" }wheels = [{ url = "https://files.pythonhosted.org/packages/cb/b1/3846dd7f199d53cb17f49cba7e651e9ce294d8497c8c150530ed11865bb8/iniconfig-2.3.0-py3-none-any.whl", hash = "sha256:f631c04d2c48c52b84d0d0549c99ff3859c98df65b3101406327ecc7d53fbf12", size = 7484, upload-time = "2025-10-18T21:55:41.639Z" },][[package]]name = "inspect-ai"version = "0.3.149"1599 unmodified lines{ url = "https://files.pythonhosted.org/packages/73/cb/ac7874b3e5d58441674fb70742e6c374b28b0c7cb988d37d991cde47166c/platformdirs-4.5.0-py3-none-any.whl", hash = "sha256:e578a81bb873cbb89a41fcc904c7ef523cc18284b7e3b3ccf06aca1403b7ebd3", size = 18651, upload-time = "2025-10-08T17:44:47.223Z" },][[package]]name = "pluggy"version = "1.6.0"source = { registry = "https://pypi.org/simple" }sdist = { url = "https://files.pythonhosted.org/packages/f9/e2/3e91f31a7d2b083fe6ef3fa267035b518369d9511ffab804f839851d2779/pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3", size = 69412, upload-time = "2025-05-15T12:30:07.975Z" }wheels = [{ url = "https://files.pythonhosted.org/packages/54/20/4d324d65cc6d9205fabedc306948156824eb9f0ee1633355a8f7ec5c66bf/pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746", size = 20538, upload-time = "2025-05-15T12:30:06.134Z" },][[package]]name = "ply"version = "3.11"355 unmodified lines{ url = "https://files.pythonhosted.org/packages/df/80/fc9d01d5ed37ba4c42ca2b55b4339ae6e200b456be3a1aaddf4a9fa99b8c/pyperclip-1.11.0-py3-none-any.whl", hash = "sha256:299403e9ff44581cb9ba2ffeed69c7aa96a008622ad0c46cb575ca75b5b84273", size = 11063, upload-time = "2025-09-26T14:40:36.069Z" },][[package]]name = "pytest"version = "9.0.2"source = { registry = "https://pypi.org/simple" }dependencies = [{ name = "colorama", marker = "sys_platform == 'win32'" },{ name = "iniconfig" },{ name = "packaging" },{ name = "pluggy" },{ name = "pygments" },]sdist = { url = "https://files.pythonhosted.org/packages/d1/db/7ef3487e0fb0049ddb5ce41d3a49c235bf9ad299b6a25d5780a89f19230f/pytest-9.0.2.tar.gz", hash = "sha256:75186651a92bd89611d1d9fc20f0b4345fd827c41ccd5c299a868a05d70edf11", size = 1568901, upload-time = "2025-12-06T21:30:51.014Z" }wheels = [{ url = "https://files.pythonhosted.org/packages/3b/ab/b3226f0bd7cdcf710fbede2b3548584366da3b19b5021e74f5bde2a8fa3f/pytest-9.0.2-py3-none-any.whl", hash = "sha256:711ffd45bf766d5264d487b917733b453d917afd2b0ad65223959f59089f875b", size = 374801, upload-time = "2025-12-06T21:30:49.154Z" },][[package]]name = "python-dateutil"version = "2.9.0.post0"
agent/config_local_mcp.jsonDeleted-16
agent/core/__init__.py+1-2
agent/core/tools.py+8-88
agent/tests/__init__.pyDeleted-3
agent/tests/unit/test_base.pyDeleted-10
agent/tools/__init__.pyAdded+8
agent/tools/hf/__init__.pyDeleted-7
agent/tools/hf/base.pyDeleted-84
agent/tools/hf/jobs/__init__.pyDeleted-6
agent/tools/hf/jobs/api_client.pyDeleted-156
agent/tools/hf/jobs/job_utils.pyDeleted-130
agent/tools/hf/jobs/uv_utils.pyDeleted-66
agent/tools/hf/jobs/jobs_tool.py → agent/tools/jobs_tool.pyRenamed+471-287
agent/tools/hf/types.py → agent/tools/types.pyRenamed+3-1
agent/tools/hf/utilities.py → agent/tools/utilities.pyRenamed+49-40
pyproject.toml+1
tests/__init__.pyAdded
tests/integration/__init__.pyAdded
tests/integration/tools/__init__.pyAdded
tests/integration/tools/test_jobs_integration.pyAdded+452
tests/tools/__init__.pyDeleted-1
tests/tools/hf/__init__.pyDeleted-1
tests/tools/hf/jobs/__init__.pyDeleted-1
tests/tools/hf/jobs/test_jobs_tool.pyDeleted-252
tests/unit/__init__.pyAdded
tests/unit/tools/__init__.pyAdded
tests/unit/tools/test_jobs_tool.pyAdded+454
uv.lock+36