text_a stringlengths 31 2k | text_b stringlengths 7 2k | label float64 0 1 | pair_type stringclasses 4
values |
|---|---|---|---|
def matches_platform(self) -> bool:
"""Check if this skill is compatible with the current platform."""
if not self.platforms:
return True # No platform restriction
current = sys.platform
for p in self.platforms:
prefix = _PLATFORM_MAP.get(p.lower(), p.lower()... | Check if this skill is compatible with the current platform. | 1 | source_docstring |
def get_function_definition(self) -> dict[str, Any]:
"""OpenAI-style function definition (for the LLM)."""
return {
"type": "function",
"function": {
"name": self.name,
"description": self.description,
"parameters": self.input_s... | Aggregate every built-in extension's prompt sections.
Returns a single string the JARVIS agent can append
to its system prompt so it knows about the available
tools. | 0 | cross_docstring |
async def list_tools(self) -> list[MCPToolSpec]:
return [
MCPToolSpec(
name="echo",
description="Echo input",
input_schema={"type": "object"},
)
] | function list_tools | 0.5 | source_name |
def get_agent(self, name: str) -> AgentProfile:
"""
Get an agent profile by name
Args:
name: Name of the agent
Returns:
AgentProfile instance
Raises:
ValueError: If agent not found
"""
if agent := self.available_agents.ge... | Register a custom agent profile
Args:
profile: Agent profile to register | 0 | cross_docstring |
def mermaid_section_id(section_id: str) -> str:
"""Convert a section ID (like 'cli-entry') to a safe Mermaid ID (like 'CLI_ENTRY')."""
return stable_ascii_id(section_id, "section").upper() | Classify edges as intra-section or inter-section.
Returns:
{
"intra": {section_id: [edges]},
"inter": [edges],
"orphan": [edges] # one endpoint not in any section
} | 0 | cross_docstring |
class ModelInfo:
"""Complete model information."""
id: str
name: str
provider_id: str
provider_name: str
family: str | None = None
reasoning: bool = False
tool_call: bool = False
temperature: bool = False
structured_output: bool = False
knowledge_date: str | None = None
... | Fetch model information from models.dev API. | 0 | cross_docstring |
def test_get_or_create_assigns_session_id(self, fresh_messaging_home):
sm = SessionManager(persist=False)
chat = Chat(platform="webhook", chat_id="alice")
s1 = sm.get_or_create(chat)
s2 = sm.get_or_create(chat)
assert s1 is s2
assert s1.session_id == s2.session_id
... | async def get_mentions(
self,
account_id: Optional[str] = None,
limit: int = 25,
) -> List[InstagramMention]:
"""Get recent mentions (posts/comments that @mention you)."""
if not account_id:
account_id = self.settings.instagram_business_account_id
if n... | 0 | random_source |
class Chat(BaseChat):
"""
Standard chat interface for the provider.
"""
def __init__(self, client: "TextPollinations"):
self.completions = Completions(client) | def description(self) -> str:
return "Core session commands: prompt, steer, follow_up, bash, compact, new_session" | 0 | random_source |
class FreeAI(OpenAICompatibleProvider):
required_auth = False
AVAILABLE_MODELS = [
"qwen7b",
"qwen3-8b",
"deepseek-r1",
"deepseek-r1-7b",
"mistral",
"qwen/qwen3-8b",
"deepseek/deepseek-chat-v3-0324",
"deepseek/deepseek-r1",
"openai/gpt-4o-m... | def get_gpg_keys(self) -> List[Dict[str, Any]]:
"""Get user's public GPG keys"""
url = f"{self.base_url}/gpg_keys"
return request(url) | 0 | random_source |
def format_scan_report(result: ScanResult) -> str:
"""Format a scan result as a human-readable report."""
lines = [
f"=== Skill Security Scan: {result.skill_name} ===",
f"Source: {result.source} | Trust: {result.trust_level}",
f"Verdict: {result.verdict.upper()}",
f"Scanned: {res... | def make_eraser(objects_to_erase: list, scene: Scene, *, start_time: float, duration: float = 1.2) -> None:
eraser = Eraser(
objects_to_erase=objects_to_erase,
drawable_cache=scene.drawable_cache,
glow_dot_hint={"color": (0.7, 0.7, 0.7), "radius": 15},
)
scene.add(SketchAnimation(sta... | 0 | random_source |
def apply(self, opsset: OpsSet, progress: float) -> OpsSet:
if self.easing_fun is not None:
progress = float(self.easing_fun(progress))
# Calculate offset based on direction
if self.direction == "left":
dx = -self.distance * progress
dy = 0
... | def on_session_start(self, agent: "BaseAgent") -> None:
"""Optional: called once per JARVIS session, after
:meth:`register`. Default is a no-op.
"""
return None | 0 | random_source |
def result_type(self) -> type[T]:
"""Get result type based on category."""
categories = {
"text": TextResult,
"images": ImagesResult,
"videos": VideosResult,
"news": NewsResult,
"books": BooksResult,
}
return categories[self... | Get result type based on category. | 1 | source_docstring |
def node_kind(node: dict) -> str:
"""Classify a graph node for Mermaid styling and table tags."""
label = str(node.get("label") or node.get("id") or "").lower()
source_file = str(node.get("source_file") or "").lower()
file_type = str(node.get("file_type") or "").lower()
node_type = str(node.get("nod... | def cmd_ext_install(args: argparse.Namespace) -> int:
"""``jarvis extension install <path-or-url>``."""
if not args.url_or_path:
print(" usage: jarvis extension install <path-or-url>")
return 1
source = args.url_or_path
target_root = get_jarvis_home() / "extensions"
target_root.mkdi... | 0 | random_source |
def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict:
"""Load the manifest from a previous run. Returns {} on any error."""
try:
return json.loads(Path(manifest_path).read_text(encoding="utf-8"))
except Exception:
return {} | Load the manifest from a previous run. Returns {} on any error. | 1 | source_docstring |
def __init__(self, glyphSet, scale: float = 0.01) -> None:
super().__init__(glyphSet)
self.opsset = OpsSet(initial_set=[])
self.scale = scale
self.min_x = self.min_y = float("inf")
self.max_x = self.max_y = -float("inf") | def header(label: str) -> None:
print()
print("=" * 60)
print(f" {label}")
print("=" * 60) | 0 | random_source |
async def delete_comment(self, comment_id: str) -> bool:
"""Delete a comment."""
try:
await self._make_request("DELETE", comment_id)
return True
except Exception as e:
logger.error("Failed to delete comment", error=str(e), comment_id=comment_id)
... | Get current rate limit information. | 0 | cross_docstring |
def from_openai_format(openai_messages: list[dict]) -> list[HistoryMessage]:
"""Parse OpenAI Chat Completions API messages into HistoryMessages."""
return [HistoryMessage.from_openai_dict(m) for m in openai_messages] | Convert HistoryMessages to simple role dicts for LLM calls. | 0 | cross_docstring |
def known_methods(self) -> list[str]:
return sorted(self._method_to_service.keys()) | def tablet(self) -> str:
"""Returns a tablet device user agent."""
matching = [a for a in self._agents if 'iPad' in a or ('Android' in a and 'Mobile' not in a)]
agent = random.choice(matching) if matching else self.custom(device_type="tablet")
self._update_stats(device_type="tablet")... | 0 | random_source |
def get_manager() -> ExtensionManager:
global _MANAGER_SINGLETON
if _MANAGER_SINGLETON is None:
_MANAGER_SINGLETON = ExtensionManager()
return _MANAGER_SINGLETON | function get_manager | 0.5 | source_name |
def __init__(self):
self._file_path = Path.home() / ".jarvis" / "trusted_folders.toml"
self._trusted: list[str] = []
self._untrusted: list[str] = []
self._session_trusted: list[str] = []
self._load() | function __init__ | 0.5 | source_name |
async def list_resource_templates(self) -> list[MCPResourceTemplateSpec]:
"""List resource templates from the MCP server."""
await self._ensure_active_loop()
if not self._initialized:
await self.connect()
if not self._session:
raise RuntimeError("MCP session... | Disconnect from all MCP servers | 0 | cross_docstring |
class GeneratedImage(Image):
"""
Represents an image generated by Google's AI image generator (e.g., ImageFX).
Attributes:
cookies (dict[str, str]): Cookies required for accessing the generated image URL,
typically from the GeminiClient/Chatbot instance.
"""
cookies: Dict[str, ... | Synchronous wrapper for the AsyncChatbot class.
This class provides a synchronous interface to interact with Google Gemini,
handling authentication, conversation management, and message sending.
Attributes:
loop (asyncio.AbstractEventLoop): Event loop for running async tasks.
secure_1psid (str): Authenticatio... | 0 | cross_docstring |
async def api_set_safety_profile(request: Request):
"""Set safety profile by ID."""
global _safety_state
try:
body = await request.json()
profile_id = body.get("profile_id", 3)
profile = next((p for p in SAFETY_PROFILES if p["id"] == profile_id), None)
if not profile:
... | function api_set_safety_profile | 0.5 | source_name |
def total_resources(self) -> int:
"""Get total number of cached resources."""
return sum(len(s.resources) for s in self._servers.values()) | Update cache for a server with fresh tool, resource, and prompt metadata. | 0 | cross_docstring |
def adjust_line_length(
cls,
line: List["Segment"],
length: int,
style: Optional[str] = None,
pad: bool = True,
) -> List["Segment"]:
"""Adjust a line to the given length.
Args:
line: List of segments.
length: Target length... | Control codes for terminal manipulation. | 0 | cross_docstring |
def test_returns_none_for_chat_stream(self):
# chat.stream is registered directly on the service
# registry, not via a handler.
from jarvis.core.web.server import _build_service_registry
reg = _build_service_registry()
assert _find_handler_cls(reg, "chat") is None | function test_returns_none_for_chat_stream | 0.5 | source_name |
def test_format_catalog_row_one_line(self):
row = format_catalog_row(get("postgres"))
assert "postgres" in row
assert "PostgreSQL" in row
assert "[db" in row
assert "JARVIS_MCP_PG_URL" in row # env requirement | function test_format_catalog_row_one_line | 0.5 | source_name |
def set_style(style):
"""Set the syntax highlighting style.
Args:
style: A Pygments Style class (e.g., SolarizedDark, LitStyle, CyberpunkStyle)
"""
global _current_style
_current_style = style | def __init__(
self,
top_left: tuple[float, float],
side_length: float,
border_radius: float = 0.1, # this is a percentage of the rectangle height or width
*args,
**kwargs,
) -> None:
self.side_length = side_length
super().__init__(
top... | 0 | random_source |
class Trace:
"""Complete trace information with all exception stacks."""
stacks: List[Stack] # List of exception stacks | Apply italic style to text. | 0 | cross_docstring |
class PublishMediaResponse(BaseModel):
"""Response from publishing media."""
id: str
status: str = "published" | Content publishing limit info. | 0 | cross_docstring |
class TestTraceAnalyzer:
"""Tests for trace analysis"""
@pytest.mark.asyncio
async def test_analyze_empty_sessions(self, tmp_path: Path):
"""Test analysis with no sessions"""
analyzer = TraceAnalyzer(sessions_dir=str(tmp_path))
metrics = await analyzer.analyze_sessions(limit=1)
... | def get_skills(self) -> dict[str, dict[str, Any]]:
"""Return all registered skills."""
return self._skills.copy() | 0 | random_source |
def get_collaborators(self) -> List[Dict[str, Any]]:
"""Get repository collaborators"""
url = f"{self.base_url}/collaborators"
return request(url) | Get repository pull requests
Args:
state: State of PRs to return (open/closed/all)
page: Page number
per_page: Items per page | 0 | cross_docstring |
def get_tool_config(self, tool_name: str) -> dict[str, Any] | None:
"""Get tool configuration."""
tool = self.tool_registry.get(tool_name)
if tool:
return {"name": tool.name, "description": tool.description}
return None | Handle /compress [topic] slash command.
Args:
focus_topic: Optional topic to focus compression on
Returns:
Dict with compression results | 0 | cross_docstring |
async def api_jarvis_update(background_tasks: BackgroundTasks) -> dict:
"""Kick off ``jarvis update`` in the background and return immediately."""
from jarvis.interface.update.install_method import detect_install_method
method = detect_install_method()
if method == "docker":
return {
... | async def test_deny() -> None:
header("TEST 4: Click 'Deny' (BOTTOM option) — or press Esc")
print("Click the BOTTOM line ('Deny'), or just press Esc.\n")
t0 = time.monotonic()
outcome = await nm.request_agent_permission(
title="Test 4 — Click 'Deny' (bottom)",
message="Click the BOTTOM ... | 0 | random_source |
class QuantizationMethod(TypedDict):
"""Type definition for quantization method descriptions."""
description: str | class QuantizationMethod | 0.5 | source_name |
async def close(self):
pass | function close | 0.5 | source_name |
def cmd_update_issue(args: argparse.Namespace) -> None:
inp: dict[str, Any] = {}
if args.title:
inp["title"] = args.title
if args.description:
inp["description"] = args.description
if args.priority is not None:
inp["priority"] = args.priority
if not inp:
sys.stderr.wr... | async def test_send_voice_wrong_format(patch_client, tmp_path):
mod = _import_tool_module("send_voice_bad", "media.py")
test_file = tmp_path / "voice.mp3"
test_file.write_bytes(b"ID3" + b"\x00" * 100)
result = await mod.send_voice(chat_id=123, file_path=str(test_file))
assert ".ogg" in result.lower(... | 0 | random_source |
class PocketTTS(KyutaiTTS):
"""
Backward compatibility alias for KyutaiTTS.
Use KyutaiTTS instead for new code.
"""
def __init__(self, *args, **kwargs):
"""Initialize PocketTTS (alias for KyutaiTTS)."""
super().__init__(*args, **kwargs)
self.default_model = "pocket-tts" | Convert text to speech using Kyutai TTS API.
Args:
text (str): The text to convert to speech
voice (str, optional): Voice to use. Defaults to model's default voice.
verbose (bool, optional): Print debug information. Defaults to False.
**kwargs: Additional parameters (model, response_format, etc.)
Retu... | 0 | cross_docstring |
async def test_get_stats_after_requests(limiter):
await limiter.acquire(wait=False)
await limiter.acquire(wait=False)
stats = limiter.get_stats()
assert stats["total_requests"] == 2
assert stats["window_current"] == 2 | function test_get_stats_after_requests | 0.5 | source_name |
def __init__(self, llm_provider, tool_registry, model=None, config_getter=None):
"""
Initialize the rubber duck agent
Args:
llm_provider: LLM provider instance
tool_registry: Tool registry instance
model: Model to use (defaults to same as parent if not sp... | def test_remove_tool():
"""Test 4: Tool removal."""
print("\n" + "=" * 60)
print("TEST 4: Tool removal")
print("=" * 60)
searcher = DynamicToolSearcher()
tools = get_sample_tools_dict()
for name, data in tools.items():
searcher.register_or_update_tool(name, data)
assert searche... | 0 | random_source |
def offload_if_needed(self, messages: list[MessageDict]) -> list[MessageDict]:
"""Check all tool-role messages and offload oversized ones to disk.
Args:
messages: Full message list (modified in-place and returned).
Returns:
The same list with large tool results repl... | Check all tool-role messages and offload oversized ones to disk.
Args:
messages: Full message list (modified in-place and returned).
Returns:
The same list with large tool results replaced by snippets. | 1 | source_docstring |
def update_typescript(version: str) -> None:
"""Update TypeScript SDK version."""
package_json = ROOT / "src" / "typescript" / "package.json"
if package_json.exists():
data = json.loads(package_json.read_text())
data["version"] = version
package_json.write_text(json.dumps(data, inden... | Update C++ SDK version. | 0 | cross_docstring |
def build_skill_prompt(user_input: str, skill: Any) -> str:
"""Build skill prompt."""
if skill and hasattr(skill, "content") and skill.content:
return f"{user_input}\n\n--- Skill Context ---\n{skill.content}"
return user_input | Build skill prompt. | 1 | source_docstring |
class ExtensionUnloaded(ExtensionEvent):
"""Emitted when an extension is unloaded"""
reason: str = "" | Base class for system-level events | 0 | cross_docstring |
class TurnEnded(TurnEvent):
"""Emitted when a turn completes with assistant message and tool results"""
tool_count: int = 0 | Emitted when a full message block is completed | 0 | cross_docstring |
def create(
self,
*,
model: str, # Not used by Writecream, for compatibility
messages: List[Dict[str, Any]],
max_tokens: Optional[int] = None, # Not used by Writecream
stream: bool = False,
temperature: Optional[float] = None, # Not used by Writecream
... | function create | 0.5 | source_name |
def __init__(
self,
*,
color_system: Optional[str] = "auto",
force_terminal: Optional[bool] = None,
no_color: bool = False,
tab_size: int = 8,
record: bool = False,
markup: bool = True,
emoji: bool = True,
highlight: bool = True,
... | Display a status message with optional spinner.
Args:
status: Status message to display.
spinner: Spinner animation type.
spinner_style: Style for the spinner.
speed: Animation speed.
refresh_per_second: Refresh rate.
Yields:
Context for the status display. | 0 | cross_docstring |
def add_file_snapshot(self, path: str, content: bytes | None) -> None:
"""Add a file snapshot to checkpoints - convenience method."""
if hasattr(self.rewind_manager, "add_snapshot"):
from jarvis.core.rewind import FileSnapshot
snapshot = FileSnapshot(path=path, content=conte... | Notifier callback to deliver heartbeat results in TUI. | 0 | cross_docstring |
async def call_tool(self, tool_name: str, arguments: dict[str, Any]) -> dict[str, Any]:
"""Call a tool on the MCP server"""
await self._ensure_active_loop()
if not self._initialized:
await self.connect()
if not self._session:
raise RuntimeError("MCP session ... | Get the number of available prompts | 0 | cross_docstring |
def on_start(self, hook: Callable[..., Any]) -> None:
"""Register a session-start hook — same as :meth:`ExtensionAPI.on_start`."""
self._api.on_start(hook)
self.log.debug("added on_start hook: %s", getattr(hook, "__name__", hook)) | def add_special_char(self, name: str, art_lines: List[str]) -> None:
"""
Add a special ASCII art character or design
:param name: Name of the special character
:param art_lines: List of art lines representing the character
"""
self.special_chars[name] = art_lines | 0 | random_source |
class ToolResultEvent(BaseEvent):
"""Tool result event."""
tool_name: str = ""
result: Any = None
tool_call_id: str = ""
tool_class: str = ""
error: str = ""
skipped: bool = False
skip_reason: str = ""
cancelled: bool = False
duration: float = 0.0 | class ToolResultEvent | 0.5 | source_name |
def get_tool_config(self, tool_name: str) -> dict[str, Any] | None:
"""Get tool configuration."""
tool = self.tool_registry.get(tool_name)
if tool:
return {"name": tool.name, "description": tool.description}
return None | Stub for teleport functionality. | 0 | cross_docstring |
async def test_allow_once_button_returns_allow_once(self):
"""mako's makoctl menu invokes the Button.on_pressed callback,
not the subprocess. We simulate that by making the mock's send()
invoke the matching Button's on_pressed.
"""
nm._set_permission_backend("mako_menu")
... | dunst caps at ~3 visible buttons; we don't silently drop
the user's options — we fall through to a numbered list. | 0 | cross_docstring |
async def cmd_bench(self, args: list[str]) -> None:
"""Benchmark skill performance.
Usage: jarvis bench skills [--max-samples <n>] [--seeds <n>]
"""
max_samples = 5
seeds = 42
for i, arg in enumerate(args):
if arg == "--max-samples" and i + 1 < len(args)... | async def execute(self, input_data: ToolInput) -> ToolOutput:
params = input_data.model_dump()
crash_text = params.get("crash_text", "").strip()
crash_type = params.get("crash_type", "auto").strip().lower()
binary_path = params.get("binary_path", "").strip()
if not crash_tex... | 0 | random_source |
def coerce_seed(value: Any) -> int:
"""Convert -1 or None to a fresh random seed; otherwise return int(value).
Accepts numeric -1 OR string "-1" (both treated as "randomize"). Other
parse failures raise TypeError/ValueError for the caller to surface.
"""
if value is None:
return random.rand... | Pretty key=value for log lines. | 0 | cross_docstring |
async def unban_user(chat_id: int, user_id: int) -> str:
"""
Unban a previously banned user from a group or channel by their user ID. They can rejoin if they have an invite link.
Args:
chat_id: ID of the group/channel
user_id: User ID to unban
"""
try:
chat = await client.ge... | function unban_user | 0.5 | source_name |
def test_split_camel_case(self):
assert split_identifier("handleMessage") == ["handlemessage", "handle", "message"] | def unsubscribe() -> None:
if handler in self._event_handlers:
self._event_handlers.remove(handler) | 0 | random_source |
def to_dict(self) -> dict:
"""Convert to dictionary for JSON serialization."""
d = asdict(self)
return {k: v for k, v in d.items() if v is not None} | Ensure a sessions row exists for the current session. | 0 | cross_docstring |
def make_title(text: str, *, y: float, color: tuple[float, float, float] = BLACK) -> Text:
return Text(
text,
position=(960, y),
font_size=100,
font_name=FONT_NAME,
stroke_style=StrokeStyle(color=color, width=4.0),
sketch_style=SKETCH,
) | function make_title | 0.5 | source_name |
class TestToolHelpers:
def test_tool_call_to_dict(self):
tc = ToolCall(id="c1", type="function", function={"name": "bash", "arguments": "{}"})
d = tc.to_dict()
assert d["id"] == "c1"
assert d["type"] == "function"
def test_create_openai_tool_call(self):
result = create_o... | class TestToolHelpers | 0.5 | source_name |
class STTProvider:
"""Abstract base for STT providers."""
slug: str = ""
display_name: str = ""
requires_api_key: bool = False
async def transcribe(self, request: STTRequest) -> STTResult:
"""Convert audio file → text."""
raise NotImplementedError
def describe(self) -> dict[st... | Abstract base for STT providers. | 1 | source_docstring |
async def close(self) -> None:
"""Close the provider session"""
raise NotImplementedError("Method needs to be implemented in subclass") | Get authentication token (optional for some providers) | 0 | cross_docstring |
async def inject_user_context(self, context: str) -> None:
"""Inject user context into agent."""
self.agent.update_context("user_context", context) | Refresh configuration. | 0 | cross_docstring |
class SystemEvent:
"""Base class for system-level events"""
timestamp: float | Emitted at the start of each LLM request cycle | 0 | cross_docstring |
class InvalidOptimizerError(WebscoutE):
"""
Exception raised when an invalid or unavailable optimizer is requested.
"""
pass | Exception raised when an invalid or unavailable optimizer is requested. | 1 | source_docstring |
def create(
self,
*,
model: str,
messages: List[Dict[str, str]],
max_tokens: Optional[int] = None,
stream: bool = False,
temperature: Optional[float] = None,
top_p: Optional[float] = None,
timeout: Optional[int] = None,
proxies: Optiona... | def test_reserved_jarvis_prefix_rejected(self):
reg = ServiceRegistry()
with pytest.raises(ValueError, match="reserved"):
reg.register_service(ServiceSpec(name="jarvis", version="0.1.0"))
with pytest.raises(ValueError, match="reserved"):
reg.register_service(ServiceSp... | 0 | random_source |
def test_approval_from_key_case_insensitive(self):
assert nm._approval_from_key("ALLOW_SESSION") is NotificationApproval.ALLOW_SESSION | def test_auto_discover_capabilities_default(self):
from jarvis.core.tools.mcp_adapter import MCPServerConfig
config = MCPServerConfig(name="test")
assert config.auto_discover_capabilities is True | 0 | random_source |
def detect_capabilities() -> dict[str, Any]:
"""Return what tools JARVIS can drive for computer-use."""
c = get_computer()
return {
"mouse_tool": c.mouse_tool[0] if c.mouse_tool else None,
"screenshot_tool": c.screenshot_tool,
"screen_size": {
"width": c.get_screen_size()... | Return what tools JARVIS can drive for computer-use. | 1 | source_docstring |
async def test_terminal_fallback_keyboard_interrupt_returns_deny(self):
with patch("jarvis.core.notification_manager._get_dn", return_value=None):
with patch("builtins.input", side_effect=KeyboardInterrupt):
result = await request_agent_permission("t", "m")
assert... | def map_dependency_file(path: str) -> list[dict[str, str]]:
"""Parse common dependency files and extract (package, version, ecosystem)."""
path_obj = Path(path)
deps: list[dict[str, str]] = []
if not path_obj.exists():
return deps
fname = path_obj.name
try:
if fname in ("requi... | 0 | random_source |
async def start(self):
"""Called when watcher starts. Silently initializes."""
# Suppress all terminal output - no logger.info or telegram notifications on startup
# This prevents interference with jarvis TUI
pass | Null logger that suppresses all output | 0 | cross_docstring |
def split_and_crop_lines(
cls,
segments: Iterable["Segment"],
length: int,
style: Optional[str] = None,
pad: bool = True,
include_new_lines: bool = True,
) -> Iterator[List["Segment"]]:
"""Split segments into lines and crop/pad to the given length.
... | function split_and_crop_lines | 0.5 | source_name |
def cmd_distance(args):
"""Calculate road distance and travel time between two places."""
origin_query = " ".join(args.origin)
destination_query = " ".join(args.to)
mode = args.mode.lower()
if mode not in OSRM_PROFILES:
error_exit(f"Invalid mode '{mode}'. Choose from: {', '.join(OSRM_PROFIL... | Return distance in metres between two lat/lon points (Haversine). | 0 | cross_docstring |
def to_openai_format(
messages: list[HistoryMessage],
system_prompt: str | None = None,
) -> list[dict]:
"""Convert HistoryMessage list to OpenAI Chat Completions API format."""
result: list[dict] = []
if system_prompt:
result.append({"role": "system", "content": system_prompt})
for msg ... | Execute a read SQL and return one row. | 0 | cross_docstring |
def end_session(self, reason: str = "normal") -> None:
"""Mark the current session as ended."""
db = self._get_db()
db.execute_write(
"UPDATE sessions SET ended_at = ?, end_reason = ? WHERE id = ?",
(time.time(), reason, self.session_id),
) | Ensure a sessions row exists for the current session. | 0 | cross_docstring |
class Handler(BaseRpcHandler):
"""Handles skill management RPC commands."""
params_models: ClassVar[dict[str, type[BaseModel]]] = {
"get_skill": GetSkillParams,
"activate_skill": ActivateSkillParams,
"deactivate_skill": DeactivateSkillParams,
}
result_models: ClassVar[dict[str, ... | def validate_media_url(cls, v, info):
"""Validate that at least one media URL is provided."""
# This validator will be called for each field individually
# We'll validate the combination in model_validator
return v | 0 | random_source |
class StaticAnimation(AnimationEvent):
"""
A static animation that keeps a drawable visible without any changes.
This is useful for holding a drawable in place while audio continues playing.
The drawable remains in its final state from previous animations.
Args:
start_time (float):... | A static animation that keeps a drawable visible without any changes.
This is useful for holding a drawable in place while audio continues playing.
The drawable remains in its final state from previous animations.
Args:
start_time (float): The starting time point of the static hold in seconds.
duration (float... | 1 | source_docstring |
class MCPToolResult(BaseModel):
"""MCP tool execution result."""
success: bool = Field(..., description="Whether the operation was successful")
data: Optional[Dict[str, Any]] = Field(None, description="Result data")
error: Optional[str] = Field(None, description="Error message if failed")
metadata:... | Request to publish media to Instagram. | 0 | cross_docstring |
async def pin_message(chat_id: int, message_id: int) -> str:
"""
Pin a message in a chat so it stays at the top for all members. Works in groups, channels, and supergroups. Requires admin or sufficient permissions.
"""
try:
entity = await client.get_entity(chat_id)
await client.pin_messa... | def test_partner_key_does_not_pollute_extra_data(self):
r = ComfyRunner(host="https://cloud.comfy.org", api_key="auth-key")
# No partner-key set → no extra_data should appear in submitted prompt
# (This is a static check; runtime check happens in submit())
assert r.partner_key is Non... | 0 | random_source |
def on_session_end(self) -> None:
"""Optional: called once per JARVIS session, on
shutdown. Default is a no-op.
"""
return None | Tools contributed by this plugin (read-only snapshot). | 0 | cross_docstring |
class Mojeek(BaseSearchEngine[TextResult]):
"""Mojeek search engine."""
name = "mojeek"
category = "text"
provider = "mojeek"
search_url = "https://www.mojeek.com/search"
search_method = "GET"
items_xpath = "//ul[contains(@class, 'results')]/li"
elements_xpath: Mapping[str, str] = {
... | Mojeek search engine. | 1 | source_docstring |
class Position:
"""A single paper-traded position."""
id: str
ticker: str
side: Side
shares: float
entry_price: float
stop_loss: float
take_profit: float
opened_at: float # unix ts
opened_at_iso: str
thesis: str = ""
confidence: float = 0.0
risk_score: float = 0.0
... | class SessionError(GeminiSDKError):
"""Raised when there's an error with a session."""
def __init__(
self,
message: str,
session_id: str | None = None,
details: dict[str, Any] | None = None,
):
details = details or {}
if session_id:
details["sessi... | 0 | random_source |
async def mute_chat(chat_id: int) -> str:
"""
Mute all notifications for a chat indefinitely. You will still receive messages but won't get push notifications.
"""
try:
from telethon.tl.types import InputPeerNotifySettings
peer = await client.get_entity(chat_id)
await client(
... | CRITICAL: Send a text message to any Telegram chat (DM, group, or channel) by chat ID. This is your primary reply tool — without it, messages never reach Telegram. Use <send_break> to split into multiple sequential messages. Use get_chats to find chat IDs.
Use <send_break> in message to split into multiple sequential m... | 0 | cross_docstring |
def iter_embedding_refs(workflow: dict) -> Iterator[tuple[str, str]]:
"""Yield (node_id, embedding_name) for every embedding mention in prompts."""
for node_id, node in iter_nodes(workflow):
inputs = node.get("inputs", {}) or {}
for field_name, val in inputs.items():
if field_name no... | Join paths, raising if the result escapes `base`.
Server-supplied filenames may contain `../` etc. This guards against
path-traversal attacks when downloading outputs. | 0 | cross_docstring |
def test_subfolder_match(self):
# Installed list has "subdir/model.safetensors", workflow asks "model.safetensors"
assert model_present("model.safetensors", {"subdir/model.safetensors"}) is True | function test_subfolder_match | 0.5 | source_name |
def resolve_audio_path(path: str) -> str:
resolved = Path(path).expanduser().resolve()
if not resolved.exists():
msg = f"Audio file does not exist: {path}"
raise FileNotFoundError(msg)
return str(resolved) | def fake_parent():
conn, _ = server.accept()
buf = b""
while b"\n" not in buf:
buf += conn.recv(65536)
request = json.loads(buf.decode())
# Echo a known response
assert request["tool"] == "read"
assert request["a... | 0 | random_source |
class TestBuiltinProfiles:
def test_default_has_knowledge_graph(self):
from jarvis.core.agents.builtin_profiles import BUILTIN_AGENTS
tools = BUILTIN_AGENTS["default"].overrides.get("tools", {})
assert "codebase_search" in tools
assert tools["codebase_search"]["permission"] == "alwa... | class TestBuiltinProfiles | 0.5 | source_name |
class RateLimitExceeded(InstagramAPIError):
"""Exception raised when rate limit is exceeded."""
pass | Validate the access token. | 0 | cross_docstring |
def trace_to_node(workflow: dict, link: list, *, max_hops: int = 8) -> str | None:
"""Follow a [node_id, slot] link, hopping through Reroute / Primitive nodes
if needed, to find the *upstream* node id that holds the actual value/input.
Bounded by both `max_hops` AND a visited-set to prevent infinite loops ... | Trace `negative` input of a sampler back to the source text encoder. | 0 | cross_docstring |
def models(self) -> SimpleModelList:
return SimpleModelList(type(self).AVAILABLE_MODELS) | function models | 0.5 | source_name |
def __init__(self, llm_provider, tool_registry, model=None, config_getter=None):
"""
Initialize the explore agent
Args:
llm_provider: LLM provider instance
tool_registry: Tool registry instance
model: Model to use (defaults to same as parent if not specif... | Initialize the explore agent
Args:
llm_provider: LLM provider instance
tool_registry: Tool registry instance
model: Model to use (defaults to same as parent if not specified)
config_getter: Function to get current configuration with profile overrides | 1 | source_docstring |
def test_all_aliases_resolve(self):
for slug in ("bwrap", "local", "hfspace", "hf-space", "opensandbox", "disabled"):
backend = get_backend(slug)
assert backend is None or isinstance(backend, SandboxBackend), slug | def make_eraser(objects_to_erase: list, *, start_time: float, duration: float = 1.2) -> None:
eraser = Eraser(
objects_to_erase=objects_to_erase,
drawable_cache=scene.drawable_cache,
glow_dot_hint={"color": (0.7, 0.7, 0.7), "radius": 15},
)
scene.add(SketchAnimation(start_time=start_... | 0 | random_source |
def telegram(data: dict[str, Any]) -> list[dict[str, Any]]:
items = []
if "items" in data:
for item in data["items"]:
text = item.get("text", "")[:300]
channel = item.get("channelTitle", item.get("channel", "Unknown"))
if text:
... | function telegram | 0.5 | source_name |
async def refresh_remote_tools_async(self) -> None:
"""Refresh remote tools (noop for now)."""
pass | Clear agent history. | 0 | cross_docstring |
async def spawn(
self,
command: str,
process: asyncio.subprocess.Process,
cwd: str | None = None,
) -> ProcessSession:
session = ProcessSession(
id=f"proc_{uuid.uuid4().hex[:12]}",
command=command,
process=process,
pid=proce... | function spawn | 0.5 | source_name |
async def execute(self, input_data: ToolInput) -> ToolOutput:
try:
broker = get_broker()
result = await asyncio.to_thread(broker.status)
return ToolOutput(
success=True,
result=json.dumps(result, default=str, indent=2),
)
... | function execute | 0.5 | source_name |
def test_invalid_yaml_raises(self) -> None:
text = "---\nname: [unclosed\n---\nbody"
with pytest.raises(ValueError):
parse_frontmatter(text) | function test_invalid_yaml_raises | 0.5 | source_name |
def get_function_definitions(self) -> list[dict[str, object]]:
"""Get function definitions for all allowed tools.
Returns:
List of function definition dictionaries
"""
return [tool.get_function_definition() for tool in self.get_tools().values()] | def draw_single_curve_with_randomization(
self,
opsset: OpsSet,
points: list[np.ndarray] | None = None,
offset: float = 1.0,
):
"""
Draw a single human style sketchy curve with random derivations
"""
if points is None:
points = self.poi... | 0 | random_source |
def tool(
self,
tool: Any = None,
*,
name: str | None = None,
description: str = "",
handler: Callable[..., Any] | None = None,
input_schema: dict[str, Any] | None = None,
tags: list[str] | None = None,
local: bool = False,
) -> None:
... | Register a keyboard shortcut — same as :meth:`ExtensionAPI.shortcut`. | 0 | cross_docstring |
def test_record_response_headers_bogus(limiter):
limiter.record_response_headers({"x-ratelimit-limit-requests": "not-a-number"}) | def test_tick_no_jobs(self):
async def _run():
scheduler = CronScheduler(config={"tick_interval": 1})
count = await scheduler.tick()
assert count == 0
asyncio.run(_run()) | 0 | random_source |
def answers(self, *args, **kwargs) -> List[Dict[str, str]]:
"""Instant answers not yet implemented for Brave."""
raise NotImplementedError("Brave instant answers not yet implemented") | def display_hermes_home() -> str:
"""Return a user-friendly ``~/``-shortened display string.
Mirrors ``hermes_constants.display_hermes_home()``."""
home = get_hermes_home()
try:
return "~/" + str(home.relative_to(Path.home()))
except ValueError:
retur... | 0 | random_source |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- -