text stringlengths 14 100k | source stringclasses 1
value | repo stringclasses 810
values | language stringclasses 13
values |
|---|---|---|---|
<|fim_prefix|>"""
Storage layer for memory using SQLite + FTS5
Provides vector and keyword search capabilities
"""
from __future__ import annotations
import re
import sqlite3
import json
import hashlib
import threading
from typing import List, Dict, Optional, Any
from pathlib import Path
from dataclasses import datac... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Memory flush manager with Deep Dream distillation
Handles memory persistence when conversation context is trimmed or overflows:
- Uses LLM to summarize discarded messages into concise daily records
- Writes to daily memory files (lazy creation)
- Deduplicates trim flushes to avoid repeated writes
- R... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Agent Prompt Module - 系统提示词构建模块
"""
from .builder impor<|fim_suffix|>',
]
<|fim_middle|>t PromptBuilder, build_agent_system_prompt
from .workspace import ensure_workspace, load_context_files
__all__ = [
'PromptBuilder',
'build_agent_system_prompt',
'ensure_workspace',
'load_context_f... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>uild the user identity section."""
if not user_identity:
return []
is_en = language == "en"
lines = [
("## 👤 User identity" if is_en else "## 👤 用户身份"),
"",
]
if user_identity.get("name"):
lines.append(f"**{'Name' if is_en else '用户姓名'}**: {user_id... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Workspace Management
Initializes the workspace, creates template files, and loads context files.
"""
from __future__ import annotations
import os
from typing import List, Optional, Dict
from dataclasses import dataclass
from common.log import logger
from .builder import ContextFile
# Default file... | fim | zhayujie/CowAgent | python |
<|fim_suffix|> 'Task',
'TaskType',
'TaskStatus',
'AgentResult',
'AgentAction',
'AgentActionType',
'ToolResult',
'LLMModel',
'LLMRequest',
'ModelFactory',
'AgentCancelledError',
'CancelTokenRegistry',
'get_cancel_registry',
]
<|fim_prefix|>from .agent import Agent
from... | fim | zhayujie/CowAgent | python |
<|fim_suffix|> if not isinstance(part, dict):
continue
block_type = part.get('type', '')
if block_type == 'text':
total_tokens += self._estimate_text_tokens(part.get('text', ''))
elif block_type == 'image':
tot... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>truncated += 1
# Truncate tool_use input blocks (e.g. large write content)
if block.get("type") == "tool_use" and isinstance(block.get("input"), dict):
input_str = json.dumps(block["input"], ensure_ascii=False)
if len(input_str) > AGG... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>ent.set()
return len(entries)
def unregister(self, request_id: str) -> None:
"""Remove an entry once the agent run is done. Safe to call twice."""
if not request_id:
return
with self._lock:
entry = self._by_request.pop(request_id, None)
... | fim | zhayujie/CowAgent | python |
class TeamContext:
def __init__(self, name: str, description: str, rule: str, agents: list, max_steps: int = 100):
"""
Initialize the TeamContext with a name, description, rules, a list of agents, and a user question.
:param name: The name of the group context.
:param description: A ... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Message sanitizer — fix broken tool_use / tool_result pairs.
Provides two public helpers that can be reused across agent_stream.py
and any bot that converts messages to OpenAI format:
1. sanitize_claude_messages(messages)
Operates on the internal Claude-format message list (in-place).
2. drop_or... | fim | zhayujie/CowAgent | python |
<|fim_suffix|><|fim_prefix|>"""
Models module for agent system.
Provides basic model classes needed by tools and bridge integration.
"""
from typing import Any, Dict, List, Optional
class LLMRequest:
"""Request model for LLM operations"""
def __init__(self, messages: List[Dict[str, str]] = None, model: ... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>
def error(cls, error_message: str, step_count: int = 0) -> "AgentResult":
"""Create an error result"""
return cls(
final_answer=f"Error: {error_message}",
step_count=step_count,
status="error",
error_message=error_message
)
... | fim | zhayujie/CowAgent | python |
<|fim_suffix|> TaskStatus) -> None:
"""
Update the status of the task.
Args:
status: The new status
"""
self.status = status
self.updated_at = time.time()<|fim_prefix|>from __future__ import annotations
import time
import uuid
from dataclasses import ... | fim | zhayujie/CowAgent | python |
"""
Skills module for agent system.
This module provides the framework for loading, managing, and executing skills.
Skills are markdown files with frontmatter that provide specialized instructions
for specific tasks.
"""
from agent.skills.types import (
Skill,
SkillEntry,
SkillMetadata,
SkillInstallSp... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Configuration support for skills.
"""
import os
import platform
from typing import Dict, Optional, List
from agent.skills.types import SkillEntry
def resolve_runtime_platform() -> str:
"""Get the current runtime platform."""
return platform.system().lower()
def has_binary(bin_name: str) -... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Skill formatter for generating prompts from skills.
"""
from typing import Dict, List
from agent.skills.types import Skill, SkillEntry
def format_skills_for_prompt(skills: List[Skill]) -> str:
"""
Format skills for inclusion in a system prompt.
Uses XML format per Agent Skills stan... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Frontmatter parsing for skills.
"""
import re
import json
from typing import Dict, Any, Optional, List
from agent.skills.types import SkillMetadata, SkillInstallSpec
def parse_frontmatter(content: str) -> Dict[str, Any]:
"""
Parse YAML-style frontmatter from markdown content.
Retur... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>
# Load builtin skills (lower precedence)
if builtin_dir and os.path.exists(builtin_dir):
result = self.load_skills_from_dir(builtin_dir, source='builtin')
all_diagnostics.extend(result.diagnostics)
for skill in result.skills:
entry = sel... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>ytree(source_dir, target_dir)
logger.debug(f"Synced skill '{skill_name}' to {target_dir}")
except Exception as e:
logger.warning(f"Failed to sync skill '{skill_name}': {e}")
logger.info(f"Synced {len(self.skills)} skills to {target_skills_dir}")... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Skill service for handling skill CRUD operations.
This service provides a unified interface for managing skills, which can be
called from the cloud control client (LinkAI), the local web console, or any
other management entry point.
"""
import os
import shutil
import zipfile
import tempfile
from typ... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>skills for a specific run."""
prompt: str # Formatted prompt text
skills: List[Dict[str, str]] # List of skill info (name, primary_env)
resolved_skills: List[Skill] = field(default_factory=list)
version: Optional[int] = None
<|fim_prefix|>"""
Type definitions for skills system.
"""
from... | fim | zhayujie/CowAgent | python |
<|fim_prefix|># Import base tool
from agent.tools.base_tool import BaseTool
from agent.tools.tool_manager import ToolManager
# Import file operation tools
from agent.tools.read.read import Read
from agent.tools.write.write import Write
from agent.tools.edit.edit import Edit
from agent.tools.bash.bash import Bash
from ... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>from enum import Enum
from <|fim_suffix|>ields
def should_auto_execute(self, context) -> bool:
"""
Determine if this tool should be automatically executed based on context.
:param context: The agent context
:return: True if the tool should be executed, False otherwise... | fim | zhayujie/CowAgent | python |
from .bash import Bash
__all__ = ['Bash']
<|endoftext|> | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Bash tool - Execute bash commands
"""
import os
import re
import signal
import sys
import subprocess
import tempfile
import threading
import time
from typing import Dict, Any
from agent.tools.base_tool import BaseTool, ToolResult
from agent.tools.utils.truncate import truncate_tail, format_size, DEF... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>from<|fim_suffix|> BrowserTool
__all__ = ["BrowserTool"]
<|fim_middle|> agent.tools.browser.browser_tool import<|endoftext|> | fim | zhayujie/CowAgent | python |
"""
Browser service - Playwright wrapper managing browser lifecycle and page operations.
All Playwright calls run on a dedicated background thread so that callers from
any worker thread can safely use the service. An idle-timeout mechanism
automatically shuts down the browser (and its thread) after a configurable
per... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Browser tool - Control a Chromium browser for web navigation and interaction.
Uses Playwright under the hood. Browser instance is lazily started on first
use, reused across tool calls within the same session, and cleaned up via
close().
Launch modes (configured under `tools.browser` in config.json):... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>
__all__ = ['Edit']
<|fim_prefix|>from .edit impo<|fim_middle|>rt Edit
<|endoftext|> | fim | zhayujie/CowAgent | python |
<|fim_suffix|>pected."
)
# Restore original line endings
final_content = bom + restore_line_endings(new_content, original_ending)
# Write file
with open(absolute_path, 'w', encoding='utf-8') as f:
f.write(final_con... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>from agent.tool<|fim_suffix|>all__ = ['EnvConfig']
<|fim_middle|>s.env_config.env_config import EnvConfig
__<|endoftext|> | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Environment Configuration Tool - Manage API keys and environment variables
"""
import os
import re
from typing import Dict, Any
from pathlib import Path
from agent.tools.base_tool import BaseTool, ToolResult
from common.log import logger
from common.utils import expand_path
# API Key 知识库:常见的环境变量及其... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>from agent.tools.evolutio<|fim_suffix|>_ = ["EvolutionUndoTool"]
<|fim_middle|>n_undo.evolution_undo import EvolutionUndoTool
__all_<|endoftext|> | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""Evolution undo tool.
Lets the main chat agent roll back a previous self-evolution when the user asks
("undo the last learning"). The rollback itself is a deterministic FILE RESTORE
from the snapshot taken before the evolution — the model only supplies the
backup_id it reads from the [EVOLUTION] record... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>mport Ls
__all__ = ['Ls']
<|fim_prefix|>from<|fim_middle|> .ls i<|endoftext|> | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Ls tool - List directory contents
"""
import os
from typing import Dict, Any
from agent.tools.base_tool import BaseTool, ToolResult
from agent.tools.utils.truncate import truncate_head, format_size, DEFAULT_MAX_BYTES
from common.utils import expand_path
DEFAULT_LIMIT = 500
class Ls(BaseTool):
... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>from agent.tools.mcp.mcp_client import McpClient, McpClie<|fim_suffix|>pClient", "McpClientRegistry", "McpTool"]
<|fim_middle|>ntRegistry
from agent.tools.mcp.mcp_tool import McpTool
__all__ = ["Mc<|endoftext|> | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
MCP (Model Context Protocol) client module.
Implements JSON-RPC 2.0 over stdio, SSE and Streamable HTTP transports
without any external MCP SDK dependency.
"""
import json
import os
import queue
import subprocess
import threading
import urllib.request
import urllib.error
from typing import Optional
... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>from agent.tools.base_tool import BaseTool, ToolResult
from common.log import logger
class McpTool(BaseTool):
"""
将单个 MCP 工具包装为 BaseTool。
一个 MCP Server 可以提供多个工具,每个工具对应一个 McpTool 实例。
"""
def __init__(self, client, tool_schema: dict, server_name: s<|fim_suffix|>ema["name"]
sel... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Memory tools for Agent
Provides memory_search and memory_get <|fim_suffix|>MemoryGetTool']
<|fim_middle|>tools
"""
from agent.tools.memory.memory_search import MemorySearchTool
from agent.tools.memory.memory_get import MemoryGetTool
__all__ = ['MemorySearchTool', '<|endoftext|> | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Memory get tool
Allows agents to read specific sections from memory files
"""
from agent.tools.base_tool import BaseTool
class MemoryGetTool(BaseTool):
"""Tool for reading memory file contents"""
name: str = "memory_get"
description: str = (
"Read specific content from mem... | fim | zhayujie/CowAgent | python |
"""
Memory search tool
Allows agents to search their memory using semantic and keyword search
"""
from typing import Dict, Any, Optional
from agent.tools.base_tool import BaseTool
class MemorySearchTool(BaseTool):
"""Tool for searching agent memory"""
name: str = "memory_search"
description: str = ... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>from .read<|fim_suffix|>'Read']
<|fim_middle|> import Read
__all__ = [<|endoftext|> | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Read tool - Read file contents
Supports text files, images (jpg, png, gif, webp), and PDF files
"""
import os
from typing import Dict, Any
from pathlib import Path
from agent.tools.base_tool import BaseTool, ToolResult
from agent.tools.utils.truncate import truncate_head, format_size, DEFAULT_MAX_LI... | fim | zhayujie/CowAgent | python |
"""
Scheduler tool for managing scheduled tasks
"""
from .scheduler_tool import SchedulerTool
__all__ = ["SchedulerTool"]
<|endoftext|> | fim | zhayujie/CowAgent | python |
<|fim_suffix|>p
context["session_id"] = scheduler_session_id
if channel_type == "web":
import uuid
request_id = f"scheduler_{task['id']}_{uuid.uuid4().hex[:8]}"
context["request_id"] = request_id
elif channel_type == "feishu":
context["receive_id_... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Background scheduler service for executing scheduled tasks
"""
import time
import threading
from datetime import datetime, timedelta
from typing import Callable, Optional
from croniter import croniter
from common.log import logger
def _parse_naive_local(iso_str: str) -> datetime:
"""Parse an IS... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Scheduler tool for creating and managing scheduled tasks
"""
import uuid
from datetime import datetime
from typing import Any, Dict, Optional
from cro<|fim_suffix|>与ai_task二选一)"
},
"ai_task": {
"type": "string",
"description": "AI任务描述 (与message二... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Task storage management for scheduler
"""
import json
import os
import threading
from datetime import datetime
from typing import Dict, List, Optional
from pathlib import Path
from common.utils import expand_path
class TaskStore:
"""
Manages persistent storage of scheduled tasks
"""
... | fim | zhayujie/CowAgent | python |
<|fim_suffix|><|fim_prefix|>from .send import Send
__all__ =<|fim_middle|> ['Send']
<|endoftext|> | fim | zhayujie/CowAgent | python |
<|fim_suffix|>n/vnd.openxmlformats-officedocument.wordprocessingml.document',
'.xls': 'application/vnd.ms-excel',
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'.ppt': 'application/vnd.ms-powerpoint',
'.pptx': 'application/vnd.openxmlformat... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>import importlib
import importlib.util
import threading
from pathlib import Path
from typing import Dict, Any, Type
from agent.tools.base_tool import BaseTool
from common.log import logger
from config import conf
def _normalize_mcp_configs(raw) -> list:
"""
Convert MCP server config to internal ... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>from .truncate import (
truncate_head,
truncate_tail,
truncate_line,
format_size,
Truncati<|fim_suffix|>normalize_for_fuzzy_match,
fuzzy_find_text,
generate_diff_string,
FuzzyMatchResult
)
__all__ = [
'truncate_head',
'truncate_tail',
'truncate_line',
'form... | fim | zhayujie/CowAgent | python |
<|fim_suffix|># Not found
return FuzzyMatchResult(found=False)
def generate_diff_string(old_content: str, new_content: str) -> dict:
"""
Generate unified diff string
:param old_content: Old content
:param new_content: New content
:return: Dictionary containing diff and first changed line ... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Shared truncation utilities for tool outputs.
Truncation is based on two independent limits - whichever is hit first wins:
- Line limit (default: 2000 lines)
- Byte limit (default: 50KB)
Never returns partial lines (except bash tail truncation edge case).
"""
from __future__ import annotations
from... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>ort Vision
<|fim_prefix|>from agent.tools.<|fim_middle|>vision.vision imp<|endoftext|> | fim | zhayujie/CowAgent | python |
"""
Vision tool - Analyze images using Vision API.
Supports local files (auto base64-encoded) and HTTP URLs.
Provider resolution:
- tools.vision.model (if set) means "prefer this model first; fall back to
other configured providers if it fails". The model name is mapped to its
native provider (e.g. doubao-* ... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>if suffix in WORD_SUFFIXES:
return self._parse_word(file_path)
elif suffix in TEXT_SUFFIXES:
return self._parse_text(file_path)
elif suffix in SPREADSHEET_SUFFIXES:
return self._parse_spreadsheet(file_path)
elif suffix in PPT_SUFFIXES:
... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>rt WebSearch
__all__ = ["WebSearch"]
<|fim_prefix|>from agent.tools.web_search.web_searc<|fim_middle|>h impo<|endoftext|> | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""Web Search tool. Supports four backends with a unified response format:
- bocha (https://open.bochaai.com)
- zhipu (https://docs.bigmodel.cn/cn/guide/tools/web-search)
- qianfan (https://cloud.baidu.com/doc/qianfan/s/2mh4su4uy)
- linkai (https://link-ai.tech, fallback)
Provider selection
... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>ite
__all__ = ['Write']
<|fim_prefix|>from .wr<|fim_middle|>ite import Wr<|endoftext|> | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Write tool - Write file content
Creates or overwrites files, automatically creates parent directories
"""
import os
from typing import Dict, Any
from pathlib import Path
from agent.tools.base_tool import BaseTool, ToolResult
from common.utils import expand_path
class Write(BaseTool):
"""Tool f... | fim | zhayujie/CowAgent | python |
<|fim_suffix|> logger.warning(f"[App] MCP warmup failed (non-fatal): {e}")
def _warmup_scheduler():
"""Eager-init AgentBridge so the scheduler thread starts at process
boot rather than waiting for the first user message."""
try:
from bridge.bridge import Bridge
Bridge().get_agent_bridg... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Agent Bridge - Integrates Agent system with existing COW bridge
"""
import os
from typing import Optional, List
from agent.protocol import Agent, LLMModel, LLMRequest, get_cancel_registry
from bridge.agent_event_handler import AgentEventHandler
from bridge.agent_initializer import AgentInitializer
f... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Agent Event Handler - Handles agent events and thinking process output
"""
from common import const
from common.log import logger
# Cap intermediate thinking messages on weixin to stay with<|fim_suffix|>a)
elif event_type == "reasoning_update":
pass
elif event_type == "to... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Agent Initializer - Handles agent initialization logic
"""
import os
import asyncio
import datetime
import threading
import time
from typing import Optional, List
from agent.protocol import Agent
from agent.tools import ToolManager
from common.log import logger
from common.utils import expand_path
... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>ply:
"""
Use super agent to handle the query
Args:
query: User query
context: Context object
on_event: Event callback for streaming
clear_history: Whether to clear conversation history
Returns:
Reply object
... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>nt":
self.content = None
else:
del self.kwargs[key]
def __str__(self):
return "Context(type={}, content={}, kwargs={})".format(self.type, self.content, self.kwargs)
<|fim_prefix|># encoding:utf-8
from enum import Enum
class ContextType(Enum):
TEXT = 1 #... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>
TEXT_ = 11 # 强制文本
VIDEO = 12
MINIAPP = 13 # 小程序
def __str__(self):
return self.name
class Reply:
def __init__(self, type: ReplyType = None, content=None):
self.type = type
self.content = content
def __str__(self):
return "Reply(type={}, conten... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>xt: Context = None) -> Reply:
"""
Build reply content, using agent if enabled in config
"""
# Check if agent mode is enabled
use_agent = conf().get("agent", True)
if use_agent:
try:
logger.info("[Channel] Using agent mode")
... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
channel factory
"""
from common import const
from .channel import Channel
def create_channel(channel_type) -> Channel:
"""
create a channel instance
:param channel_type: channel type code
:return: channel instance
"""
ch = Channel()
if channel_type == "terminal":
... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>ems)} media item(s)")
for i, (url, media_type) in enumerate(media_items):
try:
# Determine whether it is a remote URL or a local file.
if url.startswith(('http://', 'https://')):
if media_type == 'vide... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>nickname,
self.to_user_id,
self.to_user_nickname,
self.other_user_id,
self.other_user_nickname,
self.is_group,
self.is_at,
self.actual_user_id,
self.actual_user_nickname,
self.at_list
)
<|fi... | fim | zhayujie/CowAgent | python |
<|fim_suffix|> "robotCode": incoming_message.robot_code,
"msgKey": msg_key,
"msgParam": json.dumps(msg_param),
}
if is_group:
# 群聊
url = "https://api.dingtalk.com/v1.0/robot/groupMessages/send"
body["openConversationId"] = incoming... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>import os
import re
import requests
from dingtalk_stream import ChatbotMessage
from bridge.context import ContextType
from channel.chat_message import ChatMessage
# -*- coding=utf-8 -*-
from common.log import logger
from common.tmp_dir import TmpDir
from common.utils import expand_path
from config impor... | fim | zhayujie/CowAgent | python |
<|fim_suffix|> tag = "image" if ctype == ContextType.IMAGE else "file"
merged_text = f"{caption}\n[{tag}: {content}]"
dc_msg.ctype = ContextType.TEXT
dc_msg.content = merged_text
ctype = ContextType.TEXT
logger.info(f"[Discord] ... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>_nick
else:
# DM: use channel_id so replies go back to the same DM channel
self.other_user_id = str(channel.id)
self.other_user_nickname = from_user_nick
# Whether the bot was triggered by @-mention (set by channel layer)
self.is_at = False
... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
飞书通道接入
支持两种事件接收模式:
1. webhook模式: 通过HTTP服务器接收事件(需要公网IP)
2. websocket模式: 通过长连接接收事件(本地开发友好)
通过配置项 feishu_event_mode 选择模式: "webhook" 或 "websocket"
@author Saboteur7
@Date 2023/11/19
"""
import importlib.util
import json
import logging
import os
import ssl
import threading
# -*- coding=utf-8 -*-
import... | fim | zhayujie/CowAgent | python |
from bridge.context import ContextType
from channel.chat_message import ChatMessage
import json
import os
import requests
from common.log import logger
from common.tmp_dir import TmpDir
from common import utils
from common.utils import expand_path
from config import conf
class FeishuMessage(ChatMessage):
def __in... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
文件缓存管理器
用于缓存单独发送的文件消息(图片、视频、文档等),在用户提问时自动附加
"""
import time
import logging
logger = logging.getLogger(__name__)
class FileCache:
"""文件缓存管理器,按 session_id 缓存文件,TTL=2分钟"""
def __init__(self, ttl=120):
"""
Args:
ttl: 缓存过期时间(秒),默认2分钟
"""
self.cach... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
QQ Bot channel via WebSocket long connection.
Supports:
- Group chat (@bot), single chat (C2C), guild channel, guild DM
- Text / image / file message send & receive
- Heartbeat keep-alive and auto-reconnect with session resume
"""
import base64
import json
import os
import threading
import time
imp... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>
self.ctype = ContextType.TEXT
image_paths = []
tmp_dir = _get_tmp_dir()
for idx, att in enumerate(attachments):
if not att.get("content_type", "").startswith("image/"):
continue
img_url = att.get("url", ""... | fim | zhayujie/CowAgent | python |
<|fim_suffix|> = "Current task cancelled." if cancelled else "No running task to cancel."
thread_ts = event.get("thread_ts") or event.get("ts")
self._client.chat_postMessage(channel=channel_id, text=text, thread_ts=thread_ts)
logger.info(f"[Slack] /cancel session={session_id}, cancel... | fim | zhayujie/CowAgent | python |
<|fim_suffix|> self.other_user_nickname = channel_id
self.actual_user_id = from_user_id
self.actual_user_nickname = from_user_id
else:
# DM: use channel_id so replies go back to the same DM channel
self.other_user_id = channel_id or from_user_id
... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Telegram channel via Bot API (long polling mode).
Features:
- Single chat & group chat (text / photo / voice / video / document)
- Group trigger: @mention or reply-to-bot (configurable)
- /cancel fast-path matches Web channel behaviour
- Auto-register bot commands menu on startup (mirrors Web slash m... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>"""
Telegram message adapter.
Convert a python-telegram-bot Update into cow's unified ChatMessage.
File downloads are NOT performed here; the channel layer triggers
bot.get_file() on demand because it requires the async event loop.
"""
import os
from bridge.context import ContextType
from channel.chat_m... | fim | zhayujie/CowAgent | python |
import json
import os
import sys
import time
from bridge.context import *
from bridge.reply import Reply, ReplyType
from channel.chat_channel import ChatChannel, check_prefix
from channel.chat_message import ChatMessage
from common.log import logger
from config import conf
class _Style:
"""ANSI escape codes for ... | fim | zhayujie/CowAgent | python |
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).axios=t()}(this,(function(){"use strict";function e(t){return e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?functio... | fim | zhayujie/CowAgent | javascript |
<|fim_prefix|># -*- coding=utf-8 -*-
"""
WeChat Customer Service (微信客服) channel for CoW.
Differences from `channel/wechatcom/` (企微自建应用):
1. Audience: external WeChat users (not internal members).
2. Receiver fields: `external_userid` + `open_kfid` instead of a single
member `userid`.
3. Inbound flow... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>._data[open_kfid] = cursor
self._flush_locked()
def has(self, open_kfid: str) -> bool:
with self._lock:
return open_kfid in self._data
<|fim_prefix|># -*- coding=utf-8 -*-
"""
Local-file based persistence for WeCom customer-service `next_cursor`.
Why we need this:
... | fim | zhayujie/CowAgent | python |
<|fim_prefix|># -*- coding=utf-8 -*-
"""
Adapter that turns a single `sync_msg` item from WeCom customer-service
into a CoW `ChatMessage` object.
"""
import os
import re
from wechatpy.enterprise import WeChatClient
from bridge.context import ContextType
from channel.chat_message import ChatMessage
from common.log imp... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>".format(sz))
image_storage = compress_imgfile(image_storage, 10 * 1024 * 1024 - 1)
logger.info("[wechatcom] image compressed, sz={}".format(fsize(image_storage)))
image_storage.seek(0)
if ".webp" in img_url:
try:
... | fim | zhayujie/CowAgent | python |
# wechatcomapp_client.py
import threading
import time
from wechatpy.enterprise import WeChatClient
class WechatComAppClient(WeChatClient):
def __init__(self, corp_id, secret, access_token=None, session=None, timeout=None, auto_retry=True):
super(WechatComAppClient, self).__init__(corp_id, secret, access_to... | fim | zhayujie/CowAgent | python |
<|fim_suffix|> raise NotImplementedError("Unsupported message type: Type:{} ".format(msg.type))
self.from_user_id = msg.source
self.to_user_id = msg.target
self.other_user_id = msg.source
<|fim_prefix|>from wechatpy.enterprise import WeChatClient
from bridge.context import ContextType
from ch... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>import time
import web
from wechatpy import parse_message
from wechatpy.replies import create_reply
from bridge.context import *
from bridge.reply import *
from channel.wechatmp.common import *
from channel.wechatmp.wechatmp_channel import WechatMPChannel
from channel.wechatmp.wechatmp_message import We... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>ash over attacker-controlled values.
if not token:
raise web.Forbidden("wechatmp_token is not configured")
check_signature(token, signature, timestamp, nonce)
return echostr
except InvalidSignatureException:
raise web.Forbidden("Invalid signature")
excep... | fim | zhayujie/CowAgent | python |
<|fim_prefix|>import asyncio
import time
import web
from wechatpy import parse_message
from wechatpy.replies import ImageReply, VoiceReply, create_reply
import textwrap
from bridge.context import *
from bridge.reply import *
from channel.wechatmp.common import *
from channel.wechatmp.wechatmp_channel import WechatMPCh... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>at(image_storage)
filename = receiver + "-" + str(context["msg"].msg_id) + "." + image_type
content_type = "image/" + image_type
try:
response = self.client.media.upload("image", (filename, image_storage, content_type))
... | fim | zhayujie/CowAgent | python |
<|fim_suffix|>or_endpoint, **kwargs)
else:
logger.error("[wechatmp] last clear quota time is {}, less than 60s, skip clear quota")
raise e
<|fim_prefix|>import threading
import time
from wechatpy.client import WeChatClient
from wechatpy.exceptions import APILimitedException
... | fim | zhayujie/CowAgent | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.