Skills 模块¶
本页分为两部分:
Research Skills:
agentsociety2.skills下的科研工作流模块。Agent Skills:
agentsociety2.agent.skills下的 PersonAgent 技能注册与运行时机制。
Research Skills¶
总入口¶
AgentSociety2 技能模块。
本模块包含研究工作流和分析工具层入口,支持完整的科研流程:
技能列表¶
literature: 学术文献搜索与管理,支持检索、索引和格式化
experiment: 实验配置与执行,支持参数生成和配置验证
hypothesis: 假设生成与管理,支持创建、读取、列表和删除
analysis: 数据分析工具层,提供实验上下文读取、EDA 和工具注册能力
使用示例¶
from pathlib import Path
from agentsociety2.skills import analysis, hypothesis, literature
# 文献检索
results = await literature.search_literature("machine learning")
# 创建假设
hypothesis.add_hypothesis(
workspace_path=Path("./workspace"),
hypothesis="社会网络密度影响信息传播速度"
)
# 读取实验 replay catalog
from agentsociety2.storage import ReplayReader
reader = ReplayReader(Path("./workspace/hypothesis_1/experiment_1/run/replay"))
datasets = reader.load_dataset_catalog()
reader.close()
analysis¶
Analysis tool layer: data access, execution helpers, output helpers, and path utilities.
- class agentsociety2.skills.analysis.AnalysisResult(*, experiment_id, hypothesis_id, insights=<factory>, findings=<factory>, conclusions='', recommendations=<factory>, generated_at=<factory>)[源代码]¶
实验分析结果
- model_config = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.skills.analysis.AssetManager(workspace_path)[源代码]¶
Discover and normalize analysis assets.
- class agentsociety2.skills.analysis.DataStats(numeric_stats=<factory>, categorical_stats=<factory>, sample_data=<factory>, quick_stats_md='')[源代码]¶
数据统计摘要
- __init__(numeric_stats=<factory>, categorical_stats=<factory>, sample_data=<factory>, quick_stats_md='')¶
- class agentsociety2.skills.analysis.DataSummary(db_path=None, schema=None, stats=None)[源代码]¶
完整数据摘要
- schema: DatabaseSchema | None = None¶
- __init__(db_path=None, schema=None, stats=None)¶
- class agentsociety2.skills.analysis.DatabaseSchema(tables, columns, row_counts, markdown='')[源代码]¶
数据库 Schema 信息
- __init__(tables, columns, row_counts, markdown='')¶
- class agentsociety2.skills.analysis.EDAGenerator[源代码]¶
Generate exploratory data analysis artifacts.
- generate_missingno_report(db_path, output_dir, max_rows=50000, tables=None)[源代码]¶
Generate a missing-value report with missingno.
- generate_correlation_report(db_path, output_dir, max_rows=50000, tables=None)[源代码]¶
Generate a correlation report.
- generate_ydata_profile(db_path, output_dir, max_rows=10000, tables=None)[源代码]¶
Generate a ydata-profiling report.
- class agentsociety2.skills.analysis.ExecutionResult(success, stdout='', stderr='', artifacts=<factory>, generated_code='', error='')[源代码]¶
Code execution result.
- __init__(success, stdout='', stderr='', artifacts=<factory>, generated_code='', error='')¶
- class agentsociety2.skills.analysis.ExperimentContext(*, experiment_id, hypothesis_id, design, duration_seconds=None, execution_status=ExperimentStatus.UNKNOWN, completion_percentage=0.0, error_messages=<factory>)[源代码]¶
完整实验状态
- design: ExperimentDesign¶
- execution_status: ExperimentStatus¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.skills.analysis.ExperimentDesign(*, hypothesis, objectives=<factory>, variables=<factory>, methodology='', success_criteria=<factory>, hypothesis_markdown=None, experiment_markdown=None)[源代码]¶
实验设计
- model_config = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.skills.analysis.ExperimentPaths(*, hypothesis_base, experiment_path, run_path, db_path, pid_path, assets_path)[源代码]¶
单实验在 workspace 下的约定路径(只读,由 utils.experiment_paths 构建)。
- model_config = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.skills.analysis.ExperimentStatus(*values)[源代码]¶
实验执行的状态
- SUCCESSFUL = 'successful'¶
- PARTIAL_SUCCESS = 'partial_success'¶
- FAILED = 'failed'¶
- INTERRUPTED = 'interrupted'¶
- UNKNOWN = 'unknown'¶
- class agentsociety2.skills.analysis.HypothesisSummary(*, hypothesis_id, hypothesis_text, experiment_count=0, successful_experiments=0, total_completion=0.0, key_insights=<factory>, main_findings=<factory>, experiment_results=<factory>)[源代码]¶
跨多个实验的分析结果
- model_config = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.skills.analysis.PresentationPaths(*, output_dir, charts_dir, report_assets_dir, report_zh_md, report_zh_html, report_en_md, report_en_html, result_json, readme)[源代码]¶
单实验分析产物的输出路径。
这些路径按 hypothesis 聚合,位于
presentation/下,由utils.presentation_paths构建。典型产物包括:
output_dir/下的双语报告、README.md与data/analysis_summary.json。charts/下的生成图表,以及复制到assets/的报告引用资源。
- model_config = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.skills.analysis.ReportAsset(*, asset_id, asset_type, title, description='', file_path, embedded_content=None, file_size=0, created_at=<factory>, dimensions=None)[源代码]¶
报告所需要的其他资源
- model_config = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.skills.analysis.ReportContent(*, title, subtitle='', format_preference='markdown', full_content_markdown_zh=None, full_content_html_zh=None, full_content_markdown_en=None, full_content_html_en=None)[源代码]¶
报告内容(支持中英双语)
- model_config = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.skills.analysis.ReportPaths(markdown, html, markdown_zh=None, html_zh=None, markdown_en=None, html_en=None, assets_dir=None)[源代码]¶
Report file paths.
- __init__(markdown, html, markdown_zh=None, html_zh=None, markdown_en=None, html_en=None, assets_dir=None)¶
- class agentsociety2.skills.analysis.SynthesisPaths(*, output_dir, report_assets_dir, report_zh_md, report_en_md)[源代码]¶
综合报告输出路径(位于独立 synthesis 根目录下)。
- model_config = {'arbitrary_types_allowed': True}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.skills.analysis.ToolInfo(name, description, tool_type='builtin', parameters=<factory>)[源代码]¶
Tool metadata.
- __init__(name, description, tool_type='builtin', parameters=<factory>)¶
- class agentsociety2.skills.analysis.ToolResult(*, success, content, error=None, data=None)[源代码]¶
Tool execution result.
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- agentsociety2.skills.analysis.collect_experiment_files(db_path)[源代码]¶
收集 run 目录下可供执行器使用的文件路径(含 replay/、同级文件、run/artifacts)。
- agentsociety2.skills.analysis.experiment_paths(workspace_path, hypothesis_id, experiment_id)[源代码]¶
按约定聚合单实验路径;id 会做安全清洗。
- agentsociety2.skills.analysis.extract_database_schema(db_path)[源代码]¶
Extract replay schema from metadata catalog tables.
- agentsociety2.skills.analysis.format_database_schema_markdown(schema, include_row_counts=False, db_path=None)[源代码]¶
将 replay metadata schema 格式化为 Markdown,可选行数。
experiment¶
Experiment execution skills
Provides experiment execution and result management.
- class agentsociety2.skills.experiment.ExperimentConfig(*, hypothesis_id, experiment_id, run_id='run', agent_classes=<factory>, env_modules=<factory>, user_instructions=None, **extra_data)[源代码]¶
Experiment configuration model
Basic configuration for an experiment run.
- model_config = {'extra': 'allow'}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.skills.experiment.ExperimentConfigTool(workspace_path, progress_callback=None, tool_id='')[源代码]¶
Tool for initializing and validating experiment configurations
- class agentsociety2.skills.experiment.ExperimentInfo(*, hypothesis_id, experiment_id, run_id='run', has_init=False, has_run=False, status=None, pid=None, is_running=False, **extra_data)[源代码]¶
Information about an experiment
Summary of an experiment's configuration and status.
- model_config = {'extra': 'allow'}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.skills.experiment.ExperimentStatus(*, hypothesis_id, experiment_id, run_id, status, pid=None, start_time=None, end_time=None, stdout_log=None, stderr_log=None, is_running=False, **extra_data)[源代码]¶
Experiment execution status model
Represents the current status of a running or completed experiment.
- model_config = {'extra': 'allow'}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- agentsociety2.skills.experiment.format_module_suggestion_message(suggestions)[源代码]¶
Format module suggestions into a helpful message
- agentsociety2.skills.experiment.generate_hypothesis_config(topic, description, rationale, groups, agent_classes=None, env_modules=None)[源代码]¶
Generate a complete hypothesis configuration
This function creates a properly formatted hypothesis configuration that can be passed to add_hypothesis_with_validation().
- 参数:
- 返回:
Complete hypothesis configuration dictionary
- 返回类型:
- agentsociety2.skills.experiment.get_available_agent_modules()[源代码]¶
Get available agent modules with their descriptions
- agentsociety2.skills.experiment.get_available_env_modules()[源代码]¶
Get available environment modules with their descriptions
- async agentsociety2.skills.experiment.get_experiment_status(workspace_path, hypothesis_id, experiment_id, run_id='run')[源代码]¶
Get experiment status
- 参数:
- 返回:
ExperimentStatus object
- 返回类型:
- agentsociety2.skills.experiment.get_experiment_template(workspace_path, hypothesis_id, experiment_id)[源代码]¶
Get a template for experiment configuration
This function provides a template structure that Claude Code can use to generate the full experiment configuration.
- agentsociety2.skills.experiment.get_module_selection_guidance(topic, agent_classes=None, env_modules=None)[源代码]¶
Generate guidance text for module selection
- agentsociety2.skills.experiment.get_modules_summary()[源代码]¶
Get a formatted summary of available modules for LLM prompts
- 返回:
Formatted string with available modules
- 返回类型:
- async agentsociety2.skills.experiment.list_experiments(workspace_path, hypothesis_id=None)[源代码]¶
List experiments
- 参数:
- 返回:
List of ExperimentInfo objects
- 返回类型:
备注
Uses simplified init structure: init/init_config.json, init/steps.yaml
- async agentsociety2.skills.experiment.start_experiment(workspace_path, hypothesis_id, experiment_id, run_id='run', init_config_path=None, steps_path=None)[源代码]¶
Start an experiment
- 参数:
workspace_path (Path) -- Path to workspace directory
hypothesis_id (str) -- Hypothesis ID (e.g., '1', '2')
experiment_id (str) -- Experiment ID (e.g., '1', '2')
run_id (str) -- Run ID (default: 'run')
init_config_path (Path | None) -- Optional path to init_config.json (default: init/init_config.json)
steps_path (Path | None) -- Optional path to steps.yaml (default: init/steps.yaml)
- 返回:
Result dictionary with status and info
- 返回类型:
- async agentsociety2.skills.experiment.stop_experiment(workspace_path, hypothesis_id, experiment_id, run_id='run')[源代码]¶
Stop a running experiment
- agentsociety2.skills.experiment.suggest_modules_for_topic(topic)[源代码]¶
Suggest appropriate agent and environment modules for a research topic
This function analyzes the research topic and suggests suitable agent types and environment modules based on keywords and common patterns.
- agentsociety2.skills.experiment.validate_experiment_ready(workspace_path, hypothesis_id, experiment_id)[源代码]¶
Check if an experiment is ready to run
This function validates that all necessary configuration is in place for an experiment to be executed.
- agentsociety2.skills.experiment.validate_hypothesis_modules(hypothesis_data)[源代码]¶
Validate that a hypothesis has required modules
hypothesis¶
Hypothesis management module
Provides functionality for: - Creating hypotheses - Reading hypotheses - Listing hypotheses - Deleting hypotheses
- class agentsociety2.skills.hypothesis.ExperimentGroupModel(*, name, group_type, description, agent_selection_criteria=None)[源代码]¶
Experiment group model (for hypothesis generation phase)
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.skills.hypothesis.HypothesisDataModel(*, hypothesis, groups, agent_classes=None, env_modules=None)[源代码]¶
Hypothesis data model (including hypothesis and experiment groups)
- hypothesis: HypothesisModel¶
- groups: List[ExperimentGroupModel]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.skills.hypothesis.HypothesisModel(*, description, rationale)[源代码]¶
Hypothesis model
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- agentsociety2.skills.hypothesis.add_hypothesis(workspace_path, hypothesis_data)[源代码]¶
Add a new hypothesis
- agentsociety2.skills.hypothesis.add_hypothesis_with_validation(workspace_path, hypothesis_data, validate_modules=True)[源代码]¶
Add a new hypothesis with enhanced module validation
This function provides enhanced validation that checks: 1. Schema validity (via Pydantic) 2. Agent and environment module selection (at least one of each required)
- 参数:
- 返回:
Result dictionary with success status and info. If module validation fails, includes guidance for module selection.
- 返回类型:
- agentsociety2.skills.hypothesis.create_hypothesis_structure(workspace_path, hypothesis_id, hypothesis_model)[源代码]¶
Create hypothesis directory structure
- 参数:
workspace_path (Path) -- Path to workspace directory
hypothesis_id (str) -- Hypothesis ID
hypothesis_model (HypothesisDataModel) -- Validated hypothesis data model
- 返回:
Path to created hypothesis directory
- 返回类型:
- agentsociety2.skills.hypothesis.delete_hypothesis(workspace_path, hypothesis_id=None, hypothesis_path=None)[源代码]¶
Delete a hypothesis folder
- agentsociety2.skills.hypothesis.find_existing_hypotheses(workspace_path)[源代码]¶
Find existing hypothesis directories
- agentsociety2.skills.hypothesis.generate_experiment_markdown(group, exp_idx)[源代码]¶
Generate EXPERIMENT.md content
- 参数:
group (ExperimentGroupModel) -- Experiment group model
exp_idx (int) -- Experiment index
- 返回:
Markdown content for EXPERIMENT.md
- 返回类型:
- agentsociety2.skills.hypothesis.generate_hypothesis_markdown(hypothesis_model)[源代码]¶
Generate HYPOTHESIS.md content
- 参数:
hypothesis_model (HypothesisDataModel) -- Validated hypothesis data model
- 返回:
Markdown content for HYPOTHESIS.md
- 返回类型:
- agentsociety2.skills.hypothesis.generate_sim_settings(hypothesis_model)[源代码]¶
Generate SIM_SETTINGS.json content
- 参数:
hypothesis_model (HypothesisDataModel) -- Validated hypothesis data model
- 返回:
SIM_SETTINGS dictionary
- 返回类型:
- agentsociety2.skills.hypothesis.get_hypothesis(workspace_path, hypothesis_id=None, hypothesis_path=None)[源代码]¶
Get hypothesis details
- agentsociety2.skills.hypothesis.get_next_hypothesis_id(workspace_path)[源代码]¶
Get the next hypothesis ID
literature¶
Literature search and management.
Academic literature search (MCP), workspace indexing, formatting, and full-text helpers.
- class agentsociety2.skills.literature.LiteratureEntry(*, title, journal=None, doi=None, abstract=None, file_path, file_type, source, query=None, avg_similarity=None, saved_at, extra_fields=None)[源代码]¶
Literature entry data model
Used to standardize literature JSON entries, ensuring data structure consistency and type safety.
- file_type: Literal['markdown', 'pdf', 'docx', 'txt', 'md']¶
- source: Literal['literature_search', 'user_upload']¶
- model_config = {'extra': 'forbid', 'json_schema_extra': {'example': {'abstract': 'This is an example abstract...', 'avg_similarity': 0.85, 'doi': '10.1000/example', 'file_path': 'papers/Example_Research_Paper_2024-01-01.md', 'file_type': 'markdown', 'journal': 'Journal of Example Studies', 'query': 'example research', 'saved_at': '2024-01-01T12:00:00', 'source': 'literature_search', 'title': 'Example Research Paper'}}}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class agentsociety2.skills.literature.LiteratureIndex(*, entries=<factory>, version='1.0', created_at=None, updated_at=None)[源代码]¶
Literature index data model
Used to standardize the entire literature index JSON file structure.
- entries: list[LiteratureEntry]¶
- model_config = {'extra': 'forbid', 'json_schema_extra': {'example': {'created_at': '2024-01-01T12:00:00', 'entries': [{'abstract': 'This is an example abstract...', 'avg_similarity': 0.85, 'doi': '10.1000/example', 'file_path': 'papers/Example_Research_Paper_2024-01-01.md', 'file_type': 'markdown', 'journal': 'Journal of Example Studies', 'query': 'example research', 'saved_at': '2024-01-01T12:00:00', 'source': 'literature_search', 'title': 'Example Research Paper'}], 'updated_at': '2024-01-01T12:00:00', 'version': '1.0'}}}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- agentsociety2.skills.literature.format_article_as_markdown(article, query)[源代码]¶
Format a single literature article as markdown
- agentsociety2.skills.literature.format_search_results(articles, total, query)[源代码]¶
Format search results for display
- async agentsociety2.skills.literature.generate_summary(query, articles, total, router=None)[源代码]¶
Generate a summary using LLM to guide users on next steps
- agentsociety2.skills.literature.load_literature_index(workspace_path)[源代码]¶
Load literature index from workspace
- 参数:
workspace_path (Path) -- Path to workspace directory
- 返回:
LiteratureIndex object or None if file doesn't exist
- 返回类型:
LiteratureIndex | None
- agentsociety2.skills.literature.sanitize_filename(filename)[源代码]¶
Clean filename by removing illegal characters
- async agentsociety2.skills.literature.search_literature(query, limit=10, router=None, year_from=None, year_to=None, sources=None, similarity_threshold=None, vector_similarity_weight=None, chunk_content_limit=None, relevant_content_limit=None, max_chunks_per_article=None, return_chunks=True, enable_multi_query=False, mcp_url=None, api_key=None, timeout=120)[源代码]¶
Search academic literature through the MCP gateway.
- 参数:
query (str) -- Search query; Chinese text is translated to English when detected.
limit (int) -- Maximum number of articles per sub-query (default 10).
router (Router | None) -- LLM router for translation and query splitting.
year_from (int | None) -- Optional start publication year filter.
year_to (int | None) -- Optional end publication year filter.
sources (List[Literal['local', 'arxiv', 'crossref', 'openalex']] | None) -- Optional source list (
local,arxiv,crossref,openalex); default all.similarity_threshold (float | None) -- Local index similarity threshold (0.0–1.0).
vector_similarity_weight (float | None) -- Vector weight for hybrid local search (0.0–1.0).
chunk_content_limit (int | None) -- Max characters per chunk in the response.
relevant_content_limit (int | None) -- Max characters of relevant content per article.
max_chunks_per_article (int | None) -- Max chunks returned per article.
return_chunks (bool) -- Whether to include chunk text in results.
enable_multi_query (bool) -- Split complex queries into subtopics and merge results.
mcp_url (str | None) -- MCP gateway URL; uses
Config.get_literature_search_mcp_url()when omitted.api_key (str | None) -- Bearer API key; uses
Config.get_literature_search_api_key()when omitted.timeout (int) -- MCP request timeout in seconds.
- 返回:
Dict with
articles,total,query, and optionalsources;Noneon failure.- 返回类型:
- async agentsociety2.skills.literature.search_literature_and_save(query, workspace_path, router=None, limit=10, year_from=None, year_to=None, sources=None, enable_multi_query=False, download_full_text=True)[源代码]¶
Search for literature and save results to workspace
- 参数:
query (str) -- Search query (supports Chinese, will be translated to English)
workspace_path (Path) -- Path to workspace directory
router (Any | None) -- Optional litellm router. When omitted, the default LLM dispatcher is used.
limit (int) -- Number of articles to return (default: 10)
year_from (int | None) -- Filter by publication year (start)
year_to (int | None) -- Filter by publication year (end)
sources (List[Literal['local', 'arxiv', 'crossref', 'openalex']] | None) -- Data sources to search (default: all sources)
enable_multi_query (bool) -- Enable multi-query mode to split complex queries into subtopics
download_full_text (bool) -- After saving metadata, try to download open-access PDFs
- 返回:
Dictionary with search results and saved file information
- 返回类型:
备注
当前仓库中可公开使用的 research skills 模块为 analysis、experiment、
hypothesis、literature。web_research 目录当前没有保留
可读源码,因此未列为文档 API 表面。
Agent Skills¶
技能基础设施(发现、可见性/激活、脚本执行、生命周期 hook)已从 agent/skills/ 下沉到
agentsociety2.agent.base。agent/skills/ 目录现在只承载技能**内容**(如内置的
daily-guidance/)。设计说明见 Agent Skills(智能体技能)。
SkillRegistry¶
- class agentsociety2.agent.base.skill_registry.SkillRegistry[源代码]¶
基类:
objectRegistry for Skill metadata.
- 参数:
None.
- get(skill_id)[源代码]¶
Return one skill descriptor by id.
- 参数:
skill_id (str) -- Registry skill id.
- 返回:
Matching descriptor, or None.
- 返回类型:
SkillDescriptor | None
- find_by_name(name)[源代码]¶
Find skill descriptors by display name.
- 参数:
name (str) -- Skill display name.
- 返回:
Matching descriptors.
- 返回类型:
- list_hooks(hook_type)[源代码]¶
List skills declaring one hook.
- 参数:
hook_type (str) -- Lifecycle hook name.
- 返回:
Skill descriptors that declare the hook.
- 返回类型:
SkillDescriptor¶
- class agentsociety2.agent.base.skill_registry.SkillDescriptor(skill_id, name, namespace, description, root, source, source_label, script, hooks)[源代码]¶
Skill metadata.
- 参数:
skill_id (str) -- Stable registry skill id.
name (str) -- Display name from SKILL.md.
namespace (str) -- Skill namespace.
description (str) -- Catalog description.
root (Path) -- Skill root directory.
source (str) -- Source category.
source_label (str) -- Human-readable source label.
script (str | None) -- Optional default script path.
- __init__(skill_id, name, namespace, description, root, source, source_label, script, hooks)¶
AgentSkillRuntime¶
- class agentsociety2.agent.base.skill_runtime.AgentSkillRuntime(agent_id, registry)[源代码]¶
基类:
objectRuntime for skill visibility, activation, and execution.
- __init__(agent_id, registry)[源代码]¶
Initialize the skill runtime.
- 参数:
agent_id (int) -- Numeric agent id.
registry (SkillRegistryLike) -- Skill registry facade used by this runtime.
- 返回:
None.
- 返回类型:
None
- bind_workspace(*, workspace_root, fs, trace_writer)[源代码]¶
Bind this runtime to an agent-owned workspace.
- 参数:
workspace_root (Path) -- Agent workspace root created by the agent.
fs (WorkspaceFS) -- Agent-owned workspace filesystem facade.
trace_writer (JsonlTraceWriter) -- Agent-owned trace writer.
- 返回:
None.
- 返回类型:
None
- property is_initialized: bool¶
Return whether the workspace is initialized.
- 参数:
None.
- 返回:
True when the workspace has been initialized.
- property fs: WorkspaceFS¶
Return the workspace filesystem facade.
- 参数:
None.
- 返回:
Workspace filesystem facade.
- set_visible_skills(tokens)[源代码]¶
Set visible skills for this agent.
Each entry may be a registry skill id (
namespace@name) or a display name; both forms resolve against the whole registry.
- visible_skill_count()[源代码]¶
Return the visible skill count.
- 参数:
None.
- 返回:
Number of visible skills.
- 返回类型:
- list_visible_skills()[源代码]¶
List visible skill descriptors.
- 参数:
None.
- 返回:
Visible skill descriptors.
- 返回类型:
- set_activated_skills(tokens)[源代码]¶
Set activated skills from visible skills.
Each entry may be a skill id (
namespace@name) or a display name; both forms resolve against visible skills.
- add_default_activated_skills(tokens)[源代码]¶
Activate configured default skills when they are visible.
Each entry may be a skill id or a display name.
- activated_skill_count()[源代码]¶
Return activated skill count.
- 参数:
None.
- 返回:
Number of activated skills.
- 返回类型:
- infer_single_script_skill_id()[源代码]¶
Infer a visible activated skill when exactly one has a default script.
- 参数:
None.
- 返回:
Skill id for the only active scripted skill, or an empty string.
- 返回类型:
- resolve_skill_id(token, *, visible_only=True)[源代码]¶
Resolve a skill id or display name to a registry skill id.
Accepts either a registry skill id (
namespace@name) or a bare displayname— every public skill API in this runtime takes the sametokenand tolerates both forms. Whenvisible_onlyis True (the default) resolution is restricted to visible skills; when False the whole registry is searched (use this for skills that are not yet visible, e.g. inadd_visible_skill()).Ambiguous display names (more than one match) resolve only when exactly one candidate is currently activated.
- resolve_skill_id_by_name(skill_name)[源代码]¶
Deprecated alias for
resolve_skill_id().
- activate_skill_by_name(skill_name)[源代码]¶
Deprecated alias for
activate_skill().
- deactivate_skill_by_name(skill_name)[源代码]¶
Deprecated alias for
deactivate_skill().
- activated_skill_content_xml()[源代码]¶
Render docs and resource hints for activated skills.
- 参数:
None.
- 返回:
XML-like skill content blocks for active skills.
- 返回类型:
- active_hook_skills(hook_type)[源代码]¶
List visible activated skills that declare one hook.
- 参数:
hook_type (str) -- Lifecycle hook name.
- 返回:
Skill descriptors eligible to run the hook.
- 返回类型:
- resolve_skill_path(path)[源代码]¶
Map a path to a
(skill_id, relative_path)inside a visible skill.Used to recover when an agent tries to
reada skill-bundled file (e.g.references/examples.md) via the generic workspacereadtool, which only sees the agent workspace and rejects such paths as "escaping" it. Returning a mapping lets the caller transparently delegate toread_skill_file()instead of failing.Two matching strategies, in order:
Direct containment — the resolved absolute path is inside a visible skill root.
Skill-name segment — some path component equals a visible skill's
skill_idorname(e.g. the model-emitted.../skills/daily-guidance/references/examples.md). The components after that segment are taken as the skill-relative path and must resolve to an existing file under the skill root.
- async run_skill_script(skill_id, script_path, argv, *, timeout_sec=30)[源代码]¶
Run a script inside a visible skill.
SkillScriptContext¶
- class agentsociety2.agent.base.skill_runtime.SkillScriptContext(workspace_root, skill_dir, skill_id, skill_name, env=<factory>)[源代码]¶
Per-call context handed to an in-process skill
entrypoint.Replaces the process-global env vars (
AGENT_WORK_DIRetc.) that the subprocess path relied on, so 50 agents can run their hooks in-process in parallel without racing onos.environ/cwd/sys.stdout.- 参数:
workspace_root (Path) -- This agent's workspace root (was
AGENT_WORK_DIR).skill_dir (Path) -- The skill package root (was
SKILL_DIR).skill_id (str) -- Registry skill id (was
SKILL_ID).skill_name (str) -- Display name (was
SKILL_NAME).env (dict[str, str]) -- Snapshot of the env-var dict the subprocess path would have set.
- __init__(workspace_root, skill_dir, skill_id, skill_name, env=<factory>)¶
SKILL.md Frontmatter¶
SKILL.md 文件使用 YAML frontmatter 声明 skill 元信息:
---
name: my-skill
description: 触发条件 + 输出结果,选择阶段 LLM 唯一可见的文本
script: scripts/my_skill.py
hooks:
pre_step: scripts/my_skill.py
---
frontmatter 之后识别的字段:name、description``(选择阶段唯一可见,决定是否激活)、
可选的 ``script``(默认脚本相对路径)与 ``hooks``(生命周期脚本映射,键如 ``pre_step /
post_step)。Skill 注册 id 形如 namespace@name``(内置 ``built-in@、自定义 custom@)。
脚本默认在 agent 进程内经 entrypoint(argv, ctx) 执行(详见 Agent Skills(智能体技能));以
env: 开头的 skill id 会被重定向到 ask_env,走环境路由而非脚本。