Skills Module¶
This page is divided into two parts:
Research Skills: research workflow modules under
agentsociety2.skills.Agent Skills: PersonAgent skill registration and runtime mechanisms under
agentsociety2.agent.skills.
Research Skills¶
Top-level Entry¶
AgentSociety2 skills module.
This module provides the entry points for research workflows and analysis tooling, supporting a complete research process:
Skill List¶
literature: academic literature search and management, including retrieval, indexing, and formatting
experiment: experiment configuration and execution, including parameter generation and configuration validation
hypothesis: hypothesis generation and management, including create, read, list, and delete operations
analysis: data analysis tooling, providing experiment context loading, EDA, and tool registration capabilities
Usage Example¶
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>)[source]¶
Experiment Analysis Result
- 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)[source]¶
Discover and normalize analysis assets.
- class agentsociety2.skills.analysis.ContextLoader(workspace_path)[source]¶
Experiment Context Loading
- class agentsociety2.skills.analysis.DataReader(db_path)[source]¶
Database Reading and Interpretation
- class agentsociety2.skills.analysis.DataStats(numeric_stats=<factory>, categorical_stats=<factory>, sample_data=<factory>, quick_stats_md='')[source]¶
Data Statistics Summary
- __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)[source]¶
Complete Data Summary
- schema: DatabaseSchema | None = None¶
- __init__(db_path=None, schema=None, stats=None)¶
- class agentsociety2.skills.analysis.DatabaseSchema(tables, columns, row_counts, markdown='')[source]¶
Database Schema Information
- __init__(tables, columns, row_counts, markdown='')¶
- class agentsociety2.skills.analysis.EDAGenerator[source]¶
Generate exploratory data analysis artifacts.
- resolve_table_selection(reader, tables)[source]¶
Return requested, selected, and invalid table names.
- generate_missingno_report(db_path, output_dir, max_rows=50000, tables=None)[source]¶
Generate a missing-value report with missingno.
- generate_correlation_report(db_path, output_dir, max_rows=50000, tables=None)[source]¶
Generate a correlation report.
- generate_ydata_profile(db_path, output_dir, max_rows=10000, tables=None)[source]¶
Generate a ydata-profiling report.
- class agentsociety2.skills.analysis.ExecutionResult(success, stdout='', stderr='', artifacts=<factory>, generated_code='', error='')[source]¶
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>)[source]¶
Complete Experiment State
- 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)[source]¶
Experiment Design
- 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)[source]¶
Conventional read-only paths for a single experiment under the workspace, built by
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)[source]¶
Experiment Execution Status
- 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>)[source]¶
Analysis result across multiple experiments
- 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)[source]¶
Output paths for analysis artifacts of a single experiment.
These paths are grouped by hypothesis under
presentation/and built byutils.presentation_paths.Typical artifacts include:
bilingual reports, compatibility alias reports,
README.md, anddata/analysis_summary.jsonunderoutput_dir/.generated charts under
charts/, together with report reference assets copied intoassets/.
- 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)[source]¶
Additional assets required by the report
- 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)[source]¶
Report content with Chinese and English variants
- 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)[source]¶
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)[source]¶
Output paths for synthesis reports under the standalone
synthesisroot directory.- 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>)[source]¶
Tool metadata.
- __init__(name, description, tool_type='builtin', parameters=<factory>)¶
- class agentsociety2.skills.analysis.ToolResult(*, success, content, error=None, data=None)[source]¶
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)[source]¶
Collect file paths under the run directory that executors may use, including replay/, sibling files, and run/artifacts.
- agentsociety2.skills.analysis.experiment_paths(workspace_path, hypothesis_id, experiment_id)[source]¶
Aggregate paths for a single experiment by convention; the id is sanitized for safety.
- agentsociety2.skills.analysis.extract_database_schema(db_path)[source]¶
Extract replay schema from metadata catalog tables.
- agentsociety2.skills.analysis.format_database_schema_markdown(schema, include_row_counts=False, db_path=None)[source]¶
Format the replay metadata schema as Markdown, with an optional row limit.
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)[source]¶
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='')[source]¶
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)[source]¶
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)[source]¶
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)[source]¶
Format module suggestions into a helpful message
- agentsociety2.skills.experiment.generate_hypothesis_config(topic, description, rationale, groups, agent_classes=None, env_modules=None)[source]¶
Generate a complete hypothesis configuration
This function creates a properly formatted hypothesis configuration that can be passed to add_hypothesis_with_validation().
- Parameters:
- Returns:
Complete hypothesis configuration dictionary
- Return type:
- agentsociety2.skills.experiment.get_available_agent_modules()[source]¶
Get available agent modules with their descriptions
- agentsociety2.skills.experiment.get_available_env_modules()[source]¶
Get available environment modules with their descriptions
- async agentsociety2.skills.experiment.get_experiment_status(workspace_path, hypothesis_id, experiment_id, run_id='run')[source]¶
Get experiment status
- Parameters:
- Returns:
ExperimentStatus object
- Return type:
- agentsociety2.skills.experiment.get_experiment_template(workspace_path, hypothesis_id, experiment_id)[source]¶
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)[source]¶
Generate guidance text for module selection
- agentsociety2.skills.experiment.get_modules_summary()[source]¶
Get a formatted summary of available modules for LLM prompts
- Returns:
Formatted string with available modules
- Return type:
- async agentsociety2.skills.experiment.list_experiments(workspace_path, hypothesis_id=None)[source]¶
List experiments
- Parameters:
- Returns:
List of ExperimentInfo objects
- Return type:
Note
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)[source]¶
Start an experiment
- Parameters:
workspace_path (Path) – Path to the 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)
- Returns:
Result dictionary with status and info
- Return type:
- async agentsociety2.skills.experiment.stop_experiment(workspace_path, hypothesis_id, experiment_id, run_id='run')[source]¶
Stop a running experiment
- agentsociety2.skills.experiment.suggest_modules_for_topic(topic)[source]¶
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)[source]¶
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)[source]¶
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)[source]¶
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)[source]¶
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)[source]¶
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)[source]¶
Add a new hypothesis
- agentsociety2.skills.hypothesis.add_hypothesis_with_validation(workspace_path, hypothesis_data, validate_modules=True)[source]¶
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)
- Parameters:
- Returns:
Result dictionary with success status and info. If module validation fails, includes guidance for module selection.
- Return type:
- agentsociety2.skills.hypothesis.create_hypothesis_structure(workspace_path, hypothesis_id, hypothesis_model)[source]¶
Create hypothesis directory structure
- Parameters:
workspace_path (Path) – Path to the workspace directory
hypothesis_id (str) – Hypothesis ID
hypothesis_model (HypothesisDataModel) – Validated hypothesis data model
- Returns:
Path to created hypothesis directory
- Return type:
- agentsociety2.skills.hypothesis.delete_hypothesis(workspace_path, hypothesis_id=None, hypothesis_path=None)[source]¶
Delete a hypothesis folder
- agentsociety2.skills.hypothesis.find_existing_hypotheses(workspace_path)[source]¶
Find existing hypothesis directories
- agentsociety2.skills.hypothesis.generate_experiment_markdown(group, exp_idx)[source]¶
Generate EXPERIMENT.md content
- Parameters:
group (ExperimentGroupModel) – Experiment group model
exp_idx (int) – Experiment index
- Returns:
Markdown content for EXPERIMENT.md
- Return type:
- agentsociety2.skills.hypothesis.generate_hypothesis_markdown(hypothesis_model)[source]¶
Generate HYPOTHESIS.md content
- Parameters:
hypothesis_model (HypothesisDataModel) – Validated hypothesis data model
- Returns:
Markdown content for HYPOTHESIS.md
- Return type:
- agentsociety2.skills.hypothesis.generate_sim_settings(hypothesis_model)[source]¶
Generate SIM_SETTINGS.json content
- Parameters:
hypothesis_model (HypothesisDataModel) – Validated hypothesis data model
- Returns:
SIM_SETTINGS dictionary
- Return type:
- agentsociety2.skills.hypothesis.get_hypothesis(workspace_path, hypothesis_id=None, hypothesis_path=None)[source]¶
Get hypothesis details
- agentsociety2.skills.hypothesis.get_next_hypothesis_id(workspace_path)[source]¶
Get the next hypothesis ID
literature¶
Literature search and management module
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)[source]¶
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)[source]¶
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)[source]¶
Format a single literature article as markdown
- agentsociety2.skills.literature.format_search_results(articles, total, query)[source]¶
Format search results for display
- async agentsociety2.skills.literature.generate_summary(query, articles, total, router=None)[source]¶
Generate a summary using LLM to guide users on next steps
- agentsociety2.skills.literature.is_chinese_text(text)[source]¶
Check whether the text contains Chinese characters
- agentsociety2.skills.literature.load_literature_index(workspace_path)[source]¶
Load literature index from workspace
- Parameters:
workspace_path (Path) – Path to the workspace directory
- Returns:
LiteratureIndex object or None if file doesn’t exist
- Return type:
LiteratureIndex | None
- agentsociety2.skills.literature.sanitize_filename(filename)[source]¶
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)[source]¶
Search academic literature through the MCP gateway.
- Parameters:
query (str) – Search query (supports Chinese, will be translated to English)
limit (int) – Number of articles to return (default: 10)
router (Router | None) – LLM router for translation and query splitting.
year_from (int | None) – Filter by publication year (start)
year_to (int | None) – Filter by publication year (start)
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) – Enable multi-query mode to split complex queries into subtopics
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.
- Returns:
Dict with
articles,total,query, and optionalsources;Noneon failure.- Return type:
- 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)[source]¶
Search for literature and save results to workspace
- Parameters:
query (str) – Search query (supports Chinese, will be translated to English)
workspace_path (Path) – Path to the 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
- Returns:
Dictionary with search results and saved file information
- Return type:
Note
The publicly documented research skill modules in this repository are analysis, experiment, hypothesis, and literature. The web_research directory does not currently retain readable source code, so it is not included in the documented API surface.
Agent Skills¶
Skill infrastructure (discovery, visibility / activation, script execution, and lifecycle hooks) has moved from agent/skills/ down into agentsociety2.agent.base. The agent/skills/ directory now only contains skill content, such as the built-in daily-guidance/. For design notes, see Agent Skills.
SkillRegistry¶
- class agentsociety2.agent.base.skill_registry.SkillRegistry[source]¶
Bases:
objectTool metadata.
- Parameters:
None.
- __init__()[source]¶
Initialize an empty registry.
- Parameters:
None.
- Returns:
None.
- Return type:
None
- scan_custom(skills_root, namespace='custom')[source]¶
Scan custom skills from a workspace directory.
- list_all()[source]¶
List all registered skills.
- Parameters:
None.
- Returns:
Get standard status descriptions.
- Return type:
- get(skill_id)[source]¶
Return one skill descriptor by id.
- Parameters:
skill_id (str) – Registry Module
- Returns:
Matching descriptor, or None.
- Return type:
SkillDescriptor | None
- find_by_name(name)[source]¶
Find skill descriptors by display name.
- Parameters:
name (str) – Skill display name.
- Returns:
Matching descriptors.
- Return type:
- list_hooks(hook_type)[source]¶
List skills declaring one hook.
- Parameters:
hook_type (str) – Lifecycle hook name.
- Returns:
Skill descriptors that declare the hook.
- Return type:
SkillRegistry¶
- class agentsociety2.agent.base.skill_registry.SkillDescriptor(skill_id, name, namespace, description, root, source, source_label, script, hooks)[source]¶
Tool metadata.
- Parameters:
skill_id (str) – Stable registry skill id.
name (str) – Display name from SKILL.md.
namespace (str) – Skill namespace.
description (str) – Hypothesis 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)¶
Agent Skills¶
- class agentsociety2.agent.base.skill_runtime.AgentSkillRuntime(agent_id, registry)[source]¶
Bases:
objectRegistry for skill discovery, management, and execution.
- __init__(agent_id, registry)[source]¶
Initialize the skill runtime.
- Parameters:
agent_id (int) – Experiment ID
registry (SkillRegistryLike) – Skill registry facade used by this runtime.
- Returns:
None.
- Return type:
None
- bind_workspace(*, workspace_root, fs, trace_writer)[source]¶
Bind this runtime to an agent-owned workspace.
- Parameters:
workspace_root (Path) – Agent workspace root created by the agent.
fs (WorkspaceFS) – Agent-owned workspace filesystem facade.
trace_writer (JsonlTraceWriter) – Agent-owned trace writer.
- Returns:
None.
- Return type:
None
- workspace_root()[source]¶
Return the workspace root.
- Parameters:
None.
- Returns:
Absolute workspace root path.
- Return type:
- property is_initialized: bool¶
Return whether the workspace is initialized.
- Parameters:
None.
- Returns:
True when the workspace has been initialized.
- property fs: WorkspaceFS¶
Return the workspace filesystem facade.
- Parameters:
None.
- Returns:
Workspace filesystem facade.
- set_visible_skills(tokens)[source]¶
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()[source]¶
Return the visible skill count.
- Parameters:
None.
- Returns:
Number of API calls made.
- Return type:
- list_visible_skills()[source]¶
List visible skill descriptors.
- Parameters:
None.
- Returns:
Visible skill descriptors.
- Return type:
- set_activated_skills(tokens)[source]¶
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)[source]¶
Activate configured default skills when they are visible.
Each entry may be a skill id or a display name.
- activated_skill_count()[source]¶
Return activated skill count.
- Parameters:
None.
- Returns:
Number of API calls made.
- Return type:
- infer_single_script_skill_id()[source]¶
Infer a visible activated skill when exactly one has a default script.
- Parameters:
None.
- Returns:
Skill id for the only active scripted skill, or an empty string.
- Return type:
- resolve_skill_id(token, *, visible_only=True)[source]¶
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)[source]¶
Deprecated alias for
resolve_skill_id().
- activate_skill_by_name(skill_name)[source]¶
Deprecated alias for
activate_skill().
- deactivate_skill_by_name(skill_name)[source]¶
Deprecated alias for
deactivate_skill().
- activated_skill_content_xml()[source]¶
Render docs and resource hints for activated skills.
- Parameters:
None.
- Returns:
XML-like skill content blocks for active skills.
- Return type:
- active_hook_skills(hook_type)[source]¶
List visible activated skills that declare one hook.
- Parameters:
hook_type (str) – Lifecycle hook name.
- Returns:
Skill descriptors eligible to run the hook.
- Return type:
- resolve_skill_path(path)[source]¶
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)[source]¶
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>)[source]¶
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.- Parameters:
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¶
The SKILL.md file uses YAML frontmatter to declare skill metainformation:
---
name: my-skill
description: 触发条件 + 输出结果,选择阶段 LLM 唯一可见的文本
script: scripts/my_skill.py
hooks:
pre_step: scripts/my_skill.py
---
Recognized frontmatter fields are name, description (the only text visible during selection and what determines activation), optional script (default relative script path), and hooks (lifecycle script mapping with keys such as pre_step / post_step). Skill registration ids look like namespace@name (built-in built-in@, custom custom@). Scripts execute by default in the agent process through entrypoint(argv, ctx) (see Agent Skills); skill ids starting with env: are redirected to ask_env and go through environment routing rather than script execution.