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,940 @@
1
+ """Collect artifact files from an agent's sandbox VM and upload to S3.
2
+
3
+ Reads file paths from the VM, uploads each to S3 via the artifact store,
4
+ and stores the resulting S3 URIs in context.metadata["artifacts"].
5
+
6
+ File-access modes:
7
+ - Default (no `env_id`): read files via `docker exec` into the deployed
8
+ agent's container on a VM-mode sandbox.
9
+ - VM host (`sandbox_name` alone): read straight off the VM, for a host-mode agent.
10
+ - CUA (`env_id` set): read files via the CUA controller's `cua_get_file`
11
+ over the gateway's step/v1, as the deployed env's stored card declares it.
12
+ Required for CUA tasks, where deliverables live on the desktop VM (e.g.
13
+ /home/docker/Desktop) which is NOT mounted into the a2a `agent-api`
14
+ container — so the docker-exec path reports "File not found".
15
+
16
+ Artifact paths come from one of these sources (in priority order):
17
+ 1. Manifest (`manifest_step_id`): a prior prompt step's declared artifacts from
18
+ that step's PromptResponse.structured_output["artifacts"] (logical name -> abs path);
19
+ collected files are keyed by logical name.
20
+ 2. Seed data: context.metadata["seed"][artifacts_key] — a comma-separated
21
+ list of filenames (e.g., "Dockerfile,run.sh,codebase.patch")
22
+ 3. Static fallback: artifact_paths list in the step definition
23
+
24
+ Each entry may be relative (joined to base_path) OR absolute (a leading '/',
25
+ read verbatim). Absolute entries let a task collect deliverables that aren't
26
+ under a single base_path — outputs aren't guaranteed to live on the desktop /
27
+ in /app — without assuming a common directory. base_path only applies to
28
+ relative entries and to the no-list enumeration fallback.
29
+
30
+ This allows the same step definition to collect different artifacts per seed.
31
+
32
+ Usage in task JSON:
33
+ {
34
+ "id": "collect",
35
+ "type": "collect_artifacts",
36
+ "agent_name": "solver",
37
+ "base_path": "/app/artifact",
38
+ "artifacts_key": "expected_artifacts"
39
+ }
40
+
41
+ With seed CSV:
42
+ name,platform,expected_artifacts
43
+ VPC Endpoints,Terraform,"Dockerfile,run.sh,codebase.patch,test.patch,gold.patch,prompt.md,before.json,after.json,p2p_tests.json,f2p_tests.json,validation.json,progress.md"
44
+
45
+ Or with static fallback (no seed data needed):
46
+ {
47
+ "id": "collect",
48
+ "type": "collect_artifacts",
49
+ "agent_name": "solver",
50
+ "base_path": "/app/artifact",
51
+ "artifact_paths": ["Dockerfile", "run.sh", "codebase.patch"]
52
+ }
53
+
54
+ CUA task (read from the desktop VM via the controller, absolute paths so no
55
+ base directory is assumed):
56
+ {
57
+ "id": "collect-artifacts",
58
+ "type": "collect_artifacts",
59
+ "env_id": "ubuntu-cua",
60
+ "artifact_paths": [
61
+ "/home/docker/Desktop/report.pdf",
62
+ "/tmp/output/summary.docx"
63
+ ]
64
+ }
65
+ """
66
+
67
+ from __future__ import annotations
68
+
69
+ import asyncio
70
+ import functools
71
+ import logging
72
+ import os
73
+ import json
74
+ import re
75
+ import shlex
76
+ import tempfile
77
+ import time
78
+ from typing import ClassVar, Optional
79
+
80
+ from agent_env.env.gateway.constants import EXT_STEP_URI
81
+ from agent_env.task_step.context import TaskStepContext
82
+ from agent_env.entity_refs import EntityRef
83
+ from agent_env.task_step.task_step import TaskStep, TaskStepDependency
84
+ from agent_env.task_step.thread_work import finish_on_thread
85
+
86
+ logger = logging.getLogger(__name__)
87
+
88
+ # Stamped into DeployedEnv.metadata only by a desktop-VM env's deploy — used to confirm
89
+ # a step's `env_id` resolved to a CUA env before issuing cua_* controller calls.
90
+ _CUA_ENV_METADATA_MARKER = "cua_vm_sandbox_id"
91
+
92
+ # artifact_paths entries with a URL scheme are not VM files — they're gold/source
93
+ # URLs that downstream consumers (evaluator, artifact previewer) fetch directly.
94
+ # Collect skips them rather than joining them to base_path (which would mangle
95
+ # them to `/app/artifact/https://…` and fail the VM read).
96
+ _URL_ENTRY = re.compile(r"^[A-Za-z][A-Za-z0-9+.-]*://")
97
+
98
+
99
+ def _is_url_entry(entry: str) -> bool:
100
+ return isinstance(entry, str) and _URL_ENTRY.match(entry) is not None
101
+
102
+ _CONTENT_TYPES = {
103
+ ".json": "application/json",
104
+ ".md": "text/markdown",
105
+ ".sh": "text/x-shellscript",
106
+ ".patch": "text/x-diff",
107
+ ".diff": "text/x-diff",
108
+ ".txt": "text/plain",
109
+ ".csv": "text/csv",
110
+ ".pdf": "application/pdf",
111
+ ".png": "image/png",
112
+ ".jpg": "image/jpeg",
113
+ ".jpeg": "image/jpeg",
114
+ ".gif": "image/gif",
115
+ ".webp": "image/webp",
116
+ ".bmp": "image/bmp",
117
+ ".mp3": "audio/mpeg",
118
+ ".wav": "audio/wav",
119
+ ".m4a": "audio/mp4",
120
+ ".ogg": "audio/ogg",
121
+ ".aac": "audio/aac",
122
+ ".flac": "audio/flac",
123
+ ".mp4": "video/mp4",
124
+ ".webm": "video/webm",
125
+ ".mov": "video/quicktime",
126
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
127
+ ".xls": "application/vnd.ms-excel",
128
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
129
+ ".doc": "application/msword",
130
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
131
+ ".ppt": "application/vnd.ms-powerpoint",
132
+ ".ics": "text/calendar",
133
+ ".eml": "message/rfc822",
134
+ }
135
+
136
+
137
+ def _sanitize_artifact_id(value: str) -> str:
138
+ """Artifact ids become S3 key components, so spaces and separators can't survive."""
139
+ return value.replace(" ", "-").replace("/", "_")
140
+
141
+
142
+ def _exec_args(sandbox, container: Optional[str], cmd: tuple) -> tuple:
143
+ """Wrap a command for where it has to run: inside the container, on the VM host as root, or as-is."""
144
+ from agent_env.providers.sandbox_providers.sandbox_provider import SANDBOX_MODE_VM
145
+ if sandbox.mode != SANDBOX_MODE_VM:
146
+ return cmd # container-mode sandboxes are the runtime and already root
147
+ if container is not None:
148
+ return ("sudo", "docker", "exec", container, *cmd)
149
+ return ("sudo", *cmd) # host-mode agents write as uid 0, so read them back as root
150
+
151
+
152
+ def _cua_bash_stdout(text: str) -> str:
153
+ """Unwrap `cua_bash`'s JSON envelope down to the command's stdout.
154
+
155
+ The CUA MCP tools do NOT share a return shape: `cua_get_file` answers with a
156
+ bare base64 body, but `cua_bash` answers with
157
+ `{"output": ..., "error": ..., "returncode": ..., "status": ...}`. Treating
158
+ the latter like the former makes the whole JSON blob look like a single
159
+ filename, and collection then tries to read
160
+ `<base_path>/{"error": "", "output": "report.pdf\\n", ...}` and 404s — with
161
+ the real filename visible inside the path it failed on.
162
+
163
+ Tolerates a plain-stdout response so a controller that stops wrapping does
164
+ not break this in the other direction.
165
+ """
166
+ try:
167
+ payload = json.loads(text)
168
+ except (TypeError, ValueError):
169
+ return text
170
+ if not isinstance(payload, dict) or "output" not in payload:
171
+ return text
172
+ return payload.get("output") or ""
173
+
174
+
175
+ def _remove(path: str) -> None:
176
+ try:
177
+ os.unlink(path)
178
+ except FileNotFoundError:
179
+ pass
180
+
181
+
182
+ def _write_and_upload(store, content: bytes, artifact_id: str, version: int, object_name: str, content_type: str) -> str:
183
+ """Stage ``content`` in a temp file, upload it as a collected artifact and remove the file."""
184
+ with tempfile.NamedTemporaryFile(delete=False, suffix=f"-{object_name.replace('/', '_')}") as tmp:
185
+ tmp.write(content)
186
+ try:
187
+ return store.put_object_file(
188
+ artifact_type="collected_artifacts",
189
+ id=artifact_id,
190
+ version=version,
191
+ object_name=object_name,
192
+ file_path=tmp.name,
193
+ content_type=content_type,
194
+ )
195
+ finally:
196
+ _remove(tmp.name)
197
+
198
+
199
+ class CollectArtifactsTaskStep(TaskStep):
200
+ type: ClassVar[str] = "collect_artifacts"
201
+ entity_refs = (EntityRef.env("env_id"),)
202
+
203
+ def __init__(
204
+ self,
205
+ id: str,
206
+ version: Optional[int],
207
+ agent_name: Optional[str] = None,
208
+ base_path: str = "/app/artifact",
209
+ artifacts_key: str = "expected_artifacts",
210
+ artifact_paths: Optional[list[str]] = None,
211
+ env_id: Optional[str] = None,
212
+ manifest_step_id: Optional[str] = None,
213
+ exclude_basenames: Optional[list[str]] = None,
214
+ sandbox_name: Optional[str] = None,
215
+ container_name: Optional[str] = None,
216
+ universe_id_suffix: Optional[str] = None,
217
+ depends_on: Optional[list[TaskStepDependency]] = None,
218
+ fail_task_on_error: bool = True,
219
+ ):
220
+ # Three mutually exclusive collection modes: `agent_name` (agent container), `env_id` (CUA
221
+ # controller) and `container_name` (a plain container started by run_docker_container on a
222
+ # deploy_sandbox sandbox). A defaulted agent_name is tolerated: older serialized CUA steps
223
+ # persist DEFAULT_AGENT_NAME alongside env_id.
224
+ explicit_agent = agent_name not in (None, TaskStep.DEFAULT_AGENT_NAME)
225
+ if env_id is not None and explicit_agent:
226
+ raise ValueError(
227
+ "collect_artifacts: set either `agent_name` (agent-container path) "
228
+ "or `env_id` (CUA controller path), not both"
229
+ )
230
+ if sandbox_name is not None and container_name is None and (env_id is not None or explicit_agent):
231
+ raise ValueError(
232
+ "collect_artifacts: `sandbox_name` alone (VM-host path) is exclusive with "
233
+ "`agent_name` and `env_id`"
234
+ )
235
+ if container_name is not None:
236
+ if env_id is not None or explicit_agent:
237
+ raise ValueError(
238
+ "collect_artifacts: `container_name` (sandbox-container path) is exclusive with "
239
+ "`agent_name` and `env_id`"
240
+ )
241
+ if not sandbox_name:
242
+ # The lookup key in `deployed_docker_containers` is the pair, and a container name
243
+ # alone is not unique across sandboxes.
244
+ raise ValueError(
245
+ "collect_artifacts: `container_name` requires `sandbox_name`"
246
+ )
247
+ super().__init__(id, version, depends_on=depends_on, fail_task_on_error=fail_task_on_error)
248
+ # Appended to the run's artifact id so two collect steps in one run produce two
249
+ # named artifacts instead of two versions of one. A suffix rather than an absolute
250
+ # id because the latter would be identical across every seed in a batch.
251
+ self.universe_id_suffix = universe_id_suffix
252
+ self.agent_name = agent_name or TaskStep.DEFAULT_AGENT_NAME
253
+ self.base_path = base_path.rstrip("/")
254
+ self.artifacts_key = artifacts_key
255
+ self.artifact_paths = artifact_paths or []
256
+ self.env_id = env_id
257
+ self.manifest_step_id = manifest_step_id
258
+ self.exclude_basenames = set(exclude_basenames or [])
259
+ self.sandbox_name = sandbox_name
260
+ self.container_name = container_name
261
+
262
+ def to_dict(self) -> dict:
263
+ base = super().to_dict()
264
+ base["agent_name"] = self.agent_name
265
+ base["base_path"] = self.base_path
266
+ base["artifacts_key"] = self.artifacts_key
267
+ base["artifact_paths"] = self.artifact_paths
268
+ base["env_id"] = self.env_id
269
+ base["manifest_step_id"] = self.manifest_step_id
270
+ base["exclude_basenames"] = sorted(self.exclude_basenames)
271
+ base["sandbox_name"] = self.sandbox_name
272
+ base["container_name"] = self.container_name
273
+ base["universe_id_suffix"] = self.universe_id_suffix
274
+ return base
275
+
276
+ @classmethod
277
+ def from_dict(cls, data: dict) -> CollectArtifactsTaskStep:
278
+ return cls(
279
+ **cls._base_from_dict(data),
280
+ agent_name=data.get("agent_name"),
281
+ base_path=data.get("base_path", "/app/artifact"),
282
+ artifacts_key=data.get("artifacts_key", "expected_artifacts"),
283
+ artifact_paths=data.get("artifact_paths"),
284
+ env_id=data.get("env_id"),
285
+ manifest_step_id=data.get("manifest_step_id"),
286
+ exclude_basenames=data.get("exclude_basenames"),
287
+ sandbox_name=data.get("sandbox_name"),
288
+ container_name=data.get("container_name"),
289
+ universe_id_suffix=data.get("universe_id_suffix"),
290
+ )
291
+
292
+ def _resolve_filenames(self, context: TaskStepContext) -> list[str]:
293
+ """Determine which filenames to collect, from seed data or static config."""
294
+ seed = context.metadata.get("seed", {})
295
+ seed_value = seed.get(self.artifacts_key, "")
296
+ if seed_value:
297
+ return [f.strip() for f in str(seed_value).split(",") if f.strip()]
298
+ return self.artifact_paths
299
+
300
+ def _configured_entries(self, context: TaskStepContext) -> list[str]:
301
+ """The artifact_paths entries in effect: a re-run override wins over seed data and
302
+ static config."""
303
+ override = self.step_param_overrides(context)
304
+ if "artifact_paths" in override:
305
+ raw = override["artifact_paths"]
306
+ return [raw] if isinstance(raw, str) else [str(p) for p in raw]
307
+ return self._resolve_filenames(context)
308
+
309
+ def _resolve_items(self, context: TaskStepContext) -> list[tuple[str, str, str]]:
310
+ """``(key, source_path, object_name)`` triples to collect — keyed by logical name in
311
+ manifest mode, by the artifact_paths entry otherwise."""
312
+ # A re-run-from-step can override artifact_paths via step_overrides on
313
+ # the run; it wins over manifest/seed/static so a corrected path actually takes effect.
314
+ if "artifact_paths" in self.step_param_overrides(context):
315
+ paths = self._configured_entries(context)
316
+ logger.info(f"collect '{self.id}': using {len(paths)} overridden artifact_path(s)")
317
+ return self._items_from_entries(paths)
318
+ if self.manifest_step_id:
319
+ # reversed: if the step re-ran (retry/resume), the latest response wins.
320
+ response = next(
321
+ (r for r in reversed(context.prompt_responses) if r.step_id == self.manifest_step_id), None
322
+ )
323
+ structured = response.structured_output if response else None
324
+ if structured is None:
325
+ # Transitional: pre-DataPart-worker tasks carry it in the old metadata channel.
326
+ structured = (context.metadata.get("structured_outputs") or {}).get(self.manifest_step_id)
327
+ manifest = (structured.get("artifacts") if isinstance(structured, dict) else None) or {}
328
+ items: list[tuple[str, str, str]] = []
329
+ skipped_nonfile: list[str] = []
330
+ for name, path in manifest.items():
331
+ if not (isinstance(path, str) and path.startswith("/")):
332
+ skipped_nonfile.append(name) # literal value (e.g. coverage_state) or relative path
333
+ continue
334
+ if "*" in path:
335
+ continue # unresolved glob (e.g. per-iteration debug logs) — can't fetch a literal *
336
+ if os.path.basename(path) in self.exclude_basenames:
337
+ continue
338
+ rel = (
339
+ path[len(self.base_path) + 1:]
340
+ if path.startswith(self.base_path + "/")
341
+ else os.path.basename(path)
342
+ )
343
+ items.append((name, path, rel))
344
+ if skipped_nonfile:
345
+ logger.debug(
346
+ "collect(manifest=%s): skipped non-absolute manifest entries "
347
+ "(literal values or relative paths, not collected): %s",
348
+ self.manifest_step_id, skipped_nonfile,
349
+ )
350
+ return items
351
+ return self._items_from_entries(self._configured_entries(context))
352
+
353
+ def _items_from_entries(self, entries: list[str]) -> list[tuple[str, str, str]]:
354
+ """Resolve raw artifact_paths entries into (key, source_path, object_name)
355
+ triples, skipping URL-scheme entries (gold/source URLs fetched directly by
356
+ consumers, not collected from the VM)."""
357
+ items: list[tuple[str, str, str]] = []
358
+ skipped_urls: list[str] = []
359
+ for entry in entries:
360
+ if _is_url_entry(entry):
361
+ skipped_urls.append(entry)
362
+ continue
363
+ items.append((entry, *self._resolve_paths(entry)))
364
+ if skipped_urls:
365
+ logger.info(
366
+ "collect '%s': skipping %d URL entr%s (not VM files; fetched from source by "
367
+ "downstream consumers): %s",
368
+ self.id, len(skipped_urls), "y" if len(skipped_urls) == 1 else "ies", skipped_urls,
369
+ )
370
+ return items
371
+
372
+ def _drop_excluded(self, names: list[str]) -> list[str]:
373
+ """Drop names whose basename is in exclude_basenames."""
374
+ if not self.exclude_basenames:
375
+ return names
376
+ return [f for f in names if os.path.basename(f) not in self.exclude_basenames]
377
+
378
+ async def _list_base_directory(self, sandbox, container: Optional[str]) -> list[str]:
379
+ """Recursively enumerate regular files under base_path.
380
+ Returns paths relative to base_path (e.g. ``"sub/file.txt"``).
381
+ Used as the fallback when no explicit filename list was configured.
382
+
383
+ Branches on `sandbox.mode`: VM-mode sandboxes wrap `find` in
384
+ `docker exec <container>`; container-mode sandboxes (Modal, for one)
385
+ ARE the agent runtime so we run `find` directly."""
386
+ args = _exec_args(sandbox, container,
387
+ ("find", self.base_path, "-type", "f", "-printf", "%P\n"))
388
+ exit_code, stdout, stderr = await sandbox.exec_with_output(*args)
389
+ if exit_code != 0:
390
+ logger.warning(f"Failed to enumerate {self.base_path}: {stderr[:300]}")
391
+ return []
392
+ return [f.strip() for f in stdout.splitlines() if f.strip()]
393
+
394
+ async def _list_top_level(self, sandbox, container: Optional[str]) -> list[str]:
395
+ """Bounded top-level listing of base_path for the 'what was produced' hint on a failed collect."""
396
+ args = _exec_args(sandbox, container,
397
+ ("find", self.base_path, "-mindepth", "1", "-maxdepth", "1", "-printf", "%P\\n"))
398
+ exit_code, stdout, _ = await sandbox.exec_with_output(*args)
399
+ if exit_code != 0:
400
+ return []
401
+ return sorted(f.strip() for f in stdout.splitlines() if f.strip())[:100]
402
+
403
+ async def _resolve_live_sandbox(self, provider, sandbox_id: str):
404
+ """Resolve the sandbox and confirm it's reachable. A re-run-from-step can target one already
405
+ reaped past its TTL, so fail with a clear "expired" message rather than a raw provider error."""
406
+ err: Optional[Exception] = None
407
+ try:
408
+ sandbox = await provider.get_sandbox(sandbox_id)
409
+ exit_code, _, _ = await sandbox.exec_with_output("echo", "ok")
410
+ if exit_code == 0:
411
+ return sandbox
412
+ except Exception as e:
413
+ err = e
414
+ # Log the real error — TTL expiry is the common cause but not the only one (auth, quota, network).
415
+ logger.warning(f"collect: sandbox {sandbox_id!r} unreachable{f' ({err})' if err else ''}")
416
+ await provider.close()
417
+ raise RuntimeError(
418
+ f"collect: agent sandbox {sandbox_id!r} is unreachable (likely expired past its TTL) — "
419
+ f"a re-run-from-step needs the original live sandbox; re-run the full task."
420
+ ) from err
421
+
422
+ async def _discover_container(self, sandbox) -> str:
423
+ """Find the agent container running on the VM.
424
+
425
+ The A2A agent deploy hardcodes the container name to 'agent-api'
426
+ (see agent_env/a2a_agent/a2a_agent.py). We also accept any
427
+ 'a2a-agent-*' container as a fallback in case the naming scheme
428
+ evolves.
429
+ """
430
+ exit_code, stdout, stderr = await sandbox.exec_with_output(
431
+ "sudo", "docker", "ps",
432
+ "--format", "{{.Names}}",
433
+ )
434
+ if exit_code != 0:
435
+ raise RuntimeError(f"Failed to list containers: {stderr[:300]}")
436
+ running = [n.strip() for n in stdout.splitlines() if n.strip()]
437
+ # Prefer this sandbox's own container name, fall back to the a2a-agent-* prefix.
438
+ if sandbox.container_name in running:
439
+ return sandbox.container_name
440
+ fallback = [n for n in running if n.startswith("a2a-agent-")]
441
+ if fallback:
442
+ if len(fallback) > 1:
443
+ logger.warning(f"Multiple a2a-agent-* containers found; using first: {fallback}")
444
+ return fallback[0]
445
+ raise RuntimeError(
446
+ f"No agent container found on the VM (looked for 'agent-api' or 'a2a-agent-*'). "
447
+ f"Running containers: {running}. Has deploy_agent been run in this task?"
448
+ )
449
+
450
+ async def _get_file_size(self, sandbox, container: Optional[str], source_path: str) -> int:
451
+ """Get file size on the agent's filesystem. Returns -1 if the file doesn't exist.
452
+ VM-mode wraps in `docker exec <container>`; container-mode runs `stat` directly."""
453
+ args = _exec_args(sandbox, container, ("stat", "-c", "%s", source_path))
454
+ exit_code, stdout, _ = await sandbox.exec_with_output(*args)
455
+ if exit_code != 0:
456
+ return -1
457
+ return int(stdout.strip())
458
+
459
+ async def _collect_file(
460
+ self, sandbox, container: Optional[str], source_path: str, object_name: str, store, artifact_id: str,
461
+ version: int, content_type: str,
462
+ ) -> str:
463
+ """Read a file out of the sandbox and upload it to S3 — one path, any size.
464
+
465
+ base64-encode in the sandbox (raw binary over a websocket exec transport is
466
+ silently dropped; ASCII survives), stream stdout + decode incrementally to
467
+ a temp file (bounds memory), then multipart-upload. stderr is drained in
468
+ parallel so the shared output pump can't backpressure-stall."""
469
+ import base64
470
+ bash_cmd = f"base64 < {shlex.quote(source_path)}"
471
+ args = _exec_args(sandbox, container, ("bash", "-c", bash_cmd))
472
+
473
+ local_path = None
474
+ handed_off = False
475
+ try:
476
+ with tempfile.NamedTemporaryFile(delete=False, suffix=f"-{object_name.replace('/', '_')}") as tmp:
477
+ local_path = tmp.name
478
+
479
+ process = await sandbox.exec(*args)
480
+ stderr_task = asyncio.create_task(process.stderr.read())
481
+ stdout = process.stdout
482
+ with open(local_path, "wb") as fh:
483
+ if hasattr(stdout, "__aiter__"):
484
+ # Async-iterable stdout (websocket exec): stream, decoding 4-char-aligned base64.
485
+ pending = bytearray()
486
+ async for chunk in stdout:
487
+ pending += chunk.translate(None, b"\r\n") # strip 76-col wrap
488
+ n = (len(pending) // 4) * 4
489
+ if n:
490
+ fh.write(base64.b64decode(pending[:n]))
491
+ del pending[:n]
492
+ if pending:
493
+ fh.write(base64.b64decode(pending))
494
+ else:
495
+ # Modal stdout has read() but no __aiter__: read all, decode once.
496
+ data = (await stdout.read()).translate(None, b"\r\n")
497
+ fh.write(base64.b64decode(data))
498
+ exit_code = await process.wait()
499
+ try:
500
+ await stderr_task
501
+ except Exception:
502
+ pass
503
+ if exit_code != 0:
504
+ raise RuntimeError(f"base64 read failed for {source_path} (exit {exit_code})")
505
+
506
+ # Integrity check: base64-over-exec can silently truncate large streams on a
507
+ # websocket exec transport under load. Fail loudly on a size mismatch rather than upload a
508
+ # truncated artifact (retryable failure > undetectable short file).
509
+ src_size = await self._get_file_size(sandbox, container, source_path)
510
+ got_size = os.path.getsize(local_path)
511
+ if src_size >= 0 and got_size != src_size:
512
+ raise RuntimeError(
513
+ f"collect integrity check failed for {source_path}: decoded {got_size} bytes but "
514
+ f"source is {src_size} (exec-channel truncation) — refusing to upload a corrupt artifact"
515
+ )
516
+
517
+ path = local_path
518
+
519
+ def upload() -> str:
520
+ try:
521
+ return store.put_object_file(
522
+ artifact_type="collected_artifacts",
523
+ id=artifact_id,
524
+ version=version,
525
+ object_name=object_name,
526
+ file_path=path,
527
+ content_type=content_type,
528
+ )
529
+ finally:
530
+ _remove(path)
531
+
532
+ # The upload owns the file from here: a cancel must not remove it under the upload.
533
+ handed_off = True
534
+ return await finish_on_thread(
535
+ upload, f"Uploading collected {source_path}", if_never_run=lambda: _remove(path)
536
+ )
537
+ finally:
538
+ if local_path and not handed_off:
539
+ _remove(local_path)
540
+
541
+ async def _controller_call(self, deployed_env, tool_name: str, arguments: dict) -> str:
542
+ """Call a CUA MCP tool through the gateway's step/v1, as the env card declares it. Returns the text content."""
543
+ data = await deployed_env.invoke(
544
+ EXT_STEP_URI, "step", {"action": "call_tool", "tool_name": tool_name, "arguments": arguments}, timeout=600,
545
+ )
546
+ if data.get("isError"):
547
+ raise RuntimeError(f"{tool_name} failed: {data}")
548
+ content = data.get("content")
549
+ if not content:
550
+ raise RuntimeError(f"{tool_name} returned no content: {data}")
551
+ return content[0].get("text", "")
552
+
553
+ async def _controller_get_file(self, deployed_env, path: str) -> bytes:
554
+ """Fetch a file from the CUA VM as raw bytes (controller returns base64)."""
555
+ import base64
556
+
557
+ b64 = await self._controller_call(deployed_env, "cua_get_file", {"path": path})
558
+ return base64.b64decode(b64)
559
+
560
+ async def _controller_list_dir(self, deployed_env) -> list[str]:
561
+ """Recursively enumerate regular files under base_path via cua_bash.
562
+ Returns paths relative to base_path. Fallback when no explicit list
563
+ was configured."""
564
+ script = f"find {shlex.quote(self.base_path)} -type f -printf '%P\\n'"
565
+ try:
566
+ out = await self._controller_call(deployed_env, "cua_bash", {"script": script})
567
+ except Exception as e:
568
+ logger.warning(f"Failed to enumerate {self.base_path} via controller: {e}")
569
+ return []
570
+ return [f.strip() for f in _cua_bash_stdout(out).splitlines() if f.strip()]
571
+
572
+ def _resolve_cua_env(self, context):
573
+ """Resolve self.env_id to a deployed CUA env, refusing non-CUA envs.
574
+
575
+ cua_get_file / cua_bash are CUA-controller tools; firing them at an
576
+ arbitrary env's gateway would hang or error confusingly. A desktop-VM env's
577
+ deploy is the only path that stamps `cua_vm_sandbox_id` into the
578
+ DeployedEnv metadata, so its presence authoritatively marks a CUA env."""
579
+ deployed_env = next((d for d in context.deployed_envs if d.env_id == self.env_id), None)
580
+ if deployed_env is None:
581
+ raise RuntimeError(
582
+ f"Env '{self.env_id}' not found in context.deployed_envs — cannot collect artifacts via controller"
583
+ )
584
+ if _CUA_ENV_METADATA_MARKER not in (deployed_env.metadata or {}):
585
+ raise RuntimeError(
586
+ f"Env '{self.env_id}' is not a CUA environment "
587
+ f"(no '{_CUA_ENV_METADATA_MARKER}' in its deployed metadata) — refusing to issue "
588
+ f"cua_* controller calls against a non-CUA gateway. collect_artifacts with `env_id` "
589
+ f"set is only valid for CUA envs; omit `env_id` to use the agent-container path."
590
+ )
591
+ # Up front: enumeration swallows errors into [], so a missing step/v1 would become a silent empty collect.
592
+ deployed_env.require(EXT_STEP_URI, "step")
593
+ return deployed_env
594
+
595
+ def _resolve_paths(self, entry: str) -> tuple[str, str]:
596
+ """Map an artifact_paths entry to (source_path_on_vm, s3_object_name).
597
+ Absolute entries are read verbatim (base_path ignored) and stored under
598
+ their full path; relative entries keep the legacy base_path join."""
599
+ if entry.startswith("/"):
600
+ return entry, entry.lstrip("/")
601
+ return f"{self.base_path}/{entry}", entry
602
+
603
+ async def _collect_via_controller(self, context, store, artifact_id, version):
604
+ """Collect artifacts from a CUA env's desktop VM through the controller."""
605
+ from agent_env.artifact import FileArtifact
606
+
607
+ deployed_env = self._resolve_cua_env(context)
608
+ # Read files via the CUA MCP server (cua_get_file / cua_bash) over the
609
+ # gateway's step/v1. These are MCP tools registered on the gateway on both
610
+ # Ubuntu and macOS — NOT endpoints on the macOS controller sidecar, whose
611
+ # /step only accepts a ScaleCuaAction and 500s on a call_tool payload.
612
+ logger.info(f"Collecting artifacts via CUA MCP server (env_id={self.env_id}, gateway={deployed_env.environment_url})")
613
+
614
+ items = self._resolve_items(context)
615
+ if not items:
616
+ if self.manifest_step_id:
617
+ raise RuntimeError(
618
+ f"collect(manifest): step '{self.manifest_step_id}' declared no collectable "
619
+ f"artifacts in its structured output — did it run and emit StructuredOutput.artifacts?"
620
+ )
621
+ if self._configured_entries(context):
622
+ logger.info(f"collect '{self.id}': every configured entry is a URL; nothing to read from the VM")
623
+ return {}, {}
624
+ enumerated = self._drop_excluded(await self._controller_list_dir(deployed_env))
625
+ if not enumerated:
626
+ logger.warning(
627
+ f"No artifact filenames resolved and {self.base_path} is empty — nothing to collect"
628
+ )
629
+ return {}, {}
630
+ items = [(f, f"{self.base_path}/{f}", f) for f in enumerated]
631
+ logger.info(
632
+ f"No manifest/artifacts_key/artifact_paths configured; enumerated "
633
+ f"{len(items)} file(s) under {self.base_path}"
634
+ )
635
+ else:
636
+ logger.info(f"Collecting {len(items)} artifacts from {self.base_path} via controller")
637
+
638
+ collected: dict[str, str] = {}
639
+ file_artifacts: dict[str, FileArtifact] = {}
640
+ for key, source_path, object_name in items:
641
+ try:
642
+ content = await self._controller_get_file(deployed_env, source_path)
643
+ except Exception as e:
644
+ logger.warning(f"Failed to read {source_path} via controller: {e}")
645
+ continue
646
+
647
+ ext = os.path.splitext(object_name)[1]
648
+ content_type = _CONTENT_TYPES.get(ext, "application/octet-stream")
649
+
650
+ try:
651
+ s3_url = await finish_on_thread(
652
+ functools.partial(
653
+ _write_and_upload, store, content, artifact_id, version, object_name, content_type,
654
+ ),
655
+ f"Uploading collected {source_path}",
656
+ )
657
+
658
+ collected[key] = s3_url
659
+ self._register_file_artifact(
660
+ store, file_artifacts, artifact_id, key, object_name, content_type, s3_url, context,
661
+ )
662
+ logger.info(f"Collected {source_path} -> {s3_url} ({len(content)} bytes) via controller")
663
+ except Exception as e:
664
+ logger.warning(f"Failed to collect {source_path} via controller: {e}")
665
+
666
+ logger.info(f"Collected {len(collected)}/{len(items)} artifacts via controller")
667
+ return collected, file_artifacts
668
+
669
+ async def _collect_via_agent_container(self, context, store, artifact_id, version):
670
+ from agent_env.providers.sandbox_providers.sandbox_provider import (
671
+ SANDBOX_MODE_VM,
672
+ build_sandbox_provider,
673
+ get_agent_sandbox_provider,
674
+ )
675
+
676
+ agent = next((a for a in context.deployed_agents if a.agent_name == self.agent_name), None)
677
+ if agent is None:
678
+ raise RuntimeError(f"Agent '{self.agent_name}' not found in context.deployed_agents")
679
+ if not agent.sandbox_id:
680
+ raise RuntimeError(f"Agent '{self.agent_name}' has no sandbox_id — cannot collect artifacts")
681
+
682
+ items = self._resolve_items(context)
683
+ if not items and self.manifest_step_id:
684
+ raise RuntimeError(
685
+ f"collect(manifest): step '{self.manifest_step_id}' declared no collectable "
686
+ f"artifacts in its structured output — did it run and emit StructuredOutput.artifacts?"
687
+ )
688
+
689
+ provider = (
690
+ build_sandbox_provider(agent.sandbox_type)
691
+ if agent.sandbox_type
692
+ else get_agent_sandbox_provider()
693
+ )
694
+ sandbox = await self._resolve_live_sandbox(provider, agent.sandbox_id)
695
+ logger.info(f"Connected to sandbox {agent.sandbox_id} (mode={sandbox.mode})")
696
+
697
+ container = await self._discover_container(sandbox) if sandbox.mode == SANDBOX_MODE_VM else None
698
+ if container:
699
+ logger.info(f"Using agent container: {container}")
700
+
701
+ return await self._collect_items(
702
+ provider, sandbox, container, items, context, store, artifact_id, version,
703
+ )
704
+
705
+ async def _collect_via_vm_host(self, context, store, artifact_id, version):
706
+ """Collect off the VM's own filesystem — host-mode agents leave no container to exec into."""
707
+ from agent_env.providers.sandbox_providers.sandbox_provider import build_sandbox_provider, get_sandbox_provider
708
+
709
+ ds = next(
710
+ (sb for sb in context.deployed_sandboxes if sb.sandbox_name == self.sandbox_name), None
711
+ )
712
+ if ds is None:
713
+ raise RuntimeError(
714
+ f"Sandbox '{self.sandbox_name}' not found in context.deployed_sandboxes"
715
+ )
716
+
717
+ items = self._resolve_items(context)
718
+ if not items and self.manifest_step_id:
719
+ raise RuntimeError(
720
+ f"collect(manifest): step '{self.manifest_step_id}' declared no collectable "
721
+ f"artifacts in its structured output — did it run and emit StructuredOutput.artifacts?"
722
+ )
723
+
724
+ provider = build_sandbox_provider(ds.sandbox_type) if ds.sandbox_type else get_sandbox_provider()
725
+ sandbox = await self._resolve_live_sandbox(provider, ds.sandbox_id)
726
+ logger.info(f"Collecting from the VM host of sandbox '{self.sandbox_name}' ({ds.sandbox_id})")
727
+
728
+ return await self._collect_items(
729
+ provider, sandbox, None, items, context, store, artifact_id, version,
730
+ )
731
+
732
+ async def _collect_via_sandbox_container(self, context, store, artifact_id, version):
733
+ """Collect from a plain container started by ``run_docker_container``.
734
+
735
+ The agent path finds its container by discovery, and ``_discover_container`` only accepts
736
+ ``agent-api`` / ``a2a-agent-*`` names — so a task that deploys a sandbox and runs an ordinary
737
+ image had no way to get its files out. Here the (sandbox, container) pair is named
738
+ explicitly and resolved exactly as ``load_artifact`` resolves it.
739
+ """
740
+ from agent_env.providers.sandbox_providers.sandbox_provider import (
741
+ build_sandbox_provider,
742
+ get_sandbox_provider,
743
+ )
744
+
745
+ containers = context.metadata.get("deployed_docker_containers", [])
746
+ entry = next(
747
+ (
748
+ c for c in containers
749
+ if c.get("container_name") == self.container_name
750
+ and c.get("sandbox_name") == self.sandbox_name
751
+ ),
752
+ None,
753
+ )
754
+ if entry is None:
755
+ raise RuntimeError(
756
+ f"Container '{self.container_name}' not found on sandbox '{self.sandbox_name}' in "
757
+ f"context.metadata['deployed_docker_containers']"
758
+ )
759
+ deployed = next(
760
+ (s for s in context.deployed_sandboxes if s.sandbox_name == self.sandbox_name), None
761
+ )
762
+ if deployed is None:
763
+ raise RuntimeError(
764
+ f"Sandbox '{self.sandbox_name}' not found in context.deployed_sandboxes"
765
+ )
766
+
767
+ items = self._resolve_items(context)
768
+ if not items and self.manifest_step_id:
769
+ raise RuntimeError(
770
+ f"collect(manifest): step '{self.manifest_step_id}' declared no collectable "
771
+ f"artifacts in its structured output — did it run and emit StructuredOutput.artifacts?"
772
+ )
773
+
774
+ provider = (
775
+ build_sandbox_provider(deployed.sandbox_type)
776
+ if deployed.sandbox_type
777
+ else get_sandbox_provider()
778
+ )
779
+ sandbox = await self._resolve_live_sandbox(provider, deployed.sandbox_id)
780
+ logger.info(
781
+ f"Connected to sandbox {deployed.sandbox_id} (mode={sandbox.mode}), "
782
+ f"container={self.container_name}"
783
+ )
784
+ return await self._collect_items(
785
+ provider, sandbox, self.container_name, items, context, store, artifact_id, version,
786
+ )
787
+
788
+ async def _collect_items(self, provider, sandbox, container, items, context, store,
789
+ artifact_id, version):
790
+ """Pull ``items`` out of ``container`` (or the VM itself when None) and register them.
791
+
792
+ Shared by the agent-container and sandbox-container paths — everything from here down
793
+ needs only a reachable sandbox plus an optional container name.
794
+ """
795
+ from agent_env.artifact import FileArtifact
796
+
797
+ if not items:
798
+ if self._configured_entries(context):
799
+ logger.info(f"collect '{self.id}': every configured entry is a URL; nothing to read from the VM")
800
+ await provider.close()
801
+ return {}, {}
802
+ # Neither seed-driven nor static list was configured. Fall back
803
+ # to enumerating base_path on the VM — useful when the agent's
804
+ # output set is dynamic (e.g. "everything the solver wrote to
805
+ # /app/artifact"). Recursive; returns paths relative to base_path.
806
+ enumerated = self._drop_excluded(await self._list_base_directory(sandbox, container))
807
+ if not enumerated:
808
+ logger.warning(
809
+ f"No artifact filenames resolved and {self.base_path} is empty — nothing to collect"
810
+ )
811
+ await provider.close()
812
+ return {}, {}
813
+ items = [(f, f"{self.base_path}/{f}", f) for f in enumerated]
814
+ logger.info(
815
+ f"No manifest/artifacts_key/artifact_paths configured; enumerated "
816
+ f"{len(items)} file(s) under {self.base_path}"
817
+ )
818
+ else:
819
+ logger.info(f"Collecting {len(items)} artifacts from {self.base_path}")
820
+
821
+ collected: dict[str, str] = {}
822
+ file_artifacts: dict[str, FileArtifact] = {}
823
+ for key, source_path, object_name in items:
824
+ try:
825
+ file_size = await self._get_file_size(sandbox, container, source_path)
826
+ if file_size < 0:
827
+ logger.warning(f"File not found: {source_path}")
828
+ continue
829
+
830
+ ext = os.path.splitext(object_name)[1]
831
+ content_type = _CONTENT_TYPES.get(ext, "application/octet-stream")
832
+
833
+ s3_url = await self._collect_file(
834
+ sandbox, container, source_path, object_name, store, artifact_id, version, content_type,
835
+ )
836
+
837
+ collected[key] = s3_url
838
+ self._register_file_artifact(
839
+ store, file_artifacts, artifact_id, key, object_name, content_type, s3_url, context,
840
+ )
841
+ logger.info(f"Collected {source_path} -> {s3_url} ({file_size} bytes)")
842
+
843
+ except Exception as e:
844
+ logger.warning(f"Failed to collect {source_path}: {e}")
845
+
846
+ if not collected and items:
847
+ # Surface what the agent actually left in base_path so a re-collect is a pick, not a guess.
848
+ context.metadata["collect_produced_files"] = {
849
+ "step_id": self.id,
850
+ "base_path": self.base_path,
851
+ "files": await self._list_top_level(sandbox, container),
852
+ }
853
+ logger.info(f"Collected {len(collected)}/{len(items)} artifacts")
854
+ await provider.close()
855
+ return collected, file_artifacts
856
+
857
+ def _register_file_artifact(self, store, file_artifacts, artifact_id, key, object_name, content_type, s3_url, context):
858
+ """Register a FileArtifact document pointing at the already-uploaded S3
859
+ object. We do NOT re-upload the bytes — FileArtifact.object_url is just a URL
860
+ reference, and the object is already in S3 under the collected_artifacts
861
+ path. `key` is the original artifact_paths entry (an absolute path when
862
+ the file lives outside base_path); `object_name` is the S3 key. The
863
+ FileArtifact filename is the basename for clean downloads."""
864
+ from agent_env.artifact import FileArtifact
865
+
866
+ fa_id = f"{artifact_id}-{object_name}".replace("/", "_")[:200]
867
+ fa_version = store.next_version(fa_id)
868
+ fa = FileArtifact(
869
+ id=fa_id,
870
+ version=fa_version,
871
+ description=f"Collected artifact '{object_name}' from task instance {context.instance_id or artifact_id}",
872
+ filename=object_name.split("/")[-1],
873
+ content_type=content_type,
874
+ s3_url=s3_url,
875
+ )
876
+ try:
877
+ store.put_document(fa)
878
+ file_artifacts[key] = fa
879
+ except Exception as doc_err:
880
+ # Don't fail the whole collection if the document write fails.
881
+ logger.warning(f"Failed to register FileArtifact for {key}: {doc_err}")
882
+
883
+ async def execute(self, context: TaskStepContext) -> TaskStepContext:
884
+ from agent_env.artifact import FileArtifactUniverse
885
+ from agent_env.artifact.store import get_artifact_store
886
+
887
+ store = get_artifact_store()
888
+ artifact_id = (
889
+ context.metadata.get("universe_id")
890
+ or context.instance_id
891
+ or "unknown"
892
+ )
893
+ # Reserve room for the suffix inside the 100-char budget rather than appending past
894
+ # it, so a long run id can never truncate two collects back onto the same name.
895
+ suffix = _sanitize_artifact_id(self.universe_id_suffix or "")
896
+ artifact_id = _sanitize_artifact_id(artifact_id)[:100 - len(suffix)] + suffix
897
+ version = int(time.time())
898
+
899
+ if self.env_id:
900
+ collected, file_artifacts = await self._collect_via_controller(context, store, artifact_id, version)
901
+ elif self.container_name:
902
+ collected, file_artifacts = await self._collect_via_sandbox_container(context, store, artifact_id, version)
903
+ elif self.sandbox_name:
904
+ collected, file_artifacts = await self._collect_via_vm_host(context, store, artifact_id, version)
905
+ else:
906
+ collected, file_artifacts = await self._collect_via_agent_container(context, store, artifact_id, version)
907
+
908
+ # `artifacts` and `file_artifact_universe` (set below) are legacy flat keys
909
+ # that mirror the latest collect step; they can be removed once all
910
+ # consumers read `collected_artifacts[<step_id>]` instead.
911
+ context.metadata["artifacts"] = collected
912
+ collected_entry: dict = {"artifacts": collected, "file_artifact_universe": None}
913
+ context.metadata.setdefault("collected_artifacts", {})[self.id] = collected_entry
914
+
915
+ if file_artifacts:
916
+ try:
917
+ universe = FileArtifactUniverse.put(
918
+ id=artifact_id,
919
+ file_artifacts=file_artifacts,
920
+ )
921
+ universe_ref = {"id": universe.id, "version": universe.version}
922
+ context.metadata["file_artifact_universe"] = universe_ref
923
+ collected_entry["file_artifact_universe"] = universe_ref
924
+ logger.info(
925
+ f"Created FileArtifactUniverse id={universe.id} v{universe.version} "
926
+ f"with {len(file_artifacts)} file(s)"
927
+ )
928
+ except Exception as u_err:
929
+ logger.warning(f"Failed to create FileArtifactUniverse: {u_err}")
930
+
931
+ # After the metadata write, so tolerant (fail_task_on_error=False) dependents still see
932
+ # present-but-empty. Enumeration fallback resolves to empty, so it stays lenient.
933
+ expected = self._resolve_items(context)
934
+ if expected and collected_entry["file_artifact_universe"] is None:
935
+ raise RuntimeError(
936
+ f"collect: resolved {len(expected)} artifact path(s) but produced no file_artifact_universe "
937
+ f"(see per-file warnings for the cause): {[src for _, src, _ in expected]}"
938
+ )
939
+
940
+ return context