agentenv-framework 0.9.1254__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (312) hide show
  1. agent_env/__init__.py +0 -0
  2. agent_env/a2a_agent/__init__.py +23 -0
  3. agent_env/a2a_agent/a2a_agent.py +600 -0
  4. agent_env/a2a_agent/conversation_store.py +356 -0
  5. agent_env/a2a_agent/object_transfer.py +609 -0
  6. agent_env/a2a_agent/protocol.py +238 -0
  7. agent_env/a2a_agent/store.py +201 -0
  8. agent_env/a2a_agent/validator.py +901 -0
  9. agent_env/artifact/__init__.py +48 -0
  10. agent_env/artifact/artifact.py +74 -0
  11. agent_env/artifact/artifacts/__init__.py +0 -0
  12. agent_env/artifact/artifacts/cli.py +83 -0
  13. agent_env/artifact/artifacts/docker_image.py +457 -0
  14. agent_env/artifact/artifacts/environment.py +89 -0
  15. agent_env/artifact/artifacts/environment_universe.py +156 -0
  16. agent_env/artifact/artifacts/file.py +214 -0
  17. agent_env/artifact/artifacts/file_artifact_universe.py +206 -0
  18. agent_env/artifact/artifacts/skill.py +206 -0
  19. agent_env/artifact/artifacts/vm_image.py +95 -0
  20. agent_env/artifact/ref.py +15 -0
  21. agent_env/artifact/registry.py +251 -0
  22. agent_env/artifact/store.py +295 -0
  23. agent_env/artifact/universe.py +38 -0
  24. agent_env/attribution.py +41 -0
  25. agent_env/bundle/__init__.py +4 -0
  26. agent_env/bundle/_fs.py +128 -0
  27. agent_env/bundle/authoring.py +239 -0
  28. agent_env/bundle/installed.py +175 -0
  29. agent_env/bundle/ledger.py +269 -0
  30. agent_env/bundle/materialize.py +204 -0
  31. agent_env/bundle/parse.py +594 -0
  32. agent_env/bundle/plan.py +414 -0
  33. agent_env/bundle/resolve.py +404 -0
  34. agent_env/bundle/run.py +361 -0
  35. agent_env/cli/__init__.py +69 -0
  36. agent_env/cli/__main__.py +10 -0
  37. agent_env/cli/_installers.py +576 -0
  38. agent_env/cli/_plugin_changes.py +947 -0
  39. agent_env/cli/a2a_agent/__init__.py +22 -0
  40. agent_env/cli/a2a_agent/add_skill.py +97 -0
  41. agent_env/cli/a2a_agent/deploy.py +60 -0
  42. agent_env/cli/a2a_agent/get.py +15 -0
  43. agent_env/cli/a2a_agent/get_instance.py +26 -0
  44. agent_env/cli/a2a_agent/put.py +78 -0
  45. agent_env/cli/a2a_agent/validate.py +56 -0
  46. agent_env/cli/artifact/__init__.py +20 -0
  47. agent_env/cli/artifact/cli.py +83 -0
  48. agent_env/cli/artifact/environment.py +44 -0
  49. agent_env/cli/artifact/environment_universe.py +163 -0
  50. agent_env/cli/artifact/file_artifact_universe.py +281 -0
  51. agent_env/cli/artifact/skill.py +128 -0
  52. agent_env/cli/banner.py +25 -0
  53. agent_env/cli/config.py +263 -0
  54. agent_env/cli/env/__init__.py +31 -0
  55. agent_env/cli/env/deploy.py +112 -0
  56. agent_env/cli/env/gateway.py +57 -0
  57. agent_env/cli/env/get_instance.py +40 -0
  58. agent_env/cli/env/mcp_server.py +410 -0
  59. agent_env/cli/env/multi.py +282 -0
  60. agent_env/cli/env/service_db.py +99 -0
  61. agent_env/cli/env/snapshot.py +35 -0
  62. agent_env/cli/env/state/__init__.py +6 -0
  63. agent_env/cli/env/state/init.py +108 -0
  64. agent_env/cli/env/state/teardown.py +44 -0
  65. agent_env/cli/env/website.py +216 -0
  66. agent_env/cli/env/website_browser.py +67 -0
  67. agent_env/cli/eval/__init__.py +16 -0
  68. agent_env/cli/eval/add_tasks.py +63 -0
  69. agent_env/cli/eval/create.py +49 -0
  70. agent_env/cli/eval/run.py +194 -0
  71. agent_env/cli/identity/__init__.py +5 -0
  72. agent_env/cli/identity/client_identity.py +37 -0
  73. agent_env/cli/plugin.py +438 -0
  74. agent_env/cli/run.py +285 -0
  75. agent_env/cli/task/__init__.py +21 -0
  76. agent_env/cli/task/create.py +109 -0
  77. agent_env/cli/task/get.py +17 -0
  78. agent_env/cli/task/get_instance.py +34 -0
  79. agent_env/cli/task/run.py +615 -0
  80. agent_env/cli/task/validate.py +31 -0
  81. agent_env/cli/up.py +123 -0
  82. agent_env/cli/utils.py +183 -0
  83. agent_env/config/__init__.py +50 -0
  84. agent_env/config/describe.py +1067 -0
  85. agent_env/config/errors.py +13 -0
  86. agent_env/config/loader.py +245 -0
  87. agent_env/config/model.py +154 -0
  88. agent_env/config/paths.py +25 -0
  89. agent_env/config/plugin_tables.py +101 -0
  90. agent_env/config/provenance.py +134 -0
  91. agent_env/config/runtime.py +1064 -0
  92. agent_env/config/snapshot.py +81 -0
  93. agent_env/entity_refs.py +186 -0
  94. agent_env/env/__init__.py +49 -0
  95. agent_env/env/env.py +433 -0
  96. agent_env/env/env_artifact_store.py +87 -0
  97. agent_env/env/envs/__init__.py +7 -0
  98. agent_env/env/envs/_deployment.py +281 -0
  99. agent_env/env/envs/gateway_server.py +32 -0
  100. agent_env/env/envs/mcp_server.py +387 -0
  101. agent_env/env/envs/multi_env.py +780 -0
  102. agent_env/env/envs/service_db/Dockerfile +20 -0
  103. agent_env/env/envs/service_db/Dockerfile.db-mcp +42 -0
  104. agent_env/env/envs/service_db/Dockerfile.db-web +8 -0
  105. agent_env/env/envs/service_db.py +92 -0
  106. agent_env/env/envs/website.py +294 -0
  107. agent_env/env/envs/website_browser/Dockerfile +40 -0
  108. agent_env/env/envs/website_browser/__init__.py +17 -0
  109. agent_env/env/envs/website_browser/entrypoint.sh +13 -0
  110. agent_env/env/gateway/Dockerfile +14 -0
  111. agent_env/env/gateway/__init__.py +37 -0
  112. agent_env/env/gateway/clock.py +184 -0
  113. agent_env/env/gateway/constants.py +190 -0
  114. agent_env/env/gateway/entrypoint.py +156 -0
  115. agent_env/env/gateway/gateway.py +1095 -0
  116. agent_env/env/gateway/get_time.py +60 -0
  117. agent_env/env/gateway/requirements.txt +4 -0
  118. agent_env/env/gateway/triggers.py +1193 -0
  119. agent_env/env/legacy_protocol.py +146 -0
  120. agent_env/env/registry.py +93 -0
  121. agent_env/env/snapshot_store.py +372 -0
  122. agent_env/env/store.py +411 -0
  123. agent_env/eval/__init__.py +14 -0
  124. agent_env/eval/eval.py +68 -0
  125. agent_env/eval/store.py +116 -0
  126. agent_env/examples/hello/README.md +9 -0
  127. agent_env/examples/hello/artifacts/greeting/check.sh +1 -0
  128. agent_env/examples/hello/artifacts/greeting/hello.txt +1 -0
  129. agent_env/examples/hello/tasks/hello.json +10 -0
  130. agent_env/explorer/__init__.py +12 -0
  131. agent_env/explorer/app.py +277 -0
  132. agent_env/explorer/openapi_docs.py +242 -0
  133. agent_env/explorer/plugin.py +95 -0
  134. agent_env/explorer/routers/__init__.py +1 -0
  135. agent_env/explorer/routers/common.py +174 -0
  136. agent_env/explorer/routers/conversations.py +25 -0
  137. agent_env/explorer/routers/objects.py +112 -0
  138. agent_env/explorer/routers/runs.py +475 -0
  139. agent_env/plugins/__init__.py +59 -0
  140. agent_env/plugins/_cli.py +244 -0
  141. agent_env/plugins/_discovery.py +97 -0
  142. agent_env/plugins/_inventory.py +262 -0
  143. agent_env/plugins/_registration.py +268 -0
  144. agent_env/plugins/_report.py +47 -0
  145. agent_env/plugins/_requirements.py +55 -0
  146. agent_env/providers/__init__.py +37 -0
  147. agent_env/providers/env_providers/__init__.py +12 -0
  148. agent_env/providers/env_providers/constants.py +13 -0
  149. agent_env/providers/env_providers/env_gateway_provider.py +1354 -0
  150. agent_env/providers/env_providers/env_provider.py +237 -0
  151. agent_env/providers/env_providers/env_server_provider.py +133 -0
  152. agent_env/providers/env_state/__init__.py +49 -0
  153. agent_env/providers/env_state/env_state_provider.py +554 -0
  154. agent_env/providers/env_state/local_postgres.py +390 -0
  155. agent_env/providers/env_state/store.py +112 -0
  156. agent_env/providers/sandbox_providers/__init__.py +29 -0
  157. agent_env/providers/sandbox_providers/chained_sandbox_provider.py +93 -0
  158. agent_env/providers/sandbox_providers/e2b/__init__.py +6 -0
  159. agent_env/providers/sandbox_providers/e2b/provider.py +376 -0
  160. agent_env/providers/sandbox_providers/e2b/sandbox.py +342 -0
  161. agent_env/providers/sandbox_providers/e2b/template.py +158 -0
  162. agent_env/providers/sandbox_providers/local_sandbox.py +408 -0
  163. agent_env/providers/sandbox_providers/modal_sandbox.py +500 -0
  164. agent_env/providers/sandbox_providers/modal_vm_sandbox.py +466 -0
  165. agent_env/providers/sandbox_providers/sandbox.py +387 -0
  166. agent_env/providers/sandbox_providers/sandbox_provider.py +614 -0
  167. agent_env/py.typed +0 -0
  168. agent_env/runner/__init__.py +16 -0
  169. agent_env/runner/local_runner.py +190 -0
  170. agent_env/runner/runner.py +127 -0
  171. agent_env/runner/store.py +94 -0
  172. agent_env/store/__init__.py +126 -0
  173. agent_env/store/_google.py +68 -0
  174. agent_env/store/base.py +33 -0
  175. agent_env/store/document_store/__init__.py +60 -0
  176. agent_env/store/document_store/document_store.py +519 -0
  177. agent_env/store/document_store/dynamodb_document_store.py +306 -0
  178. agent_env/store/document_store/evaluation.py +199 -0
  179. agent_env/store/document_store/firestore_mongo_document_store.py +242 -0
  180. agent_env/store/document_store/mongo_document_store.py +259 -0
  181. agent_env/store/document_store/sqlite_document_store.py +314 -0
  182. agent_env/store/ids.py +123 -0
  183. agent_env/store/image_store/__init__.py +34 -0
  184. agent_env/store/image_store/ecr_image_store.py +131 -0
  185. agent_env/store/image_store/google_credentials.py +113 -0
  186. agent_env/store/image_store/image_store.py +113 -0
  187. agent_env/store/image_store/local_registry_image_store.py +106 -0
  188. agent_env/store/image_store/oci_registry_credentials.py +196 -0
  189. agent_env/store/local_state.py +27 -0
  190. agent_env/store/object_store/__init__.py +24 -0
  191. agent_env/store/object_store/gcs_object_store.py +415 -0
  192. agent_env/store/object_store/local_object_store.py +143 -0
  193. agent_env/store/object_store/object_store.py +198 -0
  194. agent_env/store/object_store/s3_object_store.py +354 -0
  195. agent_env/store/query.py +112 -0
  196. agent_env/store/routing.py +609 -0
  197. agent_env/store/secret_store/__init__.py +19 -0
  198. agent_env/store/secret_store/aws_secrets_manager_secret_store.py +293 -0
  199. agent_env/store/secret_store/gcp_secret_manager_secret_store.py +319 -0
  200. agent_env/store/secret_store/local_secret_store.py +47 -0
  201. agent_env/store/secret_store/secret_store.py +19 -0
  202. agent_env/task/__init__.py +27 -0
  203. agent_env/task/interrupts.py +109 -0
  204. agent_env/task/registry.py +27 -0
  205. agent_env/task/step_journal.py +99 -0
  206. agent_env/task/store.py +940 -0
  207. agent_env/task/task.py +815 -0
  208. agent_env/task/teardown.py +142 -0
  209. agent_env/task_step/__init__.py +47 -0
  210. agent_env/task_step/context.py +195 -0
  211. agent_env/task_step/context_ops.py +224 -0
  212. agent_env/task_step/registry.py +182 -0
  213. agent_env/task_step/review_store.py +118 -0
  214. agent_env/task_step/snapshot_utils/__init__.py +2 -0
  215. agent_env/task_step/snapshot_utils/agent_state_capture.py +261 -0
  216. agent_env/task_step/snapshot_utils/snapshot_series.py +631 -0
  217. agent_env/task_step/store.py +129 -0
  218. agent_env/task_step/task_step.py +173 -0
  219. agent_env/task_step/task_steps/__init__.py +27 -0
  220. agent_env/task_step/task_steps/a2a_agent_validator/__init__.py +31 -0
  221. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/README.md +158 -0
  222. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.m4a +0 -0
  223. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp3 +0 -0
  224. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp4 +0 -0
  225. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.ogg +0 -0
  226. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.wav +0 -0
  227. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/document.pdf +0 -0
  228. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.gif +0 -0
  229. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.jpg +0 -0
  230. agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.png +0 -0
  231. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_card.py +103 -0
  232. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_config_identity.py +69 -0
  233. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_mcp.py +178 -0
  234. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_core_protocol.py +67 -0
  235. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_install.py +115 -0
  236. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution.py +124 -0
  237. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution_runtime.py +173 -0
  238. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_modalities.py +270 -0
  239. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_peer_agents.py +102 -0
  240. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_role.py +151 -0
  241. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_skill_config.py +194 -0
  242. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_snapshot.py +111 -0
  243. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_system_prompt.py +215 -0
  244. agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_trajectory.py +164 -0
  245. agent_env/task_step/task_steps/add_skills.py +240 -0
  246. agent_env/task_step/task_steps/apply_server_config.py +288 -0
  247. agent_env/task_step/task_steps/collect_artifacts.py +940 -0
  248. agent_env/task_step/task_steps/deploy_agent.py +626 -0
  249. agent_env/task_step/task_steps/deploy_env.py +197 -0
  250. agent_env/task_step/task_steps/deploy_human_agent.py +100 -0
  251. agent_env/task_step/task_steps/deploy_sandbox.py +170 -0
  252. agent_env/task_step/task_steps/env_card_validator/__init__.py +4 -0
  253. agent_env/task_step/task_steps/env_card_validator/verify_env_card.py +109 -0
  254. agent_env/task_step/task_steps/env_card_validator/verify_env_core_protocol.py +108 -0
  255. agent_env/task_step/task_steps/install_agent.py +376 -0
  256. agent_env/task_step/task_steps/load_artifact.py +775 -0
  257. agent_env/task_step/task_steps/mcp_cli_builder/__init__.py +4 -0
  258. agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py +201 -0
  259. agent_env/task_step/task_steps/mcp_cli_builder/codegen.py +627 -0
  260. agent_env/task_step/task_steps/mcp_env_validator/__init__.py +44 -0
  261. agent_env/task_step/task_steps/mcp_env_validator/validation_gate_aggregator.py +102 -0
  262. agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_env_assessment.py +78 -0
  263. agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_tool_schema.py +152 -0
  264. agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py +486 -0
  265. agent_env/task_step/task_steps/modify_env_tool_access.py +80 -0
  266. agent_env/task_step/task_steps/multienv_validator/__init__.py +3 -0
  267. agent_env/task_step/task_steps/multienv_validator/combine_universe_verdicts.py +107 -0
  268. agent_env/task_step/task_steps/multienv_validator/universe_comparison.py +253 -0
  269. agent_env/task_step/task_steps/multienv_validator/verify_universe_agent_judge.py +180 -0
  270. agent_env/task_step/task_steps/multienv_validator/verify_universe_roundtrip.py +241 -0
  271. agent_env/task_step/task_steps/peer_agents.py +92 -0
  272. agent_env/task_step/task_steps/prompt_agent.py +900 -0
  273. agent_env/task_step/task_steps/register_agent_triggers.py +113 -0
  274. agent_env/task_step/task_steps/register_env_triggers.py +97 -0
  275. agent_env/task_step/task_steps/reset_env.py +71 -0
  276. agent_env/task_step/task_steps/review.py +152 -0
  277. agent_env/task_step/task_steps/run_code.py +461 -0
  278. agent_env/task_step/task_steps/run_code_runner.py +52 -0
  279. agent_env/task_step/task_steps/run_docker_container.py +380 -0
  280. agent_env/task_step/task_steps/sandbox_utils/__init__.py +0 -0
  281. agent_env/task_step/task_steps/sandbox_utils/sandbox_utils.py +79 -0
  282. agent_env/task_step/task_steps/snapshot_agent_state.py +205 -0
  283. agent_env/task_step/task_steps/snapshot_env.py +637 -0
  284. agent_env/task_step/task_steps/sync_env_clock.py +132 -0
  285. agent_env/task_step/task_steps/teardown_sandboxes.py +170 -0
  286. agent_env/task_step/task_steps/verifiers/__init__.py +23 -0
  287. agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py +166 -0
  288. agent_env/task_step/task_steps/verifiers/aggregate_verifiers.py +90 -0
  289. agent_env/task_step/task_steps/verifiers/env_outcome_verifier.py +127 -0
  290. agent_env/task_step/task_steps/verifiers/judge_utils/__init__.py +2 -0
  291. agent_env/task_step/task_steps/verifiers/judge_utils/frame_selection.py +377 -0
  292. agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py +1293 -0
  293. agent_env/task_step/task_steps/verifiers/judge_utils/trajectory_filter.py +514 -0
  294. agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +1318 -0
  295. agent_env/task_step/task_steps/verifiers/run_container_unit_tests_verifier.py +434 -0
  296. agent_env/task_step/task_steps/verifiers/scoring.py +40 -0
  297. agent_env/task_step/task_steps/verifiers/verify_sandbox.py +308 -0
  298. agent_env/task_step/thread_work.py +61 -0
  299. agent_env/utils/__init__.py +0 -0
  300. agent_env/utils/card_naming.py +108 -0
  301. agent_env/utils/deprecation.py +109 -0
  302. agent_env/utils/docker_build.py +29 -0
  303. agent_env/utils/exec_retry.py +77 -0
  304. agent_env/utils/litellm_attribution.py +59 -0
  305. agent_env/utils/paths.py +20 -0
  306. agentenv_framework-0.9.1254.dist-info/METADATA +394 -0
  307. agentenv_framework-0.9.1254.dist-info/RECORD +312 -0
  308. agentenv_framework-0.9.1254.dist-info/WHEEL +4 -0
  309. agentenv_framework-0.9.1254.dist-info/entry_points.txt +5 -0
  310. agentenv_framework-0.9.1254.dist-info/licenses/LICENSE +202 -0
  311. agentenv_framework-0.9.1254.dist-info/licenses/NOTICE +4 -0
  312. agentenv_framework-0.9.1254.dist-info/licenses/THIRD_PARTY_NOTICES.md +7665 -0
@@ -0,0 +1,615 @@
1
+ """Run a stored task."""
2
+
3
+ import asyncio
4
+ import copy
5
+ import csv
6
+ import json
7
+ import os
8
+ import textwrap
9
+ from uuid import uuid4
10
+
11
+ import click
12
+
13
+ from agent_env.cli.banner import print_banner
14
+ from agent_env.cli.identity import get_agent_env_client_id
15
+ from agent_env.store.ids import fs_safe
16
+
17
+
18
+ _print_lock = asyncio.Lock()
19
+
20
+
21
+ def _indent(text: str, prefix: str = " ") -> str:
22
+ """Indent each line of text."""
23
+ return textwrap.indent(text, prefix)
24
+
25
+
26
+ def _format_env(env) -> str:
27
+ from agent_env.env.env import DeployedGatewayEnv, DeployedSandboxEnv
28
+
29
+ fronted = isinstance(env, DeployedGatewayEnv) # a record without a gateway has none of its URLs
30
+ lines = [
31
+ "deployed-env:",
32
+ f" instance_id: {env.instance_id}",
33
+ f" env_id: {env.env_id}",
34
+ f" env_version: {env.env_version}",
35
+ *([f" gateway_url: {env.gateway_url}"] if fronted else []),
36
+ f" mcp_url: {env.mcp_url}",
37
+ *([f" db_web_url: {env.db_web_url}", f" db_mcp_url: {env.db_mcp_url}"] if fronted else []),
38
+ ]
39
+ if isinstance(env, DeployedSandboxEnv): # an env outside our sandboxes has no sandbox to name
40
+ lines.append(f" sandbox_id: {env.sandbox_id}")
41
+ if env.sandbox_type:
42
+ lines.append(f" sandbox_type: {env.sandbox_type}")
43
+ if fronted and env.vnc_url:
44
+ lines.append(f" vnc_url: {env.vnc_url}")
45
+ return "\n".join(lines)
46
+
47
+
48
+ def _format_agent(agent) -> str:
49
+ lines = [
50
+ "deployed-agent:",
51
+ f" agent_name: {agent.agent_name}",
52
+ f" api_url: {agent.api_url}",
53
+ ]
54
+ if agent.a2a_url:
55
+ lines.append(f" a2a_url: {agent.a2a_url}")
56
+ if agent.sandbox_id:
57
+ lines.append(f" sandbox_id: {agent.sandbox_id}")
58
+ if agent.sandbox_type:
59
+ lines.append(f" sandbox_type: {agent.sandbox_type}")
60
+ if agent.a2a_card:
61
+ lines.append(f" agent_card: {json.dumps(agent.a2a_card, indent=2)}")
62
+ return "\n".join(lines)
63
+
64
+
65
+ def _format_tool_access_change(change: dict) -> str:
66
+ state = change.get("role_state_after") or {}
67
+ disabled = state.get("disabled") or []
68
+ allowed = state.get("allowed") or []
69
+ requested = change.get("tools_requested") or []
70
+ lines = [
71
+ "tool-access-change:",
72
+ f" env_id: {change.get('env_id')}",
73
+ f" action: {change.get('action')}",
74
+ f" role: {change.get('role')}",
75
+ f" tools_requested ({len(requested)}): {requested if len(requested) <= 5 else requested[:5] + ['...']}",
76
+ f" role_state_after.disabled ({len(disabled)}): {disabled if len(disabled) <= 5 else disabled[:5] + ['...']}",
77
+ f" role_state_after.allowed ({len(allowed)}): {allowed if len(allowed) <= 5 else allowed[:5] + ['...']}",
78
+ ]
79
+ return "\n".join(lines)
80
+
81
+
82
+ def _format_server_config_changes(changes: list[dict]) -> str:
83
+ lines = [f"server-config-applied ({len(changes)}):"]
84
+ for c in changes:
85
+ lines.append(f" service={c.get('service')} uri={c.get('uri')} args={c.get('args')}")
86
+ return "\n".join(lines)
87
+
88
+
89
+ def _format_prompt_response(pr) -> str:
90
+ indented_response = _indent(pr.response, " ")
91
+ lines = [
92
+ "prompt-response:",
93
+ f" prompt_id: {pr.prompt_id}",
94
+ " response: |",
95
+ indented_response,
96
+ ]
97
+ if pr.agent_trajectory_s3_uri:
98
+ lines.append(f" agent_trajectory_s3_uri: {pr.agent_trajectory_s3_uri}")
99
+ if pr.agent_trajectory_s3_prefix:
100
+ lines.append(f" agent_trajectory_s3_prefix: {pr.agent_trajectory_s3_prefix}")
101
+ if pr.compact_trajectory_s3_uri:
102
+ lines.append(f" compact_trajectory_s3_uri: {pr.compact_trajectory_s3_uri}")
103
+ if pr.agent_trajectory_file_path:
104
+ lines.append(f" agent_trajectory_file_path: {pr.agent_trajectory_file_path}")
105
+ if pr.tool_call_count is not None:
106
+ lines.append(f" tool_call_count: {pr.tool_call_count}")
107
+ return "\n".join(lines)
108
+
109
+
110
+ def _format_verification_results(results) -> str:
111
+ indented = _indent(json.dumps(results, indent=2), " ")
112
+ lines = [
113
+ "verification-results: |",
114
+ indented,
115
+ ]
116
+ return "\n".join(lines)
117
+
118
+
119
+ def _format_snapshot_capture(snap: dict) -> str:
120
+ lines = [
121
+ "agent-snapshot:",
122
+ f" artifact_id: {snap.get('id')}",
123
+ f" artifact_version: {snap.get('version')}",
124
+ f" bundle_object_url: {snap.get('bundle_object_url') or snap.get('bundle_s3_url')}",
125
+ f" source_agent_name: {snap.get('source_agent_name')}",
126
+ f" source_context_id: {snap.get('source_context_id')}",
127
+ ]
128
+ return "\n".join(lines)
129
+
130
+
131
+ def _format_loaded_snapshot(load: dict) -> str:
132
+ lines = [
133
+ "loaded-snapshot:",
134
+ f" context_id: {load.get('context_id')}",
135
+ f" source_artifact_id: {load.get('source_artifact_id')}",
136
+ f" source_artifact_version: {load.get('source_artifact_version')}",
137
+ ]
138
+ return "\n".join(lines)
139
+
140
+
141
+ # Per-step output attribution via the step type + the `[-1]` trick.
142
+ #
143
+ # Invariant: every step that appends to context.deployed_envs / .deployed_agents
144
+ # / .prompt_responses does so as the final synchronous op in execute() — no
145
+ # await after the append. Under asyncio, that guarantees `context.<bucket>[-1]`
146
+ # at the moment on_step_complete fires is *this* step's item, even under DAG
147
+ # parallelism (no yield between the append and the callback in the same
148
+ # coroutine). Verifier output is duck-typed via `verifier_id`.
149
+ def _step_output_lines(step, context) -> list[str]:
150
+ if step.type == "deploy_env" and context.deployed_envs:
151
+ return [_format_env(context.deployed_envs[-1])]
152
+ if step.type == "deploy_agent" and context.deployed_agents:
153
+ agent = context.deployed_agents[-1]
154
+ lines = [_format_agent(agent)]
155
+ # If this deploy step also loaded a snapshot, surface its provenance.
156
+ loaded = context.metadata.get("agent_loaded_snapshots") or []
157
+ match = next(
158
+ (e for e in reversed(loaded) if e.get("agent_name") == agent.agent_name),
159
+ None,
160
+ )
161
+ if match:
162
+ lines.append(_format_loaded_snapshot(match))
163
+ return lines
164
+ if step.type == "prompt_agent" and context.prompt_responses:
165
+ return [_format_prompt_response(context.prompt_responses[-1])]
166
+ if step.type == "snapshot_agent_state":
167
+ snapshots = context.metadata.get("agent_snapshots") or []
168
+ if snapshots:
169
+ return [_format_snapshot_capture(snapshots[-1])]
170
+ if step.type == "modify_env_tool_access":
171
+ changes = context.metadata.get("tool_access_changes") or []
172
+ match = next((c for c in reversed(changes) if c.get("step_id") == step.id), None)
173
+ if match:
174
+ return [_format_tool_access_change(match)]
175
+ if step.type == "apply_server_config":
176
+ changes = [c for c in (context.metadata.get("server_config_changes") or []) if c.get("step_id") == step.id]
177
+ if changes:
178
+ return [_format_server_config_changes(changes)]
179
+ vid = getattr(step, "verifier_id", None)
180
+ if vid:
181
+ vdata = context.metadata.get("verifications", {}).get(vid)
182
+ if vdata:
183
+ return _format_verifier_output(vid, vdata)
184
+ return []
185
+
186
+
187
+ def _format_verifier_output(vid: str, vdata: dict) -> list[str]:
188
+ lines: list[str] = []
189
+ compact_uri = vdata.get("compact_trajectory_s3_uri")
190
+ if compact_uri:
191
+ lines.append(f"compact_trajectory_s3_uri (verifier_id={vid}): {compact_uri}")
192
+ judge_uri = vdata.get("judge_trajectory_s3_uri")
193
+ if judge_uri:
194
+ lines.append(f"judge_trajectory_s3_uri (verifier_id={vid}): {judge_uri}")
195
+ command = vdata.get("command")
196
+ if command is not None:
197
+ lines.append(f"command (verifier_id={vid}): {command}")
198
+ exit_code = vdata.get("exit_code")
199
+ if exit_code is not None:
200
+ timed_out = vdata.get("timed_out", False)
201
+ lines.append(f"exit_code (verifier_id={vid}): {exit_code} (timed_out={timed_out})")
202
+ stdout_artifact = vdata.get("stdout_artifact")
203
+ if stdout_artifact:
204
+ lines.append(
205
+ f"stdout_artifact (verifier_id={vid}): "
206
+ f"{stdout_artifact.get('id')} v{stdout_artifact.get('version')} -> {stdout_artifact.get('s3_url')}"
207
+ )
208
+ stdout_head = vdata.get("stdout_head")
209
+ if stdout_head:
210
+ lines.append(f"stdout_head (verifier_id={vid}):")
211
+ for line in stdout_head.splitlines():
212
+ lines.append(f" {line}")
213
+ stderr_artifact = vdata.get("stderr_artifact")
214
+ if stderr_artifact:
215
+ lines.append(
216
+ f"stderr_artifact (verifier_id={vid}): "
217
+ f"{stderr_artifact.get('id')} v{stderr_artifact.get('version')} -> {stderr_artifact.get('s3_url')}"
218
+ )
219
+ stderr_head = vdata.get("stderr_head")
220
+ if stderr_head:
221
+ lines.append(f"stderr_head (verifier_id={vid}):")
222
+ for line in stderr_head.splitlines():
223
+ lines.append(f" {line}")
224
+ extracted = vdata.get("extracted_files")
225
+ if extracted:
226
+ lines.append(f"extracted_files (verifier_id={vid}):")
227
+ for path, parsed in extracted.items():
228
+ if isinstance(parsed, dict):
229
+ lines.append(f" {path}: {json.dumps(parsed, default=str)[:600]}")
230
+ elif parsed is None:
231
+ lines.append(f" {path}: <unavailable>")
232
+ else:
233
+ lines.append(f" {path}: {str(parsed)[:600]}")
234
+ results = vdata.get("results")
235
+ if results is not None:
236
+ lines.append(f"verification (verifier_id={vid}):")
237
+ lines.append(_format_verification_results(results))
238
+ score = vdata.get("score")
239
+ if score is not None:
240
+ lines.append(f"score (verifier_id={vid}): {score}")
241
+ return lines
242
+
243
+
244
+ # -- Single-run (k=1) callbacks: verbose output, no prefix --
245
+
246
+ async def _log_step_start(i, total, step, context):
247
+ async with _print_lock:
248
+ if i == 0 and context.instance_id:
249
+ click.echo(click.style(f"Task instance: {context.instance_id}", fg="blue"))
250
+ if i > 0:
251
+ click.echo()
252
+ click.echo(click.style(
253
+ f"Running step [{i+1}/{total}]: {step.type} (id={step.id})...",
254
+ fg="yellow",
255
+ ))
256
+
257
+
258
+ async def _log_step_complete(i, total, step, context, duration):
259
+ async with _print_lock:
260
+ click.echo(click.style(
261
+ f"Completed step [{i+1}/{total}]: {step.type} (id={step.id}) [{duration:.1f}s]",
262
+ fg="green",
263
+ ))
264
+ for line in _step_output_lines(step, context):
265
+ click.echo(click.style(line, fg="green"))
266
+
267
+
268
+ # -- Parallel-run (k>1) callbacks: compact output with [run N] prefix --
269
+
270
+ def _make_parallel_callbacks(run_index):
271
+ """Return (on_step_start, on_step_complete) callbacks for a parallel run."""
272
+ tag = f"[run {run_index}]"
273
+
274
+ async def on_step_start(i, total, step, context):
275
+ async with _print_lock:
276
+ if i == 0 and context.instance_id:
277
+ click.echo(click.style(f"{tag} Task instance: {context.instance_id}", fg="blue"))
278
+ click.echo(click.style(
279
+ f"{tag} Running step [{i+1}/{total}]: {step.type} (id={step.id})...",
280
+ fg="yellow",
281
+ ))
282
+
283
+ async def on_step_complete(i, total, step, context, duration):
284
+ async with _print_lock:
285
+ click.echo(click.style(
286
+ f"{tag} Completed step [{i+1}/{total}]: {step.type} (id={step.id}) [{duration:.1f}s]",
287
+ fg="green",
288
+ ))
289
+ vid = getattr(step, "verifier_id", None)
290
+ if vid:
291
+ vdata = context.metadata.get("verifications", {}).get(vid, {})
292
+ score = vdata.get("score")
293
+ if score is not None:
294
+ click.echo(click.style(f"{tag} score (verifier_id={vid}): {score}", fg="green"))
295
+
296
+ return on_step_start, on_step_complete
297
+
298
+
299
+ def _write_context(context, task_id, output_dir, prefix=""):
300
+ """Write context JSON to output_dir and print the path."""
301
+ os.makedirs(output_dir, exist_ok=True)
302
+ filename = f"{fs_safe(task_id)}_{uuid4().hex[:8]}.json"
303
+ output_path = os.path.join(output_dir, filename)
304
+ with open(output_path, "w") as f:
305
+ json.dump(context.to_safe_dict(), f, indent=2)
306
+ click.echo(click.style(f"{prefix}Task context written to: {output_path}", fg="blue"))
307
+
308
+
309
+ def _stamp_agent_env_client_metadata(context_metadata: dict, client_id: str | None) -> None:
310
+ if client_id:
311
+ context_metadata.setdefault("agent_env_hub", {}).setdefault("caller", client_id)
312
+
313
+
314
+ # Step types whose execution path makes LiteLLM calls (directly or via a
315
+ # deployed agent that consumes LITELLM_* env vars). Used to decide whether
316
+ # the cost-attribution banner is relevant for a given task.
317
+ _LITELLM_USING_STEP_TYPES: frozenset[str] = frozenset({
318
+ "deploy_agent",
319
+ "prompt_agent",
320
+ "rubrics_verifier",
321
+ })
322
+
323
+
324
+ def _task_uses_litellm(task) -> bool:
325
+ """True if any of the task's steps are known to make LiteLLM calls."""
326
+ return any(getattr(step, "type", None) in _LITELLM_USING_STEP_TYPES for step in task.steps)
327
+
328
+
329
+ def _warn_missing_cost_attribution(
330
+ project_id: str | None,
331
+ task,
332
+ ) -> None:
333
+ """Yellow CLI banner when `--project-id` is missing on a LiteLLM task.
334
+
335
+ Project ID is the primary attribution dimension (it becomes the
336
+ LiteLLM `user` field that spend reporting joins on to derive the
337
+ customer). Skipped when the task has no LiteLLM-using
338
+ steps. Never blocks the run.
339
+ """
340
+ if project_id:
341
+ return
342
+ if not _task_uses_litellm(task):
343
+ return
344
+ click.echo(click.style(
345
+ "⚠ LiteLLM cost attribution is incomplete: --project-id not set.",
346
+ fg="yellow", bold=True,
347
+ ))
348
+ click.echo(click.style(
349
+ " Runs will still start, but spend won't be tagged to a "
350
+ "project.",
351
+ fg="yellow",
352
+ ))
353
+ click.echo(click.style(
354
+ " Pass --project-id <project-id> on your next run so the "
355
+ "cost shows up in your team's budget.",
356
+ fg="yellow",
357
+ ))
358
+ click.echo()
359
+
360
+
361
+ async def _run_single(task, run_index, task_id, output_dir, agent_model=None, agent_artifact_id=None, start_step=0, context=None):
362
+ """Execute a single parallel run."""
363
+ tag = f"[run {run_index}] "
364
+ on_start, on_complete = _make_parallel_callbacks(run_index)
365
+ context = await task.run(on_step_start=on_start, on_step_complete=on_complete, agent_model=agent_model, agent_artifact_id=agent_artifact_id, start_step=start_step, context=context)
366
+ if output_dir:
367
+ _write_context(context, task_id, output_dir, prefix=tag)
368
+ return context
369
+
370
+
371
+ @click.command()
372
+ @click.option("--id", "task_id", required=True, help="Task id")
373
+ @click.option("--version", "task_version", default=None, type=int, help="Task version (defaults to latest)")
374
+ @click.option("--output-dir", default=None, type=click.Path(file_okay=False), help="Directory to write context JSON output")
375
+ @click.option("--k", "k", default=1, type=int, help="Number of parallel task runs")
376
+ @click.option("--agent-model", default=None, type=str, help="Override the model used by prompt_agent steps")
377
+ @click.option("--agent-artifact-id", default=None, type=str, help="Override the agent image artifact for deploy_agent steps")
378
+ @click.option("--start-step", default=0, type=int, help="0-based step index to start execution from")
379
+ @click.option("--context-json", default=None, type=click.Path(exists=True, dir_okay=False), help="Path to a JSON file to seed the TaskStepContext")
380
+ @click.option("--litellm-api-key", default=None, type=str, help="Override LITELLM_API_KEY for this run")
381
+ @click.option("--judge-litellm-api-key", default=None, type=str, help="Override LITELLM_API_KEY used by rubrics_verifier judge agents (falls back to --litellm-api-key, then to config secret)")
382
+ @click.option("--apply-trajectory-filter/--no-trajectory-filter", "apply_trajectory_filter", default=None, help="Force trajectory filtering on/off for rubrics_verifier (overrides the step's trajectory_filter setting)")
383
+ @click.option("--a2a-agent-id", default=None, type=str, help="Override A2A agent id for deploy_agent steps")
384
+ @click.option("--agent-sandbox", default=None,
385
+ help="Override agent sandbox backend(s) for deploy_agent steps; comma-separated for fallback chain (e.g. 'modal,local')")
386
+ @click.option("--project-id", "project_id", default=None, type=str,
387
+ help="Project id for LiteLLM cost attribution. Forwarded as the `user` field on every LLM call and as `projectId:<id>` in `metadata.tags`. Optional, but spend won't be attributed to a project without it.")
388
+ @click.option("--env-sandbox", default=None,
389
+ help="Override env sandbox backend(s) for deploy_env steps; comma-separated for fallback chain (e.g. 'modal,local')")
390
+ @click.option("--gateway-env-id", default=None, type=str,
391
+ help="Override default_gateway_env_id (required when --env-sandbox=modal until the default gateway image is rebuilt)")
392
+ @click.option("--service-db-env-id", default=None, type=str,
393
+ help="Override default_service_db_env_id (on Modal its images must be in the configured image store)")
394
+ @click.option("--env-state-type", default=None, type=str,
395
+ help="Override the env state type for deploy_env steps")
396
+ @click.option("--env-state-instance-id", default=None, type=str,
397
+ help="Attach env to an existing EnvStateInstance")
398
+ def run(task_id: str, task_version: int | None, output_dir: str | None, k: int, agent_model: str | None, agent_artifact_id: str | None, start_step: int, context_json: str | None, litellm_api_key: str | None, judge_litellm_api_key: str | None, apply_trajectory_filter: bool | None, a2a_agent_id: str | None, agent_sandbox: str | None, project_id: str | None, env_sandbox: str | None, gateway_env_id: str | None, service_db_env_id: str | None, env_state_type: str | None, env_state_instance_id: str | None):
399
+ """Run a task by executing its steps sequentially."""
400
+ if k < 1:
401
+ raise click.BadParameter("must be at least 1", param_hint="'--k'")
402
+
403
+ from agent_env.config import get_config
404
+ from agent_env.task import Task
405
+ from agent_env.task_step.context import TaskStepContext
406
+
407
+ if gateway_env_id:
408
+ get_config().default_gateway_env_id = gateway_env_id
409
+ click.echo(f"Override default_gateway_env_id: {gateway_env_id}")
410
+ if service_db_env_id:
411
+ get_config().default_service_db_env_id = service_db_env_id
412
+ click.echo(f"Override default_service_db_env_id: {service_db_env_id}")
413
+ if output_dir is None:
414
+ output_dir = f"/tmp/taskid={fs_safe(task_id)}-run{uuid4().hex[:6]}"
415
+ if context_json:
416
+ with open(context_json) as f:
417
+ initial_context = TaskStepContext.from_dict(json.load(f))
418
+ click.echo(f"Loaded context from {context_json}")
419
+ else:
420
+ initial_context = TaskStepContext()
421
+ client_id = get_agent_env_client_id()
422
+ _stamp_agent_env_client_metadata(initial_context.metadata, client_id)
423
+ initial_context.metadata.setdefault("run_group_id", uuid4().hex)
424
+ if litellm_api_key:
425
+ initial_context.metadata.setdefault("user_overrides", {})["litellm_api_key"] = litellm_api_key
426
+ if judge_litellm_api_key:
427
+ initial_context.metadata.setdefault("user_overrides", {})["judge_litellm_api_key"] = judge_litellm_api_key
428
+ if apply_trajectory_filter is not None:
429
+ initial_context.metadata.setdefault("user_overrides", {})["apply_trajectory_filter"] = apply_trajectory_filter
430
+ if a2a_agent_id:
431
+ initial_context.metadata.setdefault("user_overrides", {})["a2a_agent_id"] = a2a_agent_id
432
+ if agent_sandbox:
433
+ initial_context.metadata.setdefault("user_overrides", {})["agent_sandbox"] = agent_sandbox
434
+ if env_sandbox:
435
+ initial_context.metadata.setdefault("user_overrides", {})["env_sandbox"] = env_sandbox
436
+ if env_state_type:
437
+ initial_context.metadata.setdefault("user_overrides", {})["env_state_type"] = env_state_type
438
+ if env_state_instance_id:
439
+ initial_context.metadata.setdefault("user_overrides", {})["env_state_instance_id"] = env_state_instance_id
440
+ initial_context.metadata["task_id"] = task_id
441
+ if project_id:
442
+ initial_context.metadata["project_id"] = project_id
443
+
444
+ click.echo(f"Fetching task: id={task_id} version={task_version or 'latest'}...")
445
+ task = Task.get(task_id, version=task_version)
446
+ click.echo(f"Found task: id={task.id} version={task.version} steps={len(task.steps)}")
447
+
448
+ print_banner()
449
+ _warn_missing_cost_attribution(project_id, task)
450
+
451
+ if k > 1:
452
+ # Parallel runs: compact output with [run N] prefixes
453
+ click.echo(click.style(f"Running {k} task runs in parallel...", fg="blue"))
454
+ click.echo()
455
+
456
+ async def _run_all():
457
+ coros = [_run_single(task, i, task_id, output_dir, agent_model=agent_model, agent_artifact_id=agent_artifact_id, start_step=start_step, context=copy.deepcopy(initial_context) if initial_context else None) for i in range(1, k + 1)]
458
+ return await asyncio.gather(*coros, return_exceptions=True)
459
+
460
+ results = asyncio.run(_run_all())
461
+
462
+ click.echo()
463
+ failures = [(i, r) for i, r in enumerate(results, 1) if isinstance(r, BaseException)]
464
+ if failures:
465
+ for run_index, exc in failures:
466
+ click.echo(click.style(f"[run {run_index}] FAILED: {exc}", fg="red"))
467
+ click.echo(click.style(
468
+ f"{len(results) - len(failures)}/{k} runs completed, {len(failures)}/{k} failed.",
469
+ fg="red",
470
+ ))
471
+ raise SystemExit(1)
472
+ else:
473
+ click.echo(click.style(f"All {k} runs completed!", fg="blue"))
474
+ else:
475
+ # Single run: verbose output
476
+ context = asyncio.run(task.run(
477
+ on_step_start=_log_step_start,
478
+ on_step_complete=_log_step_complete,
479
+ agent_model=agent_model,
480
+ agent_artifact_id=agent_artifact_id,
481
+ start_step=start_step,
482
+ context=initial_context,
483
+ ))
484
+
485
+ click.echo()
486
+ click.echo(click.style("Task completed!", fg="blue"))
487
+
488
+ _write_context(context, task_id, output_dir)
489
+
490
+
491
+ @click.command("run-batch")
492
+ @click.option("--id", "task_id", required=True, help="Task id")
493
+ @click.option("--version", "task_version", default=None, type=int, help="Task version (defaults to latest)")
494
+ @click.option("--seeds", required=True, type=click.Path(exists=True, dir_okay=False), help="CSV file with one row per seed")
495
+ @click.option("--concurrency", default=5, type=int, help="Max parallel task runs")
496
+ @click.option("--output-dir", default=None, type=click.Path(file_okay=False), help="Directory to write context JSON outputs")
497
+ @click.option("--agent-model", default=None, type=str, help="Override the model used by prompt_agent steps")
498
+ @click.option("--agent-artifact-id", default=None, type=str, help="Override the agent image artifact for deploy_agent steps")
499
+ @click.option("--litellm-api-key", default=None, type=str, help="Override LITELLM_API_KEY for all runs")
500
+ @click.option("--judge-litellm-api-key", default=None, type=str, help="Override LITELLM_API_KEY used by rubrics_verifier judge agents")
501
+ @click.option("--apply-trajectory-filter/--no-trajectory-filter", "apply_trajectory_filter", default=None, help="Force trajectory filtering on/off for rubrics_verifier")
502
+ @click.option("--agent-sandbox", default=None,
503
+ help="Override agent sandbox backend(s) for deploy_agent steps; comma-separated for fallback chain (e.g. 'modal,local')")
504
+ @click.option("--env-sandbox", default=None,
505
+ help="Override env sandbox backend(s) for deploy_env steps; comma-separated for fallback chain (e.g. 'modal,local')")
506
+ @click.option("--project-id", "project_id", default=None, type=str,
507
+ help="Project id for LiteLLM cost attribution. Forwarded as the `user` field on every LLM call and as `projectId:<id>` in `metadata.tags`. Optional, but spend won't be attributed to a project without it.")
508
+ @click.option("--env-state-type", default=None, type=str,
509
+ help="Override the env state type for deploy_env steps")
510
+ @click.option("--env-state-instance-id", default=None, type=str,
511
+ help="Attach env to an existing EnvStateInstance")
512
+ def run_batch(task_id: str, task_version: int | None, seeds: str, concurrency: int, output_dir: str | None, agent_model: str | None, agent_artifact_id: str | None, litellm_api_key: str | None, judge_litellm_api_key: str | None, apply_trajectory_filter: bool | None, agent_sandbox: str | None, env_sandbox: str | None, project_id: str | None, env_state_type: str | None, env_state_instance_id: str | None):
513
+ """Run a task in batch against multiple seeds from a CSV file.
514
+
515
+ Each row in the CSV becomes a seed dict passed to the task via
516
+ context.metadata["seed"]. Prompt templates with <placeholder> variables
517
+ are rendered using the seed values before being sent to the agent.
518
+ """
519
+ from agent_env.task import Task
520
+ from agent_env.task_step.context import TaskStepContext
521
+
522
+ if output_dir is None:
523
+ output_dir = f"/tmp/taskid={fs_safe(task_id)}-batch{uuid4().hex[:6]}"
524
+
525
+ # Read seeds from CSV
526
+ with open(seeds, newline="") as f:
527
+ reader = csv.DictReader(f)
528
+ seed_rows = [row for row in reader if any(row.values())]
529
+
530
+ click.echo(f"Loaded {len(seed_rows)} seeds from {seeds}")
531
+ if not seed_rows:
532
+ raise click.ClickException("No seeds found in CSV")
533
+
534
+ click.echo(f"Fetching task: id={task_id} version={task_version or 'latest'}...")
535
+ task = Task.get(task_id, version=task_version)
536
+ click.echo(f"Found task: id={task.id} version={task.version} steps={len(task.steps)}")
537
+ click.echo(click.style(f"Running {len(seed_rows)} seeds with concurrency={concurrency}...", fg="blue"))
538
+ click.echo()
539
+
540
+ print_banner()
541
+ _warn_missing_cost_attribution(project_id, task)
542
+
543
+ sem = asyncio.Semaphore(concurrency)
544
+ batch_run_group_id = uuid4().hex
545
+ client_id = get_agent_env_client_id()
546
+
547
+ async def _run_seed(index: int, seed: dict):
548
+ async with sem:
549
+ seed_name = seed.get("name", seed.get("repo_url", f"seed-{index}"))
550
+ tag = f"[seed {index}: {seed_name[:50]}]"
551
+ on_start, on_complete = _make_parallel_callbacks(f"seed {index}")
552
+
553
+ ctx = TaskStepContext()
554
+ _stamp_agent_env_client_metadata(ctx.metadata, client_id)
555
+ ctx.metadata["run_group_id"] = batch_run_group_id
556
+ ctx.metadata["seed"] = seed
557
+ # Populate universe_id so collect_artifacts can name the
558
+ # FileArtifactUniverse stably across runs of the same seed.
559
+ # Prefer seed.id, fall back to seed.name. If neither is set,
560
+ # collect_artifacts falls through to the per-run instance_id.
561
+ universe_id = seed.get("id") or seed.get("name")
562
+ if universe_id:
563
+ ctx.metadata["universe_id"] = universe_id
564
+ if litellm_api_key:
565
+ ctx.metadata.setdefault("user_overrides", {})["litellm_api_key"] = litellm_api_key
566
+ if judge_litellm_api_key:
567
+ ctx.metadata.setdefault("user_overrides", {})["judge_litellm_api_key"] = judge_litellm_api_key
568
+ if apply_trajectory_filter is not None:
569
+ ctx.metadata.setdefault("user_overrides", {})["apply_trajectory_filter"] = apply_trajectory_filter
570
+ if agent_sandbox:
571
+ ctx.metadata.setdefault("user_overrides", {})["agent_sandbox"] = agent_sandbox
572
+ if env_sandbox:
573
+ ctx.metadata.setdefault("user_overrides", {})["env_sandbox"] = env_sandbox
574
+ if env_state_type:
575
+ ctx.metadata.setdefault("user_overrides", {})["env_state_type"] = env_state_type
576
+ if env_state_instance_id:
577
+ ctx.metadata.setdefault("user_overrides", {})["env_state_instance_id"] = env_state_instance_id
578
+ ctx.metadata["task_id"] = task_id
579
+ if project_id:
580
+ ctx.metadata["project_id"] = project_id
581
+
582
+ click.echo(click.style(f"{tag} Starting...", fg="yellow"))
583
+ context = await task.run(
584
+ on_step_start=on_start,
585
+ on_step_complete=on_complete,
586
+ agent_model=agent_model,
587
+ agent_artifact_id=agent_artifact_id,
588
+ context=ctx,
589
+ )
590
+ if output_dir:
591
+ _write_context(context, f"{task_id}-seed{index}", output_dir, prefix=f"{tag} ")
592
+ return index, seed_name, context
593
+
594
+ async def _run_all():
595
+ coros = [_run_seed(i, seed) for i, seed in enumerate(seed_rows, 1)]
596
+ return await asyncio.gather(*coros, return_exceptions=True)
597
+
598
+ results = asyncio.run(_run_all())
599
+
600
+ click.echo()
601
+ successes = 0
602
+ failures = []
603
+ for r in results:
604
+ if isinstance(r, BaseException):
605
+ failures.append(r)
606
+ else:
607
+ successes += 1
608
+
609
+ if failures:
610
+ for exc in failures:
611
+ click.echo(click.style(f"FAILED: {exc}", fg="red"))
612
+ click.echo(click.style(f"{successes}/{len(seed_rows)} succeeded, {len(failures)}/{len(seed_rows)} failed.", fg="red"))
613
+ raise SystemExit(1)
614
+ else:
615
+ click.echo(click.style(f"All {len(seed_rows)} seeds completed!", fg="blue"))
@@ -0,0 +1,31 @@
1
+ """Check a task's step config without running it."""
2
+
3
+ import click
4
+
5
+
6
+ @click.command()
7
+ @click.option("--id", "task_id", required=True, help="Task id")
8
+ @click.option("--version", "task_version", default=None, type=int, help="Task version (defaults to latest)")
9
+ def validate(task_id: str, task_version: int | None):
10
+ """Validate a stored task's step config without deploying anything.
11
+
12
+ Reports steps whose script artifact does not resolve, or resolves to the wrong
13
+ type, and deploy_env steps that couldn't deploy their env. Exits non-zero
14
+ when there are problems, so it can gate CI.
15
+ """
16
+ from agent_env.task import Task
17
+ from agent_env.task_step.task_step import TaskStep
18
+
19
+ task = Task.get(task_id, task_version)
20
+ problems = task.preflight()
21
+ # Most step types have no preflight, so report coverage rather than implying a full check.
22
+ checked = sum(1 for s in task.steps if type(s).preflight is not TaskStep.preflight)
23
+ if problems:
24
+ click.echo(f"{task.id} v{task.version}: {len(problems)} problem(s)", err=True)
25
+ for p in problems:
26
+ click.echo(f" - {p}", err=True)
27
+ raise SystemExit(1)
28
+ click.echo(
29
+ f"{task.id} v{task.version}: {checked} of {len(task.steps)} step(s) have "
30
+ f"preflight checks; no problems found"
31
+ )