xeophon commited on
Commit
32fdf48
·
verified ·
1 Parent(s): 421b35b

Upload general-agent environment with RL tags

Browse files

Copy environments/tool_use/general_agent from https://github.com/PrimeIntellect-ai/prime-envs/tree/5732a4bbb7e454716608b5f8af51ec890892350f/environments/tool_use/general_agent and add rl-environment and verifiers tags to the dataset card.

README.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - rl-environment
4
+ - verifiers
5
+ ---
6
+
7
+ # general-agent
8
+
9
+ Requires `verifiers[harbor]>=0.3.1`.
10
+
11
+ Multi-turn tool-use tasks from the self-growing general-agent toolbench, where each task ships its own tool world and a gold tool-call chain. Tasks are scored by replaying the gold chain and rewarding an exact final database-hash match or a passing `verify(db)` check.
12
+
13
+ ## Taskset
14
+
15
+ - **Source:** [`general-agent` corpus](https://github.com/PrimeIntellect-ai/prime-envs) downloaded via the Harbor CLI (not vendored)
16
+ - **Size:** 4,417 tasks
17
+
18
+ ## Notes
19
+
20
+ - The corpus is downloaded on first use (cached under `~/.cache/harbor/`) via the Harbor CLI, resolved through the legacy Harbor registry in `PrimeIntellect-ai/prime-envs`. Needs read access to those repos; point `--env.taskset.repo` / `--env.taskset.dataset` at a branch or pin for local or PR-branch validation.
21
+
22
+ ## Changelog
23
+
24
+ - 2026-07-31: Migrated each task's dynamic tool server to the explicit `toolsets(config)` API required by `verifiers>=0.2.2.dev65`.
25
+ - 2026-07-10: Ported to the task-centric verifiers API: rewards and lifecycle hooks live on the `Task` (a `TaskData` row + behavior split), and task-facing config knobs (judges, tool/user placement, scoring parameters) moved from `--env.taskset.*` to `--env.taskset.task.*`. Requires `verifiers>=0.2.0` and Python `>=3.11`.
general_agent/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from general_agent.taskset import GeneralAgentSolverTaskset
2
+
3
+ __all__ = ["GeneralAgentSolverTaskset"]
general_agent/common.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared types for the solver taskset and its toolset (kept here to avoid an import cycle)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import verifiers.v1 as vf
6
+
7
+
8
+ class GeneralAgentState(vf.State):
9
+ """Per-rollout state shared between the toolset and scoring. The toolset writes the agent's
10
+ live task DB here after each tool call (as a plain dict); the task's reward reads it back
11
+ off `trace.state` to hash against the gold solution."""
12
+
13
+ db: dict | None = None
14
+
15
+
16
+ class GeneralAgentToolsetConfig(vf.ToolsetConfig):
17
+ """Placement for the per-task tool server (defaults to its own host runtime, where the task
18
+ cache lives). The task to serve is fetched per rollout over the `/task` channel."""
general_agent/corpus.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The task corpus: download it on first use via the Harbor CLI, then load individual tasks.
2
+
3
+ The 4,417-task corpus is large (~320 MB) and lives in the `prime-tasks` repo, so it is NOT
4
+ vendored here — `ensure_corpus()` resolves the `general-agent` dataset through the legacy Harbor
5
+ registry in `prime-envs` and downloads it (cached under `~/.cache/harbor/`) on first use.
6
+ `load_task_attrs()` then dynamically imports a single task's `tools.py` (its `TaskDB` / `TaskTools` /
7
+ `verify`), installing a `sys.modules` shim so the raw task files' `from general_agent.tools import ...`
8
+ resolves to this package's base classes unmodified.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import importlib.util
14
+ import json
15
+ import re
16
+ import sys
17
+ import types
18
+ from pathlib import Path
19
+ from typing import Any
20
+
21
+ # `dataset_dir` is the Harbor downloader; it isn't re-exported from the package, so import the module.
22
+ from verifiers.v1.tasksets.harbor.taskset import HarborConfig, dataset_dir
23
+
24
+ # Harbor selectors for the general-agent corpus: the `general-agent` dataset is resolved through the
25
+ # legacy Harbor registry in `prime-envs`, whose entries point at the task files in
26
+ # `prime-tasks`. Override per config for local or PR-branch validation.
27
+ CORPUS_DATASET = "general-agent@2026-06-25"
28
+ CORPUS_REPO = "PrimeIntellect-ai/prime-envs@main"
29
+
30
+ # Matches the `_t<N>` tier suffix on a task name (e.g. `calendar_scheduling_t2`).
31
+ TIER_RE = re.compile(r"_t\d+$")
32
+
33
+
34
+ def ensure_corpus(dataset: str = CORPUS_DATASET, repo: str | None = CORPUS_REPO) -> Path:
35
+ """Download the general-agent Harbor dataset on first use and return the dir holding the
36
+ per-task dirs. Delegates to the Harbor CLI downloader, which caches (under `~/.cache/harbor/`)
37
+ and is process-safe."""
38
+ return dataset_dir(HarborConfig(dataset=dataset, repo=repo))
39
+
40
+
41
+ # --- dynamic task loading -----------------------------------------------------
42
+
43
+ _shim_installed = False
44
+
45
+
46
+ def _install_shim() -> None:
47
+ """Make `general_agent.tools` resolve to this package's base classes, so a task's raw
48
+ `tools.py` (`from general_agent.tools import DB, Tools, tool`) loads unmodified."""
49
+ global _shim_installed
50
+ if _shim_installed:
51
+ return
52
+ from general_agent import tools as _tools
53
+
54
+ pkg = types.ModuleType("general_agent")
55
+ pkg.tools = _tools # type: ignore[attr-defined]
56
+ sys.modules.setdefault("general_agent", pkg)
57
+ sys.modules.setdefault("general_agent.tools", _tools)
58
+ _shim_installed = True
59
+
60
+
61
+ def load_task_attrs(task_dir: Path, *attrs: str) -> tuple[Any | None, ...]:
62
+ """Import a task's `tools.py` once and return the requested attributes."""
63
+ _install_shim()
64
+ path = task_dir / "tools.py"
65
+ prev = sys.dont_write_bytecode
66
+ sys.dont_write_bytecode = True # don't litter the cache with .pyc
67
+ try:
68
+ spec = importlib.util.spec_from_file_location(f"ga_task_{task_dir.name}", path)
69
+ if spec is None or spec.loader is None:
70
+ return (None,) * len(attrs)
71
+ module = importlib.util.module_from_spec(spec)
72
+ spec.loader.exec_module(module)
73
+ return tuple(getattr(module, attr, None) for attr in attrs)
74
+ finally:
75
+ sys.dont_write_bytecode = prev
76
+
77
+
78
+ def gold_check(task_dir: Path) -> tuple[bool, str | None]:
79
+ """Validate a task dir the way the corpus does — returns `(ok, reason)`. The gold chain must
80
+ exist and change the DB hash, and (if `verify` is defined) `verify(initial_db) == 0` and
81
+ `verify(gold_db) == 1`. Shared by the solver's `validate` hook and the synth's reward."""
82
+ if not (task_dir / "db.json").exists():
83
+ return False, "no db.json"
84
+ gold_path = task_dir / "gold.json"
85
+ if not gold_path.exists():
86
+ return False, "no gold.json"
87
+ task_db, task_tools, verify_fn = load_task_attrs(task_dir, "TaskDB", "TaskTools", "verify")
88
+ if task_db is None or task_tools is None:
89
+ return False, "tools.py must define TaskDB and TaskTools"
90
+ initial = task_tools(task_db.load(task_dir / "db.json"))
91
+ gold = task_tools(task_db.load(task_dir / "db.json"))
92
+ try:
93
+ for tool_name, kwargs in json.loads(gold_path.read_text()):
94
+ gold.call_tool(tool_name, **kwargs)
95
+ except Exception as e:
96
+ return False, f"gold replay failed: {type(e).__name__}: {e}"
97
+ if initial.db.get_hash() == gold.db.get_hash():
98
+ return False, "gold solution did not change the DB"
99
+ if verify_fn is None:
100
+ return True, None
101
+ if verify_fn(initial.db) != 0.0:
102
+ return False, "verify(initial_db) != 0.0"
103
+ if verify_fn(gold.db) != 1.0:
104
+ return False, "verify(gold_db) != 1.0"
105
+ return True, None
106
+
107
+
108
+ # --- filtering helpers (mirror the source corpus) -----------------------------
109
+
110
+
111
+ def task_matches(task_name: str, pattern: str) -> bool:
112
+ """Exact task (`calendar_scheduling_t2`) or a whole family (`calendar_scheduling` → all tiers)."""
113
+ if TIER_RE.search(pattern):
114
+ return task_name == pattern
115
+ return TIER_RE.sub("", task_name) == pattern
116
+
117
+
118
+ def matches_pass_rate(metadata: dict, model: str, solver: str, lo: float, hi: float) -> bool:
119
+ """True if a recorded `(model, solver)` pass-rate lies in `[lo, hi]`. The default `(0.0, 1.0)`
120
+ is a no-op; anything narrower excludes tasks lacking a matching measurement."""
121
+ if lo == 0.0 and hi == 1.0:
122
+ return True
123
+ for entry in metadata.get("pass_rates") or []:
124
+ if entry.get("model") == model and entry.get("solver") == solver:
125
+ return lo <= float(entry.get("value", 0.0)) <= hi
126
+ return False
general_agent/servers/__init__.py ADDED
File without changes
general_agent/servers/toolset.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The per-task tool server.
2
+
3
+ Unlike a normal `vf.Toolset` (one fixed set of `@vf.tool` methods), each general-agent task ships
4
+ its own `tools.py` with a different tool set. The server's lifecycle runs `setup_task` (which loads
5
+ that task's `tools.py`) before `_register`, so the tools are known by registration time: `setup_task`
6
+ builds the live `TaskTools`, and `_register` advertises each of its methods over MCP. Every call
7
+ mutates the live `TaskDB`; the mutated DB is pushed onto `self.state` so the task's reward can hash
8
+ it against the gold solution.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import inspect
14
+ import json
15
+ import tempfile
16
+ from pathlib import Path
17
+ from typing import Callable
18
+
19
+ import verifiers.v1 as vf
20
+
21
+ from general_agent.common import GeneralAgentState, GeneralAgentToolsetConfig
22
+ from general_agent.corpus import load_task_attrs
23
+
24
+
25
+ class GeneralAgentToolset(vf.Toolset[GeneralAgentToolsetConfig, GeneralAgentState]):
26
+ TOOL_PREFIX = "tools" # the model sees `tools_<name>` for each of the task's tools
27
+
28
+ async def setup_task(self, task) -> None:
29
+ task_dir = self._task_dir(task)
30
+ task_db, task_tools = load_task_attrs(task_dir, "TaskDB", "TaskTools")
31
+ if task_db is None or task_tools is None:
32
+ raise ValueError(f"tools.py must define TaskDB and TaskTools: {task_dir}")
33
+ self._tools = task_tools(task_db.load(task_dir / "db.json"))
34
+
35
+ @staticmethod
36
+ def _task_dir(task) -> Path:
37
+ """Where this rollout's `tools.py` + `db.json` live in *this* runtime. Own-host: the host
38
+ cache (`task.dir`). Colocated in a sandbox: that host path isn't here (and the corpus repo
39
+ is private), so materialize the files shipped with the task over `/task` into a temp dir."""
40
+ task_dir = Path(task.dir)
41
+ if (task_dir / "tools.py").exists():
42
+ return task_dir
43
+ if not task.files:
44
+ raise RuntimeError(
45
+ f"task dir {task_dir} not present in this runtime and no files were shipped with "
46
+ "the task — the corpus is host-side, so the toolset can't load it here"
47
+ )
48
+ tmp = Path(tempfile.mkdtemp(prefix=f"ga-{task.name}-"))
49
+ for name, content in task.files.items():
50
+ (tmp / name).write_text(content)
51
+ return tmp
52
+
53
+ def register(self, mcp) -> None:
54
+ for name, method in sorted(self._tools.tool_methods.items()):
55
+ mcp.add_tool(
56
+ self._with_state(self._make_tool(name, method)),
57
+ name=name,
58
+ description=(method.__doc__ or "").strip() or None,
59
+ )
60
+
61
+ def _make_tool(self, name: str, method: Callable) -> Callable:
62
+ async def call(**kwargs):
63
+ result = method(**kwargs) # mutates the live TaskDB
64
+ self.state.db = self._tools.db.model_dump(mode="json")
65
+ return result if isinstance(result, str) else json.dumps(result, default=str)
66
+
67
+ call.__name__ = name
68
+ call.__doc__ = method.__doc__
69
+ call.__signature__ = inspect.signature(method).replace(return_annotation=str)
70
+ return call
71
+
72
+
73
+ if __name__ == "__main__":
74
+ GeneralAgentToolset.run()
general_agent/taskset.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """general-agent (solver): multi-turn tool-use tasks scored by DB-hash + `verify(db)`.
2
+
3
+ A self-growing toolbench: each task ships its own `tools.py` (a `TaskDB` world + `@tool` methods that
4
+ mutate it) and a gold tool-call chain. The agent is given the task instruction and the task's tools
5
+ (served per rollout by `servers.toolset.GeneralAgentToolset`); the reward replays the gold chain and
6
+ checks the agent's final DB hash-matches it, OR that the task's `verify(db)` accepts it. The 4,417-task
7
+ corpus is pulled into a local cache on first use (see `corpus.ensure_corpus`), not vendored.
8
+
9
+ Runs under any MCP-tool-capable v1 harness (e.g. `bash`, `default`). Filter the corpus with `--env.taskset.tasks`
10
+ (tasks or whole families), `--env.taskset.min-tier` / `--env.taskset.max-tier`, or a recorded pass-rate band.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import tomllib
17
+ from pathlib import Path
18
+
19
+ import verifiers.v1 as vf
20
+
21
+ from general_agent.common import GeneralAgentState, GeneralAgentToolsetConfig
22
+ from general_agent.corpus import (
23
+ CORPUS_DATASET,
24
+ CORPUS_REPO,
25
+ ensure_corpus,
26
+ gold_check,
27
+ load_task_attrs,
28
+ matches_pass_rate,
29
+ task_matches,
30
+ )
31
+ from general_agent.servers.toolset import GeneralAgentToolset
32
+
33
+
34
+ class GeneralAgentData(vf.TaskData):
35
+ dir: str
36
+ """Absolute path to the task's directory in the local (host) cache."""
37
+ tier: int = 0
38
+ """Difficulty tier (0 = easiest .. 4 = hardest), from the task's `task.toml`."""
39
+ files: dict[str, str] = {}
40
+ """The task's `tools.py` + `db.json` contents, embedded only when the toolset runs in a sandbox
41
+ (colocated or its own non-host runtime) — where the host-side `dir` isn't reachable. The toolset
42
+ materializes these per rollout; empty for the default own-host placement (which reads `dir`)."""
43
+
44
+
45
+ class GeneralAgentTaskConfig(vf.TaskConfig):
46
+ tools: GeneralAgentToolsetConfig = GeneralAgentToolsetConfig()
47
+
48
+
49
+ class GeneralAgentTask(vf.Task[GeneralAgentData, GeneralAgentState, GeneralAgentTaskConfig]):
50
+ @classmethod
51
+ def toolsets(cls, config: GeneralAgentTaskConfig) -> list[vf.Toolset]:
52
+ return [GeneralAgentToolset(config.tools)]
53
+
54
+ @vf.metric
55
+ async def checks(self, trace: vf.Trace) -> dict[str, float]:
56
+ """Compute both checks from one reconstructed agent DB."""
57
+ task_dir = Path(self.data.dir)
58
+ try:
59
+ task_db, task_tools, verify_fn = load_task_attrs(task_dir, "TaskDB", "TaskTools", "verify")
60
+ agent = (
61
+ task_db.model_validate(trace.state.db) if trace.state.db is not None and task_db is not None else None
62
+ )
63
+ except Exception:
64
+ return {"db_hash": 0.0, "verify": 0.0}
65
+
66
+ db_hash = 0.0
67
+ try:
68
+ gold_path = task_dir / "gold.json"
69
+ if agent is not None and task_db is not None and task_tools is not None:
70
+ tools = task_tools(task_db.load(task_dir / "db.json"))
71
+ for tool_name, kwargs in json.loads(gold_path.read_text()):
72
+ tools.call_tool(tool_name, **kwargs)
73
+ db_hash = float(agent.get_hash() == tools.db.get_hash())
74
+ except Exception:
75
+ pass
76
+
77
+ verified = 0.0
78
+ try:
79
+ if agent is not None and verify_fn is not None:
80
+ verified = float(verify_fn(agent))
81
+ except Exception:
82
+ pass
83
+ return {"db_hash": db_hash, "verify": verified}
84
+
85
+ @vf.reward(weight=1.0)
86
+ async def solved(self, trace: vf.Trace) -> float:
87
+ return max(trace.metrics["db_hash"], trace.metrics["verify"])
88
+
89
+ async def validate(self, runtime: vf.Runtime) -> bool:
90
+ """Gold-check (model-free), run by `uv run validate`: the gold chain must change the DB,
91
+ and (if defined) `verify(initial)` is 0 and `verify(gold)` is 1."""
92
+ ok, _ = gold_check(Path(self.data.dir))
93
+ return ok
94
+
95
+
96
+ class GeneralAgentConfig(vf.TasksetConfig):
97
+ dataset: str = CORPUS_DATASET
98
+ """Harbor dataset id for the general-agent corpus, pulled on first use."""
99
+ repo: str | None = CORPUS_REPO
100
+ """Harbor registry selector; override for local or PR-branch validation."""
101
+ tasks: list[str] = []
102
+ """Restrict to these tasks (`calendar_scheduling_t0`) or whole families (`calendar_scheduling`);
103
+ empty = all."""
104
+ min_tier: int | None = None
105
+ max_tier: int | None = None
106
+ """Inclusive tier band (None = unbounded)."""
107
+ pass_rate_model: str = "openai/gpt-5-mini"
108
+ pass_rate_solver: str = "local"
109
+ min_pass_rate: float = 0.0
110
+ max_pass_rate: float = 1.0
111
+ """Keep only tasks whose recorded `(pass_rate_model, pass_rate_solver)` pass-rate is in
112
+ `[min_pass_rate, max_pass_rate]`. The default `[0, 1]` is a no-op (no filtering)."""
113
+ task: GeneralAgentTaskConfig = GeneralAgentTaskConfig()
114
+
115
+
116
+ class GeneralAgentSolverTaskset(vf.Taskset[GeneralAgentTask, GeneralAgentConfig]):
117
+ def load(self) -> list[GeneralAgentTask]:
118
+ root = ensure_corpus(self.config.dataset, self.config.repo)
119
+ # A tool server in a sandbox (colocated, or its own non-host runtime) can't reach the
120
+ # host-side corpus, so ship the two files it loads with each task; own-host reads `dir`.
121
+ tools = self.config.task.tools
122
+ embed = tools.colocated or tools.runtime.type != "subprocess"
123
+ tasks: list[GeneralAgentTask] = []
124
+ # Harbor exports the dataset as `<root>/<dataset>/<task>/`, so tasks sit exactly one level
125
+ # under `root`; globbing at that depth (not `rglob`) ignores any stray nested `task.toml`.
126
+ task_dirs = sorted(p.parent for p in root.glob("*/*/task.toml") if (p.parent / "instruction.md").is_file())
127
+ for task_dir in task_dirs:
128
+ name = task_dir.name
129
+ if self.config.tasks and not any(task_matches(name, t) for t in self.config.tasks):
130
+ continue
131
+ metadata = self._metadata(task_dir)
132
+ tier = metadata.get("tier", 0)
133
+ if self.config.min_tier is not None and tier < self.config.min_tier:
134
+ continue
135
+ if self.config.max_tier is not None and tier > self.config.max_tier:
136
+ continue
137
+ if not matches_pass_rate(
138
+ metadata,
139
+ self.config.pass_rate_model,
140
+ self.config.pass_rate_solver,
141
+ self.config.min_pass_rate,
142
+ self.config.max_pass_rate,
143
+ ):
144
+ continue
145
+ files = (
146
+ {
147
+ "tools.py": (task_dir / "tools.py").read_text(),
148
+ "db.json": (task_dir / "db.json").read_text(),
149
+ }
150
+ if embed
151
+ else {}
152
+ )
153
+ tasks.append(
154
+ GeneralAgentTask(
155
+ GeneralAgentData(
156
+ idx=len(tasks),
157
+ name=name,
158
+ dir=str(task_dir),
159
+ tier=tier,
160
+ prompt=(task_dir / "instruction.md").read_text().strip(),
161
+ files=files,
162
+ ),
163
+ self.config.task,
164
+ )
165
+ )
166
+ if not tasks:
167
+ raise ValueError(f"No tasks in {root} match the configured filters")
168
+ return tasks
169
+
170
+ # --- internals ---
171
+
172
+ def _metadata(self, task_dir: Path) -> dict:
173
+ with open(task_dir / "task.toml", "rb") as f:
174
+ return tomllib.load(f).get("metadata", {})
175
+
176
+
177
+ __all__ = ["GeneralAgentSolverTaskset"]
general_agent/tools.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """`DB` + `Tools` base classes and the `@tool` decorator that every task's `tools.py` builds on.
2
+
3
+ A task's `tools.py` declares `TaskDB(DB)` (its world state), `TaskTools(Tools)` (the `@tool` methods
4
+ the agent calls, which mutate `self.db`) and a module-level `verify(db) -> float`. The corpus's task
5
+ files import these from `general_agent.tools`; the corpus loader installs a `sys.modules` shim so that
6
+ name resolves here (see `corpus._install_shim`), so the raw task files load unmodified.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ from pathlib import Path
14
+ from typing import Any, Callable
15
+
16
+ from pydantic import BaseModel
17
+
18
+ _TOOL_ATTR = "__ga_tool__"
19
+
20
+
21
+ def tool(func: Callable) -> Callable:
22
+ """Mark a `Tools` method as a tool exposed to the agent."""
23
+ setattr(func, _TOOL_ATTR, True)
24
+ return func
25
+
26
+
27
+ class DB(BaseModel):
28
+ """Pydantic base for a task's database — its world state, loaded from `db.json`."""
29
+
30
+ @classmethod
31
+ def load(cls, path: str | Path) -> "DB":
32
+ with open(path) as f:
33
+ return cls.model_validate(json.load(f))
34
+
35
+ def get_hash(self) -> str:
36
+ """First 12 hex of the sha256 of the canonical JSON dump — the exact-match scoring
37
+ primitive (the agent's final DB must hash-equal the gold solution's)."""
38
+ return hashlib.sha256(self.model_dump_json(exclude_none=False).encode()).hexdigest()[:12]
39
+
40
+
41
+ class Tools:
42
+ """Base for a task's tools: owns a mutable `DB` and exposes its `@tool` methods."""
43
+
44
+ def __init__(self, db: DB):
45
+ self.db = db
46
+
47
+ @property
48
+ def tool_methods(self) -> dict[str, Callable]:
49
+ """The `@tool`-decorated methods across the MRO, as bound methods."""
50
+ methods: dict[str, Callable] = {}
51
+ for name in dir(self):
52
+ attr = getattr(type(self), name, None)
53
+ if callable(attr) and getattr(attr, _TOOL_ATTR, False):
54
+ methods[name] = getattr(self, name)
55
+ return methods
56
+
57
+ def call_tool(self, tool_name: str, **kwargs) -> Any:
58
+ methods = self.tool_methods
59
+ if tool_name not in methods:
60
+ raise ValueError(f"Unknown tool: {tool_name}")
61
+ return methods[tool_name](**kwargs)
pyproject.toml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "general-agent"
3
+ version = "0.1.0"
4
+ description = "Self-growing tool-use tasks (solver) scored by DB-hash + verify(db)."
5
+ tags = ["multi-turn", "tool-use", "agentic", "v1"]
6
+ requires-python = ">=3.11"
7
+ dependencies = [
8
+ "verifiers[harbor]>=0.3.1",
9
+ ]
10
+
11
+ [build-system]
12
+ requires = ["hatchling"]
13
+ build-backend = "hatchling.build"
14
+
15
+ [tool.hatch.build.targets.wheel]
16
+ packages = ["general_agent"]