repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
QwenPaw | src/qwenpaw/hooks/skill_env/skill_env_hook.py | .py | # -*- coding: utf-8 -*-
"""Skill environment override hooks.
Applies ``skill_config_env_overrides`` as a PRE_EXECUTE / FINALLY
hook pair.
"""
from __future__ import annotations
import logging
from ..base import LifecycleHook
from ...runtime.hooks import HookContext, HookResult
from ...runtime.phases import Phase
l... | 62 | 1,734 |
QwenPaw | src/qwenpaw/governance/audit.py | .py | # -*- coding: utf-8 -*-
"""AuditLog — Audit records for each assert_policy + audit call.
Storage: single-file SQLite (~/.qwenpaw/audit.db), global singleton.
- record() writes immediately, no in-memory buffer
- query() supports filtering by workspace / agent / tool / decision /
time range, with pagination
- purge() ... | 411 | 14,310 |
QwenPaw | src/qwenpaw/governance/policy.py | .py | # -*- coding: utf-8 -*-
"""GovernancePolicy — builtin_rules + user_rules two-layer policy engine.
- builtin_rules + user_rules two layers:
builtin_rules — system built-in protection (resource ask /
command deny), not modifiable by agent
user_rules — generated by user/approve, can be added or removed... | 1,676 | 63,763 |
QwenPaw | src/qwenpaw/governance/__init__.py | .py | # -*- coding: utf-8 -*-
"""Governance layer
Public surface:
ResourceGovernor — Core entry point (assert_policy / audit etc.)
GovernanceAction — Rule action (ALLOW / DENY / ASK / SANDBOX_FALLBACK)
GovernanceDecision — Decision result with action + reason + sandbox_config
PolicyGuardedTool — Tool wrap... | 21 | 625 |
QwenPaw | src/qwenpaw/governance/detectors.py | .py | # -*- coding: utf-8 -*-
"""Deep security detectors for GovernancePolicy Phase 1.
Extracted from the three tool-guard Guardians as pure functions:
- detect_sensitive_paths: FilePathToolGuardian logic
- detect_dangerous_patterns: RuleBasedToolGuardian logic
- detect_shell_evasion: ShellEvasionGuardian logic
These funct... | 806 | 27,605 |
QwenPaw | src/qwenpaw/governance/tool_adapter.py | .py | # -*- coding: utf-8 -*-
# pylint: disable=protected-access
"""PolicyGuardedTool — Governance policy-checked tool wrapper.
Replaces the GuardedFunctionTool. Each tool call goes through two layers:
1. check_permissions: pre-execution decision
2. __call__: actual execution — handles sandbox violation retry loop
"""
from... | 741 | 27,442 |
QwenPaw | src/qwenpaw/governance/generalize.py | .py | # -*- coding: utf-8 -*-
"""Rule generalization — widen an approved tool-call target via the LLM.
When a user approves a tool call, future *similar* calls should be
auto-approved without prompting again. Given the exact approved target
(e.g. ``"git status"``, ``"/ws/src/foo.py"``), the LLM is asked for a
conservative g... | 422 | 14,303 |
QwenPaw | src/qwenpaw/governance/tool_registry.py | .py | # -*- coding: utf-8 -*-
"""ToolRegistry — Single source of truth for tool metadata.
Each tool declares on registration:
- Type (file / network / shell / internal)
- Target parameter name (file_path / command / url …)
- Python function name → policy tool name mapping
Relationship with policy.yaml:
Tool... | 554 | 20,059 |
QwenPaw | src/qwenpaw/governance/resource_governor.py | .py | # -*- coding: utf-8 -*-
"""Resource Governor — Policy evaluation + audit logging +
sandbox config compilation.
Core responsibilities: policy evaluation, audit recording, dynamic rule
addition, sandbox config compilation.
"""
from __future__ import annotations
import hashlib
import logging
from pathlib import Path
fr... | 517 | 19,985 |
QwenPaw | src/qwenpaw/token_usage/turn_usage.py | .py | # -*- coding: utf-8 -*-
"""Per-turn token/context usage: compute, reconcile, persist."""
from __future__ import annotations
import logging
from typing import Any
from .model_wrapper import TokenRecordingModelWrapper
logger = logging.getLogger(__name__)
TURN_USAGE_META_KEY = "qwenpaw_turn_usage"
def fmt_tokens(n:... | 254 | 7,554 |
QwenPaw | src/qwenpaw/token_usage/storage.py | .py | # -*- coding: utf-8 -*-
"""File I/O for token usage data with atomic writes.
"""
import json
import logging
import os
from pathlib import Path
import aiofiles
logger = logging.getLogger(__name__)
async def load_data(path: Path) -> dict:
"""Load token usage data from *path*."""
if not path.exists():
... | 71 | 1,817 |
QwenPaw | src/qwenpaw/token_usage/manager.py | .py | # -*- coding: utf-8 -*-
"""Token usage manager — thin orchestrator.
"""
import logging
import threading
from datetime import date, timedelta
from pathlib import Path
from typing import Optional
from pydantic import BaseModel, Field
from ..constant import WORKING_DIR, TOKEN_USAGE_FILE
from .buffer import TokenUsageBu... | 313 | 10,349 |
QwenPaw | src/qwenpaw/token_usage/model_wrapper.py | .py | # -*- coding: utf-8 -*-
"""Model wrapper that records token usage from LLM responses."""
from datetime import date, datetime, timezone
from typing import Any, AsyncGenerator, Literal
from agentscope.model import ChatModelBase
from agentscope.model._model_response import ChatResponse
from agentscope.model._model_usage... | 144 | 5,614 |
QwenPaw | src/qwenpaw/token_usage/__init__.py | .py | # -*- coding: utf-8 -*-
"""Token usage tracking for LLM API calls."""
from .buffer import _UsageEvent
from .manager import (
TokenUsageByModel,
TokenUsageRecord,
TokenUsageStats,
TokenUsageSummary,
get_token_usage_manager,
)
from .model_wrapper import TokenRecordingModelWrapper
from .turn_usage imp... | 31 | 660 |
QwenPaw | src/qwenpaw/token_usage/buffer.py | .py | # -*- coding: utf-8 -*-
"""In-memory write buffer with async producer-consumer for token usage.
"""
import asyncio
import copy
import logging
from pathlib import Path
from typing import NamedTuple, Optional
from .storage import load_data, save_data_sync
logger = logging.getLogger(__name__)
_DEFAULT_FLUSH_INTERVAL =... | 219 | 7,354 |
QwenPaw | src/qwenpaw/loop/catalog.py | .py | # -*- coding: utf-8 -*-
"""Built-in gate catalog for user-editable loop modes."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Callable, Literal, Type
from pydantic import BaseModel, ConfigDict, Field, model_validator
from ..config.config import DoomLoopConfig, DoomLoo... | 294 | 9,853 |
QwenPaw | src/qwenpaw/loop/__init__.py | .py | # -*- coding: utf-8 -*-
"""Loop engineering infrastructure package.
Core architecture:
StopHandler + StopGate (in gates/ sub-package)
├── LoopGate — session-safe base for loop plugins
├── DoomLoopGate — multi-stage repetition detection
├── RubricGate — rubric-based evaluation (GoalMode)
├─... | 38 | 901 |
QwenPaw | src/qwenpaw/loop/compiler.py | .py | # -*- coding: utf-8 -*-
"""Compile declarative custom loop modes into stop handlers."""
from __future__ import annotations
from ..config.config import CustomLoopModeConfig
from .catalog import GateCatalog, get_gate_catalog
from .gates.configured import ConfiguredGate
from .gates.handler import StopHandler
def compil... | 45 | 1,267 |
QwenPaw | src/qwenpaw/loop/gates/configured.py | .py | # -*- coding: utf-8 -*-
"""Order adapter for gates in declarative loop modes."""
from __future__ import annotations
from typing import Any
from .base import StopGate, StopHandlerResult
class ConfiguredGate(StopGate):
"""Bind one built-in gate to user-defined identity and order."""
def __init__(
sel... | 50 | 1,211 |
QwenPaw | src/qwenpaw/loop/gates/runner.py | .py | # -*- coding: utf-8 -*-
"""Run registered stop handlers and return result.
Decouples stop handler execution logic from the agent class.
"""
from __future__ import annotations
import logging
from typing import Any
from .base import StopAction, StopHandlerResult
logger = logging.getLogger(__name__)
def _registratio... | 216 | 6,217 |
QwenPaw | src/qwenpaw/loop/gates/completion.py | .py | # -*- coding: utf-8 -*-
"""Agent-native completion rubric gate."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from ...constant import (
QWENPAW_MESSAGE_TAG_KEY,
RUBRIC_EVALUATION_MESSAGE_TAG,
)
from .base import StopAction, StopHandlerResult
from .loop_gate imp... | 146 | 4,704 |
QwenPaw | src/qwenpaw/loop/gates/__init__.py | .py | # -*- coding: utf-8 -*-
"""Gates sub-package for the loop stop handler system.
Public API:
StopAction, StopGate, LoopGate, FileLoopGate,
IterationGate, BudgetGate, DoomLoopGate,
StopHandler, StopHandlerResult, StopHandlerRegistration,
RubricStrategy, GoalStatusRubric, RubricVerdict,
RubricEvaluatio... | 62 | 1,561 |
QwenPaw | src/qwenpaw/loop/gates/loop_gate.py | .py | # -*- coding: utf-8 -*-
"""LoopGate — generic session-safe base for stateful gates.
Hierarchy:
StopGate (ABC)
└── LoopGate (ABC) ← session isolation only
├── FileLoopGate ← file state + iterations
│ ├── RalphGate, UltraworkGate, ...
├── IterationGate
├── BudgetGate
... | 90 | 2,370 |
QwenPaw | src/qwenpaw/loop/gates/file_loop_gate.py | .py | # -*- coding: utf-8 -*-
"""FileLoopGate — file-state + iteration loop base.
For plugins that track completion via state files on disk.
Hierarchy:
LoopGate (session isolation)
└── FileLoopGate (file state + iteration cap)
├── RalphGate
├── UltraworkGate
└── ...
Subclasses implem... | 128 | 3,508 |
QwenPaw | src/qwenpaw/loop/gates/rubric.py | .py | # -*- coding: utf-8 -*-
"""Rubric evaluation strategies for loop completion.
Architecture:
RubricStrategy (ABC)
├── DefaultRubric — always SATISFIED (no rubric)
├── GoalStatusRubric — checks session.active
└── SubAgentRubric — placeholder for subagent eval
"""
from __future__ import annotations... | 248 | 6,262 |
QwenPaw | src/qwenpaw/loop/gates/limits.py | .py | # -*- coding: utf-8 -*-
"""Built-in resource limit gates for custom loop modes."""
from __future__ import annotations
import time
from collections import Counter
from dataclasses import dataclass, field
from typing import Any
from .base import StopAction, StopHandlerResult
from .loop_gate import LoopGate
def _bypas... | 242 | 7,367 |
QwenPaw | src/qwenpaw/loop/gates/iteration.py | .py | # -*- coding: utf-8 -*-
"""IterationGate — universal iteration limiter.
Tracks per-session iteration count. Returns TERMINATE when
``max_iterations`` is reached.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import Any, Optional
from .base import StopAction, Sto... | 95 | 2,352 |
QwenPaw | src/qwenpaw/loop/gates/handler.py | .py | # -*- coding: utf-8 -*-
"""Universal StopHandler with composable gates.
Architecture:
StopHandler holds an ordered list of StopGate.
Gates are checked in priority order (lower first).
TERMINATE -> agent stops immediately.
INTERRUPT_AND_CONTINUE -> call gate.build_continuation()
to get the messa... | 181 | 5,642 |
QwenPaw | src/qwenpaw/loop/gates/base.py | .py | # -*- coding: utf-8 -*-
"""Gate abstraction for the universal stop handler.
Defines the StopGate ABC, StopAction enum, and
StopHandlerResult dataclass.
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
from typing import Any, Callable, O... | 137 | 3,752 |
QwenPaw | src/qwenpaw/loop/gates/budget.py | .py | # -*- coding: utf-8 -*-
"""BudgetGate — universal token budget limiter.
Tracks per-session token usage. Returns TERMINATE when
``max_tokens`` is exceeded.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import Any, Optional
from .base import StopAction, StopHandler... | 83 | 2,037 |
QwenPaw | src/qwenpaw/loop/gates/doom_loop.py | .py | # -*- coding: utf-8 -*-
"""DoomLoopGate: session-safe doom loop detection.
Inherits LoopGate for per-session state isolation.
Includes inline sliding-window similarity detection.
"""
from __future__ import annotations
import hashlib
import json
import logging
from collections import deque
from dataclasses import data... | 288 | 7,984 |
QwenPaw | src/qwenpaw/local_models/manager.py | .py | # -*- coding: utf-8 -*-
"""Facade for local llama.cpp and model download management."""
from __future__ import annotations
import asyncio
import json
import logging
from typing import Any
from pydantic import BaseModel, Field, ValidationError
from ..constant import DEFAULT_LOCAL_PROVIDER_DIR
from .llamacpp import ... | 244 | 9,135 |
QwenPaw | src/qwenpaw/local_models/__init__.py | .py | # -*- coding: utf-8 -*-
"""Local model management and inference."""
from .manager import LocalModelManager
from .manager import LocalModelConfig
from .model_manager import ModelManager, LocalModelInfo, DownloadSource
from .llamacpp import LlamaCppBackend
__all__ = [
"DownloadSource",
"LocalModelInfo",
"Lo... | 17 | 407 |
QwenPaw | src/qwenpaw/local_models/tag_parser.py | .py | # -*- coding: utf-8 -*-
"""Parse special tags from model-generated text.
Handles ``<think>...</think>`` (reasoning) and
``<tool_call>...</tool_call>`` (function calling) tags that local models
like Qwen3-Instruct embed in their raw text output.
"""
from __future__ import annotations
import json
import logging
import... | 374 | 11,472 |
QwenPaw | src/qwenpaw/local_models/llamacpp.py | .py | # -*- coding: utf-8 -*-
from __future__ import annotations
import atexit
import asyncio
import logging
import multiprocessing as mp
import shutil
import socket
import tempfile
import uuid
from contextlib import contextmanager, suppress
from pathlib import Path
from typing import Any, Iterator, Optional
import httpx
f... | 936 | 32,287 |
QwenPaw | src/qwenpaw/local_models/download_manager.py | .py | # -*- coding: utf-8 -*-
"""Shared download state types and progress tracking helpers."""
from __future__ import annotations
import logging
import threading
import time
from contextlib import suppress
from dataclasses import asdict, dataclass, replace
from enum import Enum
from queue import Empty
from typing import An... | 599 | 18,567 |
QwenPaw | src/qwenpaw/local_models/model_manager.py | .py | # -*- coding: utf-8 -*-
"""Class-based local model downloader."""
from __future__ import annotations
import contextlib
import importlib
import logging
import multiprocessing as mp
import os
import shutil
import uuid
from pathlib import Path
from queue import Empty
from typing import Any, Optional
from enum import Enu... | 655 | 22,079 |
QwenPaw | src/qwenpaw/tool_calls/_coordinator.py | .py | # -*- coding: utf-8 -*-
"""ToolCoordinator — single owner of all in-flight tool calls."""
from __future__ import annotations
import asyncio
import logging
import time
from collections import OrderedDict
from dataclasses import dataclass
from typing import Any, AsyncGenerator, Awaitable, Callable
from agentscope.mess... | 1,016 | 36,616 |
QwenPaw | src/qwenpaw/tool_calls/_hint.py | .py | # -*- coding: utf-8 -*-
"""Construct hint messages for completed background tool calls."""
from __future__ import annotations
from typing import Any
from agentscope.message import Msg, TextBlock
def make_offload_hint_msg(entry: Any) -> Any:
"""Construct a hint Msg for a completed offloaded tool call.
The ... | 37 | 1,175 |
QwenPaw | src/qwenpaw/tool_calls/_ctxvars.py | .py | # -*- coding: utf-8 -*-
"""ContextVar for tool-internal access to ToolCallContext."""
from __future__ import annotations
from contextvars import ContextVar
from ._context import ToolCallContext
_current: ContextVar[ToolCallContext | None] = ContextVar(
"current_tool_call_context",
default=None,
)
def set_c... | 25 | 573 |
QwenPaw | src/qwenpaw/tool_calls/_stream.py | .py | # -*- coding: utf-8 -*-
"""Fan-out notifier for live tool output subscribers."""
from __future__ import annotations
import asyncio
from dataclasses import dataclass
from typing import Any, AsyncIterator
_SENTINEL = object()
@dataclass
class ToolStream:
"""Pure fan-out notifier. Holds no chunk storage of its own... | 71 | 1,980 |
QwenPaw | src/qwenpaw/tool_calls/_hooks.py | .py | # -*- coding: utf-8 -*-
"""Per-tool before/after hooks and timeout metadata."""
from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import Any, Awaitable, Callable
from ._context import ToolCallContext
logger = logging.getLogger(__name__)
BeforeHook = Callable[
[dict... | 78 | 2,407 |
QwenPaw | src/qwenpaw/tool_calls/__init__.py | .py | # -*- coding: utf-8 -*-
"""Tool call lifecycle management for QwenPaw."""
from ._context import CancelReason, OffloadReason, ToolCallContext
from ._coordinator import ToolCoordinator
from ._ctxvars import get_call_context, reset_call_context, set_call_context
from ._entry import ToolCallEntry, ToolCallStatus
from ._ho... | 40 | 1,106 |
QwenPaw | src/qwenpaw/tool_calls/_timeout_helper.py | .py | # -*- coding: utf-8 -*-
"""Cooperative timeout helpers for built-in tools."""
from __future__ import annotations
import asyncio
import logging
from typing import Any
from ._ctxvars import get_call_context
logger = logging.getLogger(__name__)
# Foreground offload window as a fraction of the resolved tool timeout so
... | 155 | 5,059 |
QwenPaw | src/qwenpaw/tool_calls/_entry.py | .py | # -*- coding: utf-8 -*-
"""Single-owner state for one in-flight tool call."""
from __future__ import annotations
import asyncio
from dataclasses import dataclass
from enum import StrEnum
from typing import Any
from ._context import ToolCallContext
from ._stream import ToolStream
class ToolCallStatus(StrEnum):
... | 32 | 733 |
QwenPaw | src/qwenpaw/tool_calls/_middleware.py | .py | # -*- coding: utf-8 -*-
"""on_acting middleware delegating tool execution to ToolCoordinator."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, AsyncGenerator, Callable
from agentscope.middleware import MiddlewareBase
if TYPE_CHECKING:
from agentscope.agent import Agent... | 57 | 1,896 |
QwenPaw | src/qwenpaw/tool_calls/_context.py | .py | # -*- coding: utf-8 -*-
"""Per-call runtime handle for tool execution lifecycle."""
from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
from enum import StrEnum
from typing import Any
class CancelReason(StrEnum):
USER = "user"
TIMEOUT = "timeout"
AGENT = "agent"
... | 59 | 1,438 |
QwenPaw | src/qwenpaw/services/project_directory.py | .py | # -*- coding: utf-8 -*-
"""Resolve the project directory independently from agent workspace state."""
from __future__ import annotations
from pathlib import Path
from typing import Any
def normalize_project_dir(value: str | Path) -> Path:
"""Normalize one configured project directory for the current platform.""... | 46 | 1,612 |
QwenPaw | src/qwenpaw/services/workspace_files.py | .py | # -*- coding: utf-8 -*-
"""Safe, bounded filesystem primitives for the unified Files workspace."""
from __future__ import annotations
import base64
import json
import os
import secrets
import stat
import threading
from datetime import datetime, timezone
from pathlib import Path, PurePosixPath
from typing import Any
... | 385 | 11,414 |
QwenPaw | src/qwenpaw/services/workspace_manager/workspace_manager.py | .py | # -*- coding: utf-8 -*-
"""Per-workspace workspace + sandbox manager (interface only).
The concrete implementation is provided by a separate workstream.
This module defines the lifecycle contract (``start`` / ``stop``)
and the relationship between ``WorkspaceManager`` and ``Sandbox``.
``WorkspaceManager`` is per-work... | 60 | 1,682 |
QwenPaw | src/qwenpaw/services/workspace_manager/__init__.py | .py | # -*- coding: utf-8 -*-
"""WorkspaceManager + Sandbox — per-workspace resource boundary management.
Concrete implementations are provided by a separate workstream.
This package defines the interface contracts only.
"""
from .sandbox import Sandbox, SandboxViolationError
from .workspace_manager import WorkspaceManager... | 12 | 391 |
QwenPaw | src/qwenpaw/services/workspace_manager/sandbox.py | .py | # -*- coding: utf-8 -*-
"""Lightweight resource-boundary sandbox (interface only).
The concrete implementation is provided by a separate workstream.
This module defines the contracts that tool execution code programs
against — ``check_path`` / ``check_tool`` raise
:class:`SandboxViolationError` when a tool call violat... | 85 | 2,614 |
QwenPaw | src/qwenpaw/observability/langfuse.py | .py | # -*- coding: utf-8 -*-
"""Langfuse trace context for QwenPaw agent turns.
This module is intentionally optional: QwenPaw does not depend on langfuse at
install time, so every helper becomes a no-op when Langfuse is unavailable.
"""
from __future__ import annotations
import importlib
import importlib.util
import logg... | 238 | 6,884 |
QwenPaw | src/qwenpaw/observability/__init__.py | .py | # -*- coding: utf-8 -*-
"""Observability helpers."""
| 3 | 53 |
QwenPaw | src/qwenpaw/pawapp/app.py | .py | # -*- coding: utf-8 -*-
"""PawApp class — Developer-facing SDK entry point.
Wraps PluginApi under the hood. Provides decorator sugar for:
- ``@app.route(path)`` — register HTTP route
- ``@app.tool(name, desc)`` — register agent tool
- ``@app.command(name, desc)`` — register /slash command
- ``@app.hook(phase)`` — regi... | 321 | 11,116 |
QwenPaw | src/qwenpaw/pawapp/__init__.py | .py | # -*- coding: utf-8 -*-
# src/qwenpaw/pawapp/__init__.py
"""PawApp SDK v2 — Thin wrapper over the QwenPaw Plugin system.
PawApp = a Plugin that has both frontend + backend entries and declares
``meta.pawapp`` fields in its manifest. The SDK provides:
- ``PawApp`` class (wraps PluginApi, exposes decorators)
- ``get_ct... | 18 | 588 |
QwenPaw | src/qwenpaw/pawapp/deps.py | .py | # -*- coding: utf-8 -*-
"""get_ctx — FastAPI dependency that creates PawAppContext per request.
Usage in Router mode:
from qwenpaw.pawapp import get_ctx
from fastapi import Depends
@router.get("/projects")
async def list_projects(ctx=Depends(get_ctx)):
return await ctx.storage.get("projects", ... | 108 | 3,313 |
QwenPaw | src/qwenpaw/pawapp/context.py | .py | # -*- coding: utf-8 -*-
# pylint: disable=too-many-branches, too-many-nested-blocks
"""PawAppContext — The ``ctx`` object that PawApp developers interact with.
Provides access to QwenPaw capabilities via thin delegation:
- ctx.chat() / ctx.chat_stream() → Workspace.stream_query()
- ctx.storage.get/set/search → SafeJSO... | 609 | 20,284 |
QwenPaw | src/qwenpaw/pawapp/task.py | .py | # -*- coding: utf-8 -*-
"""TaskManager + SSEChannel — Long-running task infrastructure.
Enables ``ctx.ui.push()`` to send realtime events to the frontend,
and ``paw.api.task()`` to subscribe to those events via EventSource.
Backend flow:
task_id = await task_manager.create_task(app_id, handler, ctx, params)
#... | 208 | 6,206 |
QwenPaw | src/qwenpaw/drivers/approval.py | .py | # -*- coding: utf-8 -*-
"""Driver approval boundary contracts."""
from __future__ import annotations
from typing import Protocol
from .policy import DriverInvocationContext
class ApprovalGate(Protocol):
"""Application-provided gate for Driver policy approvals.
Driver core owns policy evaluation, but it do... | 24 | 679 |
QwenPaw | src/qwenpaw/drivers/errors.py | .py | # -*- coding: utf-8 -*-
"""Driver subsystem errors."""
from __future__ import annotations
from typing import Any
from ..exceptions import (
AgentRuntimeErrorException,
AppBaseException,
ConfigurationException,
)
class DriverError(AppBaseException):
"""Base class for Driver subsystem errors."""
cl... | 128 | 3,711 |
QwenPaw | src/qwenpaw/drivers/contracts.py | .py | # -*- coding: utf-8 -*-
"""Driver card contracts and validation."""
from __future__ import annotations
from dataclasses import dataclass, field, replace
from typing import Any
from .constants import (
CREDENTIAL_KIND_NONE,
PRINCIPAL_SUBJECT_USER,
)
from .errors import DriverCardError
from .policy_types impor... | 325 | 10,926 |
QwenPaw | src/qwenpaw/drivers/storage.py | .py | # -*- coding: utf-8 -*-
"""YAML storage helpers for DriverCard files."""
from __future__ import annotations
import asyncio
import logging
import os
import tempfile
from dataclasses import asdict
from pathlib import Path
from typing import Any, cast
import yaml
from .constants import (
POLICY_EFFECT_ASK,
POL... | 476 | 14,835 |
QwenPaw | src/qwenpaw/drivers/manager.py | .py | # -*- coding: utf-8 -*-
"""Driver manager and lifecycle owner."""
from __future__ import annotations
import asyncio
import logging
from collections.abc import Callable, Iterable
from pathlib import Path
from .approval import ApprovalGate
from .capabilities import (
DriverCapability,
DriverInvocation,
Dri... | 715 | 25,684 |
QwenPaw | src/qwenpaw/drivers/policy.py | .py | # -*- coding: utf-8 -*-
"""Access policy evaluation for Drivers."""
from __future__ import annotations
import logging
from dataclasses import dataclass, field
from datetime import datetime, time, timezone
from typing import Any
from .constants import (
DRIVER_OPERATION_INVOKE,
POLICY_EFFECT_ALLOW,
POLICY... | 328 | 9,690 |
QwenPaw | src/qwenpaw/drivers/__init__.py | .py | # -*- coding: utf-8 -*-
"""Agent OS Driver subsystem."""
from .handler import DriverHandler
from .contracts import (
CredentialRef,
DriverCard,
DriverPolicy,
PolicyPrincipal,
PolicyRule,
PolicyTarget,
)
from .manager import DriverManager
__all__ = [
"CredentialRef",
"DriverCard",
"... | 25 | 440 |
QwenPaw | src/qwenpaw/drivers/constants.py | .py | # -*- coding: utf-8 -*-
"""Shared Driver string constants."""
from __future__ import annotations
from typing import Final, Literal
CREDENTIAL_ALIAS_DEFAULT: Final = "default"
CREDENTIAL_ALIAS_STATIC: Final = "static"
CREDENTIAL_ALIAS_OAUTH: Final = "oauth"
CREDENTIAL_KIND_NONE: Final = "none"
CREDENTIAL_KIND_STATIC... | 43 | 1,307 |
QwenPaw | src/qwenpaw/drivers/policy_types.py | .py | # -*- coding: utf-8 -*-
"""Driver policy data types and coercion helpers."""
from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass, field
from typing import Any, Literal, TypeAlias, cast, get_args
from .capabilities import CapabilityKind
from .constants import (
... | 223 | 6,687 |
QwenPaw | src/qwenpaw/drivers/capabilities.py | .py | # -*- coding: utf-8 -*-
"""Driver runtime capability contracts."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Literal
from urllib.parse import quote, unquote, urlsplit
# Keep the concrete kind set aligned with implemented Driver protocols. MCP
# currently exp... | 149 | 4,052 |
QwenPaw | src/qwenpaw/drivers/time.py | .py | # -*- coding: utf-8 -*-
"""Driver-local time helpers for policy evaluation."""
from __future__ import annotations
import logging
from datetime import datetime, timezone
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from ..config import load_config
from ..config.timezone import normalize_tz
logger = logging.g... | 35 | 1,152 |
QwenPaw | src/qwenpaw/drivers/handler.py | .py | # -*- coding: utf-8 -*-
"""DriverHandler template method base class."""
from __future__ import annotations
import logging
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any
from .approval import ApprovalGate
from .capabilities import (
DriverCapability,
DriverInvocation,
DriverInvo... | 242 | 7,647 |
QwenPaw | src/qwenpaw/drivers/credentials/types.py | .py | # -*- coding: utf-8 -*-
"""Runtime credential value types."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, ClassVar
def _redact_mapping(values: dict[str, Any]) -> dict[str, str]:
return {str(key): "***" for key in values}
@dataclass(frozen=True)
class Cre... | 61 | 1,632 |
QwenPaw | src/qwenpaw/drivers/credentials/bindings.py | .py | # -*- coding: utf-8 -*-
"""Credential-to-runtime binding helpers for Driver handlers."""
from __future__ import annotations
import base64
import logging
from typing import Any
from ..constants import (
CREDENTIAL_ALIAS_DEFAULT,
CREDENTIAL_ALIAS_OAUTH,
CREDENTIAL_ALIAS_STATIC,
)
from .providers import Cre... | 165 | 5,171 |
QwenPaw | src/qwenpaw/drivers/credentials/store.py | .py | # -*- coding: utf-8 -*-
"""Per-workspace YAML credential store."""
from __future__ import annotations
import asyncio
import os
import tempfile
import threading
from pathlib import Path
from typing import Any
import yaml
from .types import CredentialRecord
from ..errors import CredentialNotFoundError, DriverCardErro... | 225 | 8,303 |
QwenPaw | src/qwenpaw/drivers/credentials/__init__.py | .py | # -*- coding: utf-8 -*-
"""Driver credential helpers."""
from .providers import (
CredentialProvider,
build_provider,
)
from .store import AsyncCredentialStore
from .types import (
CredentialRecord,
ResolvedCredential,
)
__all__ = [
"CredentialProvider",
"CredentialRecord",
"AsyncCredentia... | 21 | 379 |
QwenPaw | src/qwenpaw/drivers/credentials/providers.py | .py | # -*- coding: utf-8 -*-
"""CredentialProvider strategies and factory."""
from __future__ import annotations
import asyncio
import base64
import hashlib
import hmac
import time
from abc import ABC, abstractmethod
from collections.abc import Callable
from typing import Any, Protocol
import httpx
from .store import As... | 358 | 11,456 |
QwenPaw | src/qwenpaw/drivers/handlers/mcp.py | .py | # -*- coding: utf-8 -*-
"""MCP Driver handler."""
from __future__ import annotations
import asyncio
import logging
import re
import time
from typing import Any
from ..capabilities import (
CapabilityExposure,
DriverCapability,
DriverInvocation,
DriverInvocationResult,
format_capability_id,
pa... | 436 | 14,507 |
QwenPaw | src/qwenpaw/drivers/handlers/mcp_stateful_client.py | .py | # -*- coding: utf-8 -*-
"""MCP stateful clients with proper cross-task lifecycle management.
This module provides drop-in replacements for AgentScope's MCP clients
that solve the CPU leak issue caused by cross-task context manager exits.
The issue occurs when using AgentScope's StatefulClientBase in uvicorn/FastAPI:
... | 855 | 33,637 |
QwenPaw | src/qwenpaw/drivers/handlers/__init__.py | .py | # -*- coding: utf-8 -*-
"""Driver handler implementations."""
from .mcp import MCPDriverHandler
__all__ = ["MCPDriverHandler"]
| 7 | 129 |
QwenPaw | src/qwenpaw/drivers/adapters/env_ref.py | .py | # -*- coding: utf-8 -*-
"""Parse ${VAR} environment references embedded in legacy MCP values.
Legacy ``agent.json`` MCP clients may embed process-environment references in
header/env values (e.g. ``Authorization: "Bearer ${API_KEY}"``). The Driver
model represents such a reference structurally as an ``env:`` credentia... | 59 | 2,006 |
QwenPaw | src/qwenpaw/drivers/adapters/__init__.py | .py | # -*- coding: utf-8 -*-
"""Driver config adapters."""
__all__: list[str] = []
| 5 | 79 |
QwenPaw | src/qwenpaw/drivers/adapters/mcp_card_builder.py | .py | # -*- coding: utf-8 -*-
"""Build DriverCard and CredentialRecord objects for Console MCP clients."""
from __future__ import annotations
import time
from dataclasses import replace
from typing import Any
from .mcp_binding import (
binding_plain_keys,
binding_to_response,
classify_mcp_binding,
normaliz... | 379 | 12,643 |
QwenPaw | src/qwenpaw/drivers/adapters/mcp_legacy_config.py | .py | # -*- coding: utf-8 -*-
"""Legacy agent.json MCP migration helpers."""
from __future__ import annotations
import asyncio
import time
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any
import yaml
from .env_ref import env_ref
from .mcp_console import (
mcp_credential... | 585 | 18,352 |
QwenPaw | src/qwenpaw/drivers/adapters/agentscope_tool.py | .py | # -*- coding: utf-8 -*-
"""AgentScope runtime adapter for Driver capabilities.
Driver owns capability discovery and policy execution. This module is the
thin boundary that turns those protocol-neutral capabilities into
AgentScope ``ToolBase`` instances for the agent runtime.
"""
from __future__ import annotations
i... | 222 | 6,618 |
QwenPaw | src/qwenpaw/drivers/adapters/mcp_console.py | .py | # -*- coding: utf-8 -*-
"""Console MCP adapter compatibility facade."""
from __future__ import annotations
from .mcp_binding import (
EnvRefPlan,
binding_plain_keys,
binding_to_response,
classify_mcp_binding,
mask_mcp_secret_value,
normalize_secret_key,
plan_env_ref_bindings,
restore_m... | 53 | 1,339 |
QwenPaw | src/qwenpaw/drivers/adapters/mcp_binding.py | .py | # -*- coding: utf-8 -*-
"""MCP env/header binding classification and presentation helpers."""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import Any
from .env_ref import env_alias, parse_env_template
from ..credentials.types import CredentialRecord
_SAFE_KEY_PAT... | 261 | 8,304 |
QwenPaw | src/qwenpaw/config/utils.py | .py | # -*- coding: utf-8 -*-
from __future__ import annotations
import json
import logging
import os
import plistlib
import shlex
import shutil
import socket
import subprocess
import sys
import threading
import uuid
from pathlib import Path
from typing import Any, Optional, Tuple
from json_repair import repair_json
from ... | 925 | 30,213 |
QwenPaw | src/qwenpaw/config/timezone.py | .py | # -*- coding: utf-8 -*-
"""Detect the system IANA timezone.
Kept in its own module to avoid circular imports between config.py and
utils.py. Uses only the standard library; always returns a valid string
(falls back to ``"UTC"``).
"""
from __future__ import annotations
import logging
import os
from datetime import d... | 257 | 7,808 |
QwenPaw | src/qwenpaw/config/__init__.py | .py | # -*- coding: utf-8 -*-
from .config import (
Config,
ChannelConfig,
ChannelConfigUnion,
AgentsRunningConfig,
FileGuardConfig,
HeartbeatConfig,
SecurityConfig,
ToolGuardConfig,
ToolGuardRuleConfig,
ModelSlotConfig,
ActiveModelsInfo,
ACPConfig,
ACPAgentConfig,
Visu... | 59 | 1,326 |
QwenPaw | src/qwenpaw/config/context.py | .py | # -*- coding: utf-8 -*-
"""Context variable for agent workspace directory.
This module provides a context variable to pass the agent's workspace
directory to tool functions, allowing them to resolve relative paths
correctly in a multi-agent environment.
"""
from __future__ import annotations
from contextvars import C... | 208 | 5,737 |
QwenPaw | src/qwenpaw/config/config.py | .py | # -*- coding: utf-8 -*-
from __future__ import annotations
import importlib
import json
import logging
import re
import threading
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
List,
Literal,
Optional,
Set,
Tuple,
Union,
)
from apscheduler.triggers.cron import C... | 3,321 | 109,509 |
QwenPaw | src/qwenpaw/tunnel/binary_manager.py | .py | # -*- coding: utf-8 -*-
"""Auto-download cloudflared binary if not in PATH."""
from __future__ import annotations
import hashlib
import logging
import os
import platform
import shutil
import stat
import tempfile
from pathlib import Path
import httpx
from ..constant import WORKING_DIR
logger = logging.getLogger(__na... | 210 | 7,042 |
QwenPaw | src/qwenpaw/tunnel/__init__.py | .py | # -*- coding: utf-8 -*-
"""Tunnel utilities for exposing local servers to the internet."""
from .cloudflare import CloudflareTunnelDriver, TunnelInfo
__all__ = ["CloudflareTunnelDriver", "TunnelInfo"]
| 6 | 202 |
QwenPaw | src/qwenpaw/tunnel/cloudflare.py | .py | # -*- coding: utf-8 -*-
"""Cloudflare Quick Tunnel driver.
Runs ``cloudflared tunnel --url http://localhost:<port>`` and exposes
the generated ``*.trycloudflare.com`` URL.
"""
from __future__ import annotations
import asyncio
import logging
import re
from dataclasses import dataclass
from datetime import datetime, ti... | 198 | 6,488 |
QwenPaw | src/qwenpaw/agent_stats/models.py | .py | # -*- coding: utf-8 -*-
"""Agent statistics models."""
from __future__ import annotations
from pydantic import BaseModel
class ChannelStats(BaseModel):
channel: str
session_count: int
user_messages: int
assistant_messages: int
total_messages: int
class DailyStats(BaseModel):
date: str
... | 52 | 1,297 |
QwenPaw | src/qwenpaw/agent_stats/__init__.py | .py | # -*- coding: utf-8 -*-
"""Agent statistics package."""
from __future__ import annotations
from .models import AgentStatsSummary, ChannelStats, DailyStats
from .service import AgentStatsService, get_agent_stats_service
__all__ = [
"AgentStatsService",
"AgentStatsSummary",
"ChannelStats",
"DailyStats"... | 16 | 355 |
QwenPaw | src/qwenpaw/agent_stats/service.py | .py | # -*- coding: utf-8 -*-
"""Agent statistics service."""
from __future__ import annotations
import asyncio
import logging
import os
from datetime import date, timedelta
from pathlib import Path
import aiofiles
import aiofiles.os
import orjson
from ..app.chats.repo import JsonChatRepository
from ..token_usage import ... | 452 | 15,844 |
QwenPaw | src/qwenpaw/utils/command_runner.py | .py | # -*- coding: utf-8 -*-
from __future__ import annotations
import asyncio
import os
import signal
import subprocess
import time
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Mapping, Sequence
from qwenpaw.exceptions import (
CommandExecutionErro... | 620 | 17,265 |
QwenPaw | src/qwenpaw/utils/logging.py | .py | # -*- coding: utf-8 -*-
"""Logging setup for application logging and optional file output."""
import logging
import logging.handlers
import os
import platform
import re
import sys
from pathlib import Path
from ..constant import PROJECT_NAME, WORKING_DIR
# Rotating file handler limits (idempotent add avoids duplicate... | 342 | 11,131 |
QwenPaw | src/qwenpaw/utils/telemetry.py | .py | # -*- coding: utf-8 -*-
"""Telemetry collection for installation analytics."""
from __future__ import annotations
import json
import logging
import platform
import subprocess
import sys
import time
import uuid
from pathlib import Path
from typing import Any, Callable
logger = logging.getLogger(__name__)
TELEMETRY_EN... | 305 | 9,849 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.