@withgateway/sdk 0.1.20 → 0.2.1

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 (1222) hide show
  1. package/README.md +165 -2
  2. package/dist/cli.js +14075 -1326
  3. package/dist/cli.js.map +1 -1
  4. package/dist/cli.mjs +14073 -1325
  5. package/dist/cli.mjs.map +1 -1
  6. package/dist/files/index.d.mts +2 -0
  7. package/dist/files/index.d.ts +2 -0
  8. package/dist/files/index.js +446 -0
  9. package/dist/files/index.js.map +1 -0
  10. package/dist/files/index.mjs +395 -0
  11. package/dist/files/index.mjs.map +1 -0
  12. package/dist/index-BgvvQ3BC.d.ts +170 -0
  13. package/dist/index-CLkMr6VG.d.ts +171 -0
  14. package/dist/index-CdbmO4aX.d.mts +171 -0
  15. package/dist/index-CiKWoroJ.d.mts +170 -0
  16. package/dist/index.d.mts +3 -1
  17. package/dist/index.d.ts +3 -1
  18. package/dist/index.js +3341 -241
  19. package/dist/index.js.map +1 -1
  20. package/dist/index.mjs +3279 -235
  21. package/dist/index.mjs.map +1 -1
  22. package/dist/traces/index.d.mts +2 -0
  23. package/dist/traces/index.d.ts +2 -0
  24. package/dist/traces/index.js +320 -0
  25. package/dist/traces/index.js.map +1 -0
  26. package/dist/traces/index.mjs +278 -0
  27. package/dist/traces/index.mjs.map +1 -0
  28. package/dist/tracing/index.js +24 -2
  29. package/dist/tracing/index.js.map +1 -1
  30. package/dist/tracing/index.mjs +24 -2
  31. package/dist/tracing/index.mjs.map +1 -1
  32. package/dist/worlds/index.d.mts +1419 -25
  33. package/dist/worlds/index.d.ts +1419 -25
  34. package/dist/worlds/index.js +2829 -87
  35. package/dist/worlds/index.js.map +1 -1
  36. package/dist/worlds/index.mjs +2824 -83
  37. package/dist/worlds/index.mjs.map +1 -1
  38. package/package.json +24 -2
  39. package/runtime/gatewaysdk/__init__.py +0 -0
  40. package/runtime/gatewaysdk/environment/__init__.py +108 -0
  41. package/runtime/gatewaysdk/environment/_bundle.py +281 -0
  42. package/runtime/gatewaysdk/environment/_harbor.py +276 -0
  43. package/runtime/gatewaysdk/environment/_materialize.py +97 -0
  44. package/runtime/gatewaysdk/environment/_tar.py +33 -0
  45. package/runtime/gatewaysdk/environment/_world.py +359 -0
  46. package/runtime/gatewaysdk/environment/core.py +527 -0
  47. package/runtime/gatewaysdk/environment/errors.py +58 -0
  48. package/runtime/gatewaysdk/environment/runtime.py +150 -0
  49. package/runtime/gatewaysdk/environment/schema/__init__.py +43 -0
  50. package/runtime/gatewaysdk/environment/schema/__main__.py +360 -0
  51. package/runtime/gatewaysdk/environment/schema/_slack_fidelity.py +116 -0
  52. package/runtime/gatewaysdk/environment/schema/_slack_scenario.py +183 -0
  53. package/runtime/gatewaysdk/environment/schema/api.py +1824 -0
  54. package/runtime/gatewaysdk/environment/schema/batch.py +785 -0
  55. package/runtime/gatewaysdk/environment/schema/compiler.py +693 -0
  56. package/runtime/gatewaysdk/environment/schema/conform.py +520 -0
  57. package/runtime/gatewaysdk/environment/schema/connector.py +1116 -0
  58. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/api/handlers.py +778 -0
  59. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/connector.toml +671 -0
  60. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/handlers.py +18 -0
  61. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/parity.json +34 -0
  62. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/provenance.json +1768 -0
  63. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/instruction.md +7 -0
  64. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/scenario.toml +2 -0
  65. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_activities.json +24 -0
  66. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_activity_devices.json +12 -0
  67. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_applecare_coverages.json +52 -0
  68. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_apps.json +35 -0
  69. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_audit_events.json +139 -0
  70. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_blueprint_apps.json +12 -0
  71. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_blueprint_configurations.json +20 -0
  72. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_blueprint_devices.json +16 -0
  73. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_blueprint_packages.json +8 -0
  74. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_blueprint_user_groups.json +12 -0
  75. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_blueprint_users.json +12 -0
  76. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_blueprints.json +39 -0
  77. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_configurations.json +64 -0
  78. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_device_assignments.json +20 -0
  79. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_mdm_device_details.json +55 -0
  80. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_mdm_devices.json +33 -0
  81. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_mdm_servers.json +56 -0
  82. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_org_devices.json +178 -0
  83. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_organizational_unit_memberships.json +16 -0
  84. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_organizational_units.json +24 -0
  85. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_packages.json +20 -0
  86. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_user_group_memberships.json +16 -0
  87. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_user_groups.json +30 -0
  88. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scenarios/default/seed/abm_users.json +115 -0
  89. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/scope.toml +139 -0
  90. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/tests/tools.json +48 -0
  91. package/runtime/gatewaysdk/environment/schema/connectors/apple-business-manager/world.json +2366 -0
  92. package/runtime/gatewaysdk/environment/schema/connectors/asana/api/handlers.py +1026 -0
  93. package/runtime/gatewaysdk/environment/schema/connectors/asana/connector.toml +511 -0
  94. package/runtime/gatewaysdk/environment/schema/connectors/asana/fidelity.json +89 -0
  95. package/runtime/gatewaysdk/environment/schema/connectors/asana/handlers.py +40 -0
  96. package/runtime/gatewaysdk/environment/schema/connectors/asana/provenance.json +101 -0
  97. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/scenario.toml +2 -0
  98. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/account_settings.json +12 -0
  99. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/custom_field_settings.json +60 -0
  100. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/custom_fields.json +43 -0
  101. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/enum_options.json +52 -0
  102. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/notifications.json +103 -0
  103. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/project_favorites.json +12 -0
  104. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/project_memberships.json +144 -0
  105. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/projects.json +120 -0
  106. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/recent_projects.json +19 -0
  107. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/sections.json +102 -0
  108. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/stories.json +852 -0
  109. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/task_custom_fields.json +508 -0
  110. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/task_followers.json +368 -0
  111. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/task_memberships.json +184 -0
  112. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/tasks.json +1921 -0
  113. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/teams.json +22 -0
  114. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/user_task_list_sections.json +32 -0
  115. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/user_task_lists.json +11 -0
  116. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/users.json +60 -0
  117. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/workspace_memberships.json +76 -0
  118. package/runtime/gatewaysdk/environment/schema/connectors/asana/scenarios/default/seed/workspaces.json +13 -0
  119. package/runtime/gatewaysdk/environment/schema/connectors/asana/scope.toml +156 -0
  120. package/runtime/gatewaysdk/environment/schema/connectors/asana/tests/routes.json +298 -0
  121. package/runtime/gatewaysdk/environment/schema/connectors/asana/tests/tools.json +152 -0
  122. package/runtime/gatewaysdk/environment/schema/connectors/asana/ui/static/assets/index-DTTTJ6a4.css +1 -0
  123. package/runtime/gatewaysdk/environment/schema/connectors/asana/ui/static/assets/index-WS8dLEjv.js +67 -0
  124. package/runtime/gatewaysdk/environment/schema/connectors/asana/ui/static/index.html +40 -0
  125. package/runtime/gatewaysdk/environment/schema/connectors/asana/world.json +1911 -0
  126. package/runtime/gatewaysdk/environment/schema/connectors/base.json +28 -0
  127. package/runtime/gatewaysdk/environment/schema/connectors/confluence/api/handlers.py +847 -0
  128. package/runtime/gatewaysdk/environment/schema/connectors/confluence/connector.toml +457 -0
  129. package/runtime/gatewaysdk/environment/schema/connectors/confluence/handlers.py +176 -0
  130. package/runtime/gatewaysdk/environment/schema/connectors/confluence/provenance.json +187 -0
  131. package/runtime/gatewaysdk/environment/schema/connectors/confluence/scenarios/default/instruction.md +39 -0
  132. package/runtime/gatewaysdk/environment/schema/connectors/confluence/scenarios/default/scenario.toml +3 -0
  133. package/runtime/gatewaysdk/environment/schema/connectors/confluence/scenarios/default/seed/confluence_favourites.json +29 -0
  134. package/runtime/gatewaysdk/environment/schema/connectors/confluence/scenarios/default/seed/confluence_footer_comments.json +984 -0
  135. package/runtime/gatewaysdk/environment/schema/connectors/confluence/scenarios/default/seed/confluence_inline_comments.json +355 -0
  136. package/runtime/gatewaysdk/environment/schema/connectors/confluence/scenarios/default/seed/confluence_labels.json +99 -0
  137. package/runtime/gatewaysdk/environment/schema/connectors/confluence/scenarios/default/seed/confluence_notifications.json +40 -0
  138. package/runtime/gatewaysdk/environment/schema/connectors/confluence/scenarios/default/seed/confluence_page_labels.json +209 -0
  139. package/runtime/gatewaysdk/environment/schema/connectors/confluence/scenarios/default/seed/confluence_page_versions.json +828 -0
  140. package/runtime/gatewaysdk/environment/schema/connectors/confluence/scenarios/default/seed/confluence_pages.json +949 -0
  141. package/runtime/gatewaysdk/environment/schema/connectors/confluence/scenarios/default/seed/confluence_recently_viewed_pages.json +59 -0
  142. package/runtime/gatewaysdk/environment/schema/connectors/confluence/scenarios/default/seed/confluence_sites.json +12 -0
  143. package/runtime/gatewaysdk/environment/schema/connectors/confluence/scenarios/default/seed/confluence_spaces.json +128 -0
  144. package/runtime/gatewaysdk/environment/schema/connectors/confluence/scenarios/default/seed/confluence_users.json +100 -0
  145. package/runtime/gatewaysdk/environment/schema/connectors/confluence/scenarios/default/seed/confluence_watches.json +96 -0
  146. package/runtime/gatewaysdk/environment/schema/connectors/confluence/tests/routes.json +212 -0
  147. package/runtime/gatewaysdk/environment/schema/connectors/confluence/tests/tools.json +140 -0
  148. package/runtime/gatewaysdk/environment/schema/connectors/confluence/tests/writes.json +201 -0
  149. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/assets/index-BWaOVdpn.js +70 -0
  150. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/assets/index-CKyfi3i5.css +1 -0
  151. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/avatars/acct-01.svg +1 -0
  152. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/avatars/acct-02.svg +1 -0
  153. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/avatars/acct-03.svg +1 -0
  154. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/avatars/acct-04.svg +1 -0
  155. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/avatars/acct-05.svg +1 -0
  156. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/avatars/acct-06.svg +1 -0
  157. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/avatars/space-DES.svg +1 -0
  158. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/avatars/space-ENG.svg +1 -0
  159. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/avatars/space-OPS.svg +1 -0
  160. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/avatars/space-ORB.svg +1 -0
  161. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/avatars/space-PN.svg +1 -0
  162. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/fonts/AtlassianMono-latin.woff2 +0 -0
  163. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/fonts/AtlassianSans-latin.woff2 +0 -0
  164. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/fonts/AtlassianSansItalic-latin.woff2 +0 -0
  165. package/runtime/gatewaysdk/environment/schema/connectors/confluence/ui/static/index.html +47 -0
  166. package/runtime/gatewaysdk/environment/schema/connectors/confluence/world.json +1346 -0
  167. package/runtime/gatewaysdk/environment/schema/connectors/custom/handlers.py +18 -0
  168. package/runtime/gatewaysdk/environment/schema/connectors/custom/provenance.json +35 -0
  169. package/runtime/gatewaysdk/environment/schema/connectors/custom/tests/tools.json +123 -0
  170. package/runtime/gatewaysdk/environment/schema/connectors/custom/world.json +211 -0
  171. package/runtime/gatewaysdk/environment/schema/connectors/github/api/handlers.py +2923 -0
  172. package/runtime/gatewaysdk/environment/schema/connectors/github/connector.toml +2091 -0
  173. package/runtime/gatewaysdk/environment/schema/connectors/github/handlers.py +81 -0
  174. package/runtime/gatewaysdk/environment/schema/connectors/github/parity.json +37 -0
  175. package/runtime/gatewaysdk/environment/schema/connectors/github/provenance.json +162 -0
  176. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/instruction.md +18 -0
  177. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/scenario.toml +2 -0
  178. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_apps.json +49 -0
  179. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_artifacts.json +26 -0
  180. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_branches.json +443 -0
  181. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_check_runs.json +220 -0
  182. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_check_suites.json +404 -0
  183. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_code_scanning_alerts.json +126 -0
  184. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_collaborators.json +100 -0
  185. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_commit_comments.json +43 -0
  186. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_commit_statuses.json +80 -0
  187. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_commits.json +461 -0
  188. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_dependabot_alerts.json +168 -0
  189. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_deployment_statuses.json +86 -0
  190. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_deployments.json +94 -0
  191. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_environments.json +31 -0
  192. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_gist_comments.json +38 -0
  193. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_gists.json +118 -0
  194. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_git_refs.json +59 -0
  195. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_installations.json +54 -0
  196. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_issue_comments.json +151 -0
  197. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_issue_events.json +606 -0
  198. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_issue_types.json +26 -0
  199. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_issues.json +758 -0
  200. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_labels.json +64 -0
  201. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_licenses.json +54 -0
  202. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_milestones.json +130 -0
  203. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_organization_memberships.json +139 -0
  204. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_organizations.json +38 -0
  205. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_pull_requests.json +874 -0
  206. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_release_assets.json +45 -0
  207. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_releases.json +92 -0
  208. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_repositories.json +797 -0
  209. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_repository_invitations.json +184 -0
  210. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_review_comments.json +66 -0
  211. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_reviews.json +138 -0
  212. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_secret_scanning_alerts.json +50 -0
  213. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_stargazers.json +88 -0
  214. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_tags.json +28 -0
  215. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_team_memberships.json +25 -0
  216. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_team_repositories.json +258 -0
  217. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_teams.json +130 -0
  218. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_users.json +174 -0
  219. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_webhooks.json +31 -0
  220. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_workflow_jobs.json +115 -0
  221. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_workflow_runs.json +1021 -0
  222. package/runtime/gatewaysdk/environment/schema/connectors/github/scenarios/default/seed/github_workflows.json +30 -0
  223. package/runtime/gatewaysdk/environment/schema/connectors/github/scope.toml +597 -0
  224. package/runtime/gatewaysdk/environment/schema/connectors/github/tests/tools.json +79 -0
  225. package/runtime/gatewaysdk/environment/schema/connectors/github/vendor-openapi.json +1 -0
  226. package/runtime/gatewaysdk/environment/schema/connectors/github/world.json +15762 -0
  227. package/runtime/gatewaysdk/environment/schema/connectors/gmail/api/handlers.py +1413 -0
  228. package/runtime/gatewaysdk/environment/schema/connectors/gmail/connector.toml +630 -0
  229. package/runtime/gatewaysdk/environment/schema/connectors/gmail/handlers.py +136 -0
  230. package/runtime/gatewaysdk/environment/schema/connectors/gmail/scenarios/default/scenario.toml +1 -0
  231. package/runtime/gatewaysdk/environment/schema/connectors/gmail/scenarios/default/seed/10-gmail_profiles.json +10 -0
  232. package/runtime/gatewaysdk/environment/schema/connectors/gmail/scenarios/default/seed/20-gmail_labels.json +205 -0
  233. package/runtime/gatewaysdk/environment/schema/connectors/gmail/scenarios/default/seed/30-gmail_contacts.json +234 -0
  234. package/runtime/gatewaysdk/environment/schema/connectors/gmail/scenarios/default/seed/40-gmail_threads.json +374 -0
  235. package/runtime/gatewaysdk/environment/schema/connectors/gmail/scenarios/default/seed/50-gmail_messages.json +1015 -0
  236. package/runtime/gatewaysdk/environment/schema/connectors/gmail/scenarios/default/seed/60-gmail_message_parts.json +3039 -0
  237. package/runtime/gatewaysdk/environment/schema/connectors/gmail/scenarios/default/seed/70-gmail_attachments.json +28 -0
  238. package/runtime/gatewaysdk/environment/schema/connectors/gmail/scenarios/default/seed/80-gmail_drafts.json +39 -0
  239. package/runtime/gatewaysdk/environment/schema/connectors/gmail/scenarios/default/seed/90-gmail_client_settings.json +103 -0
  240. package/runtime/gatewaysdk/environment/schema/connectors/gmail/world.json +784 -0
  241. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/api/handlers.py +454 -0
  242. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/connector.toml +519 -0
  243. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/handlers.py +23 -0
  244. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/provenance.json +229 -0
  245. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/scenarios/default/instruction.md +25 -0
  246. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/scenarios/default/scenario.toml +1 -0
  247. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/scenarios/default/seed/10-calendar_calendars.json +75 -0
  248. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/scenarios/default/seed/20-calendar_calendar_list_entries.json +115 -0
  249. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/scenarios/default/seed/30-calendar_acl_rules.json +124 -0
  250. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/scenarios/default/seed/40-calendar_events.json +810 -0
  251. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/scenarios/default/seed/50-calendar_settings.json +76 -0
  252. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/scenarios/default/seed/60-calendar_channels.json +26 -0
  253. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/scenarios/default/seed/70-calendar_colors.json +48 -0
  254. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/scope.toml +105 -0
  255. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/tests/tools.json +53 -0
  256. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/vendor-openapi.json +4185 -0
  257. package/runtime/gatewaysdk/environment/schema/connectors/google-calendar/world.json +1384 -0
  258. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/api/handlers.py +782 -0
  259. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/connector.toml +373 -0
  260. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/google-docs-types.json +4939 -0
  261. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/handlers.py +197 -0
  262. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/provenance.json +191 -0
  263. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/scenarios/default/instruction.md +29 -0
  264. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/scenarios/default/scenario.toml +2 -0
  265. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/scenarios/default/seed/gdocs_comments.json +50 -0
  266. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/scenarios/default/seed/gdocs_documents.json +8096 -0
  267. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/scenarios/default/seed/gdocs_files.json +1187 -0
  268. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/scenarios/default/seed/gdocs_permissions.json +543 -0
  269. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/scenarios/default/seed/gdocs_replies.json +22 -0
  270. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/scenarios/default/seed/gdocs_revisions.json +643 -0
  271. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/scenarios/default/seed/gdocs_users.json +32 -0
  272. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/scope.toml +148 -0
  273. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/tests/api.json +319 -0
  274. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/tests/tools.json +262 -0
  275. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/ui/static/assets/index-BH9fmZSS.css +1 -0
  276. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/ui/static/assets/index-CU4Fk9dX.js +67 -0
  277. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/ui/static/fonts/README.md +20 -0
  278. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/ui/static/fonts/google-sans-variable.woff2 +0 -0
  279. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/ui/static/fonts/roboto-italic-variable-latin.woff2 +0 -0
  280. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/ui/static/fonts/roboto-variable-latin-ext.woff2 +0 -0
  281. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/ui/static/fonts/roboto-variable-latin.woff2 +0 -0
  282. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/ui/static/icons/material_common_sprite1038_gm3_grey_medium.svg +1 -0
  283. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/ui/static/index.html +13 -0
  284. package/runtime/gatewaysdk/environment/schema/connectors/google-docs/world.json +4489 -0
  285. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/api/handlers.py +466 -0
  286. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/connector.toml +626 -0
  287. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/handlers.py +55 -0
  288. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/provenance.json +342 -0
  289. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/scenarios/default/instruction.md +11 -0
  290. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/scenarios/default/scenario.toml +2 -0
  291. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/scenarios/default/seed/drive_access_proposals.json +31 -0
  292. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/scenarios/default/seed/drive_approvals.json +145 -0
  293. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/scenarios/default/seed/drive_apps.json +81 -0
  294. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/scenarios/default/seed/drive_comments.json +70 -0
  295. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/scenarios/default/seed/drive_drives.json +71 -0
  296. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/scenarios/default/seed/drive_files.json +700 -0
  297. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/scenarios/default/seed/drive_labels.json +75 -0
  298. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/scenarios/default/seed/drive_permissions.json +93 -0
  299. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/scenarios/default/seed/drive_replies.json +66 -0
  300. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/scenarios/default/seed/drive_revisions.json +82 -0
  301. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/scope.toml +126 -0
  302. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/tests/tools.json +101 -0
  303. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/vendor-openapi.json +6193 -0
  304. package/runtime/gatewaysdk/environment/schema/connectors/google-drive/world.json +2150 -0
  305. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/api/handlers.py +1645 -0
  306. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/connector.toml +414 -0
  307. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/handlers.py +200 -0
  308. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/scenarios/default/scenario.toml +2 -0
  309. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/scenarios/default/seed/gsheets_cells.json +10252 -0
  310. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/scenarios/default/seed/gsheets_charts.json +103 -0
  311. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/scenarios/default/seed/gsheets_conditional_formats.json +138 -0
  312. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/scenarios/default/seed/gsheets_dimensions.json +256 -0
  313. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/scenarios/default/seed/gsheets_named_ranges.json +16 -0
  314. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/scenarios/default/seed/gsheets_permissions.json +31 -0
  315. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/scenarios/default/seed/gsheets_sheets.json +95 -0
  316. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/scenarios/default/seed/gsheets_spreadsheets.json +14 -0
  317. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/scenarios/default/seed/gsheets_view_states.json +26 -0
  318. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/tests/page.json +311 -0
  319. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/tests/vendor.json +843 -0
  320. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/ui/static/assets/index-CUpfKgm_.js +40 -0
  321. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/ui/static/assets/index-D3VhwBIC.css +1 -0
  322. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/ui/static/fonts/GoogleSans-400.woff2 +0 -0
  323. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/ui/static/fonts/GoogleSans-500.woff2 +0 -0
  324. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/ui/static/fonts/GoogleSans-700.woff2 +0 -0
  325. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/ui/static/fonts/GoogleSansText-400.woff2 +0 -0
  326. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/ui/static/fonts/GoogleSansText-500.woff2 +0 -0
  327. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/ui/static/fonts/GoogleSansText-700.woff2 +0 -0
  328. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/ui/static/fonts/Roboto-400.woff2 +0 -0
  329. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/ui/static/fonts/Roboto-500.woff2 +0 -0
  330. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/ui/static/fonts/Roboto-700.woff2 +0 -0
  331. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/ui/static/index.html +26 -0
  332. package/runtime/gatewaysdk/environment/schema/connectors/google-sheets/world.json +4029 -0
  333. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/api/handlers.py +800 -0
  334. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/connector.toml +776 -0
  335. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/handlers.py +226 -0
  336. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/instruction.md +11 -0
  337. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/scenario.toml +2 -0
  338. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_accounts.json +17 -0
  339. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_associations.json +1478 -0
  340. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_calls.json +147 -0
  341. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_companies.json +144 -0
  342. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_contacts.json +284 -0
  343. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_deals.json +204 -0
  344. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_emails.json +160 -0
  345. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_meetings.json +147 -0
  346. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_nav_items.json +204 -0
  347. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_notes.json +160 -0
  348. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_notifications.json +25 -0
  349. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_object_views.json +334 -0
  350. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_owners.json +76 -0
  351. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_pipeline_stages.json +109 -0
  352. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_pipelines.json +13 -0
  353. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_properties.json +1220 -0
  354. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_tasks.json +394 -0
  355. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/scenarios/default/seed/hubspot_tickets.json +34 -0
  356. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/assets/index-hdb5vB78.css +1 -0
  357. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/assets/index-xhg5ASqE.js +68 -0
  358. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/fonts/lexend-deca-300.ttf +0 -0
  359. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/fonts/lexend-deca-400.ttf +0 -0
  360. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/fonts/lexend-deca-500.ttf +0 -0
  361. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/fonts/lexend-deca-600.ttf +0 -0
  362. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/fonts/lexend-deca-700.ttf +0 -0
  363. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/fonts/lexend-deca-latin.woff2 +0 -0
  364. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/add.svg +1 -0
  365. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/avatar.svg +1 -0
  366. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/bell.svg +3 -0
  367. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/breeze.svg +4 -0
  368. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/call.svg +1 -0
  369. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/chevron-up.svg +3 -0
  370. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/companies.svg +1 -0
  371. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/contact.svg +1 -0
  372. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/contacts.svg +1 -0
  373. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/date.svg +1 -0
  374. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/deals.svg +1 -0
  375. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/duplicate.svg +1 -0
  376. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/export.svg +3 -0
  377. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/external-link.svg +1 -0
  378. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/filter-lines.svg +3 -0
  379. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/frame-expand.svg +3 -0
  380. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/funnel.svg +3 -0
  381. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/help.svg +1 -0
  382. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/hierarchy.svg +4 -0
  383. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/home.svg +1 -0
  384. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/hubspot-logo.svg +1 -0
  385. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/info.svg +1 -0
  386. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/kanban.svg +1 -0
  387. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/marketing-email.svg +1 -0
  388. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/marketplace.svg +1 -0
  389. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/meetings.svg +1 -0
  390. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/more.svg +1 -0
  391. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/pencil.svg +3 -0
  392. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/pin.svg +3 -0
  393. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/prospecting.svg +1 -0
  394. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/refresh.svg +1 -0
  395. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/search.svg +1 -0
  396. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/settings.svg +1 -0
  397. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/sidebar-collapse.svg +3 -0
  398. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/sort.svg +3 -0
  399. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/table.svg +1 -0
  400. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/tasks.svg +1 -0
  401. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/thumbs-down.svg +1 -0
  402. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/thumbs-up.svg +1 -0
  403. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/undo.svg +3 -0
  404. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/upgrade-arrow.svg +1 -0
  405. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/vertical-dots.svg +5 -0
  406. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/icons/workflows.svg +1 -0
  407. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/ui/static/index.html +37 -0
  408. package/runtime/gatewaysdk/environment/schema/connectors/hubspot/world.json +1347 -0
  409. package/runtime/gatewaysdk/environment/schema/connectors/jamf/api/handlers.py +987 -0
  410. package/runtime/gatewaysdk/environment/schema/connectors/jamf/connector.toml +3057 -0
  411. package/runtime/gatewaysdk/environment/schema/connectors/jamf/handlers.py +34 -0
  412. package/runtime/gatewaysdk/environment/schema/connectors/jamf/parity.json +49 -0
  413. package/runtime/gatewaysdk/environment/schema/connectors/jamf/provenance.json +9495 -0
  414. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/scenario.toml +4 -0
  415. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_account_groups.json +64 -0
  416. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_accounts.json +58 -0
  417. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_advanced_computer_searches.json +139 -0
  418. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_advanced_mobile_device_searches.json +61 -0
  419. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_advanced_user_content_searches.json +61 -0
  420. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_advanced_user_searches.json +124 -0
  421. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_api_integrations.json +37 -0
  422. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_api_roles.json +25 -0
  423. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_app_request_form_input_fields.json +22 -0
  424. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_buildings.json +34 -0
  425. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_byo_profiles.json +46 -0
  426. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_categories.json +19 -0
  427. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_classes.json +217 -0
  428. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_cloud_idps.json +19 -0
  429. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_computer_group_members.json +16 -0
  430. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_computer_groups.json +38 -0
  431. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_computer_invitations.json +82 -0
  432. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_computer_prestages.json +274 -0
  433. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_computers.json +1537 -0
  434. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_configuration_profiles.json +649 -0
  435. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_departments.json +16 -0
  436. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_device_enrollment_devices.json +70 -0
  437. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_device_enrollments.json +46 -0
  438. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_directory_bindings.json +34 -0
  439. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_disk_encryption_configurations.json +22 -0
  440. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_distribution_points.json +91 -0
  441. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_dock_items.json +25 -0
  442. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_ebooks.json +43 -0
  443. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_enrollment_customizations.json +43 -0
  444. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_extension_attributes.json +52 -0
  445. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_ibeacons.json +25 -0
  446. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_inventory_preload_records.json +100 -0
  447. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_ios_branding_configurations.json +31 -0
  448. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_ldap_servers.json +16 -0
  449. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_licensed_software_records.json +244 -0
  450. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_mac_applications.json +610 -0
  451. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_macos_branding_configurations.json +34 -0
  452. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_managed_software_update_plans.json +67 -0
  453. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_mdm_commands.json +58 -0
  454. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_mobile_device_applications.json +700 -0
  455. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_mobile_device_configuration_profiles.json +652 -0
  456. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_mobile_device_enrollment_profiles.json +160 -0
  457. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_mobile_device_extension_attributes.json +43 -0
  458. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_mobile_device_group_members.json +16 -0
  459. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_mobile_device_groups.json +38 -0
  460. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_mobile_device_prestages.json +280 -0
  461. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_mobile_device_provisioning_profiles.json +31 -0
  462. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_mobile_devices.json +1558 -0
  463. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_network_segments.json +46 -0
  464. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_packages.json +118 -0
  465. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_patch_software_title_configurations.json +88 -0
  466. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_policies.json +1054 -0
  467. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_printers.json +52 -0
  468. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_removable_mac_addresses.json +16 -0
  469. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_restricted_software_titles.json +289 -0
  470. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_return_to_service_configurations.json +19 -0
  471. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_scripts.json +61 -0
  472. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_sites.json +19 -0
  473. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_software_update_servers.json +25 -0
  474. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_supervision_identities.json +22 -0
  475. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_user_extension_attributes.json +31 -0
  476. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_user_groups.json +112 -0
  477. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_users.json +37 -0
  478. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_volume_purchasing_locations.json +106 -0
  479. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_volume_purchasing_subscriptions.json +76 -0
  480. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scenarios/default/seed/jamf_webhooks.json +70 -0
  481. package/runtime/gatewaysdk/environment/schema/connectors/jamf/scope.toml +900 -0
  482. package/runtime/gatewaysdk/environment/schema/connectors/jamf/tests/tools.json +95 -0
  483. package/runtime/gatewaysdk/environment/schema/connectors/jamf/vendor-openapi.json +1 -0
  484. package/runtime/gatewaysdk/environment/schema/connectors/jamf/world.json +11559 -0
  485. package/runtime/gatewaysdk/environment/schema/connectors/jira/api/handlers.py +1056 -0
  486. package/runtime/gatewaysdk/environment/schema/connectors/jira/connector.toml +955 -0
  487. package/runtime/gatewaysdk/environment/schema/connectors/jira/handlers.py +87 -0
  488. package/runtime/gatewaysdk/environment/schema/connectors/jira/parity.json +27 -0
  489. package/runtime/gatewaysdk/environment/schema/connectors/jira/provenance.json +166 -0
  490. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/instruction.md +22 -0
  491. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/scenario.toml +3 -0
  492. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_boards.json +61 -0
  493. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_changelogs.json +136 -0
  494. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_comments.json +205 -0
  495. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_components.json +78 -0
  496. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_fields.json +498 -0
  497. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_issue_link_types.json +25 -0
  498. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_issue_links.json +190 -0
  499. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_issue_types.json +44 -0
  500. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_issues.json +1448 -0
  501. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_priorities.json +40 -0
  502. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_project_categories.json +16 -0
  503. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_projects.json +111 -0
  504. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_resolutions.json +22 -0
  505. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_sprint_issues.json +20 -0
  506. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_sprints.json +39 -0
  507. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_status_categories.json +25 -0
  508. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_statuses.json +60 -0
  509. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_transitions.json +179 -0
  510. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_users.json +83 -0
  511. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_versions.json +30 -0
  512. package/runtime/gatewaysdk/environment/schema/connectors/jira/scenarios/default/seed/jira_worklogs.json +96 -0
  513. package/runtime/gatewaysdk/environment/schema/connectors/jira/scope.toml +255 -0
  514. package/runtime/gatewaysdk/environment/schema/connectors/jira/tests/tools.json +151 -0
  515. package/runtime/gatewaysdk/environment/schema/connectors/jira/vendor-openapi.json +13562 -0
  516. package/runtime/gatewaysdk/environment/schema/connectors/jira/world.json +3587 -0
  517. package/runtime/gatewaysdk/environment/schema/connectors/kandji/api/handlers.py +406 -0
  518. package/runtime/gatewaysdk/environment/schema/connectors/kandji/connector.toml +531 -0
  519. package/runtime/gatewaysdk/environment/schema/connectors/kandji/handlers.py +38 -0
  520. package/runtime/gatewaysdk/environment/schema/connectors/kandji/parity.json +29 -0
  521. package/runtime/gatewaysdk/environment/schema/connectors/kandji/provenance.json +335 -0
  522. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/scenario.toml +2 -0
  523. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_blueprint_items.json +22 -0
  524. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_blueprint_template_categories.json +14 -0
  525. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_blueprint_templates.json +38 -0
  526. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_blueprints.json +52 -0
  527. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_custom_apps.json +45 -0
  528. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_custom_profiles.json +32 -0
  529. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_custom_scripts.json +27 -0
  530. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_device_activities.json +43 -0
  531. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_device_apps.json +52 -0
  532. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_device_commands.json +41 -0
  533. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_device_notes.json +20 -0
  534. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_device_parameters.json +28 -0
  535. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_device_tags.json +16 -0
  536. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_devices.json +122 -0
  537. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_in_house_apps.json +33 -0
  538. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_library_item_activities.json +33 -0
  539. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_library_item_statuses.json +98 -0
  540. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_library_items.json +24 -0
  541. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_self_service_categories.json +12 -0
  542. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_tags.json +16 -0
  543. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scenarios/default/seed/kandji_users.json +61 -0
  544. package/runtime/gatewaysdk/environment/schema/connectors/kandji/scope.toml +199 -0
  545. package/runtime/gatewaysdk/environment/schema/connectors/kandji/tests/tools.json +64 -0
  546. package/runtime/gatewaysdk/environment/schema/connectors/kandji/vendor-openapi.json +5463 -0
  547. package/runtime/gatewaysdk/environment/schema/connectors/kandji/world.json +1817 -0
  548. package/runtime/gatewaysdk/environment/schema/connectors/linear/api/handlers.py +139 -0
  549. package/runtime/gatewaysdk/environment/schema/connectors/linear/connector.toml +1574 -0
  550. package/runtime/gatewaysdk/environment/schema/connectors/linear/handlers.py +23 -0
  551. package/runtime/gatewaysdk/environment/schema/connectors/linear/provenance.json +142 -0
  552. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/scenario.toml +2 -0
  553. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/attachments.json +21 -0
  554. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/comments.json +79 -0
  555. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/customer_needs.json +21 -0
  556. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/customer_statuses.json +26 -0
  557. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/customer_tiers.json +26 -0
  558. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/customers.json +48 -0
  559. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/cycles.json +86 -0
  560. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/documents.json +27 -0
  561. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/initiative_projects.json +13 -0
  562. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/initiative_updates.json +23 -0
  563. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/initiatives.json +41 -0
  564. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/issue_labels.json +16 -0
  565. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/issue_relations.json +13 -0
  566. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/issues.json +264 -0
  567. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/labels.json +52 -0
  568. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/organizations.json +53 -0
  569. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/project_labels.json +34 -0
  570. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/project_members.json +16 -0
  571. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/project_milestones.json +30 -0
  572. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/project_relations.json +18 -0
  573. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/project_statuses.json +76 -0
  574. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/project_updates.json +42 -0
  575. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/projects.json +110 -0
  576. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/reactions.json +28 -0
  577. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/roadmap_projects.json +13 -0
  578. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/roadmaps.json +19 -0
  579. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/team_memberships.json +34 -0
  580. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/teams.json +114 -0
  581. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/templates.json +27 -0
  582. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/users.json +106 -0
  583. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/webhooks.json +21 -0
  584. package/runtime/gatewaysdk/environment/schema/connectors/linear/scenarios/default/seed/workflow_states.json +108 -0
  585. package/runtime/gatewaysdk/environment/schema/connectors/linear/scope.toml +87 -0
  586. package/runtime/gatewaysdk/environment/schema/connectors/linear/tests/tools.json +52 -0
  587. package/runtime/gatewaysdk/environment/schema/connectors/linear/world.json +6148 -0
  588. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/api/handlers.py +1218 -0
  589. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/connector.toml +1246 -0
  590. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/fidelity.json +75 -0
  591. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/handlers.py +1 -0
  592. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/provenance.json +1632 -0
  593. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/instruction.md +12 -0
  594. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/scenario.toml +2 -0
  595. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_async_operations.json +47 -0
  596. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_channel_hosted_contents.json +12 -0
  597. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_channel_members.json +88 -0
  598. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_channel_messages.json +313 -0
  599. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_channel_replies.json +128 -0
  600. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_channels.json +319 -0
  601. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_chat_hosted_contents.json +18 -0
  602. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_chat_members.json +155 -0
  603. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_chat_messages.json +265 -0
  604. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_chat_views.json +37 -0
  605. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_chats.json +167 -0
  606. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_incoming_channels.json +25 -0
  607. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_pinned_messages.json +9 -0
  608. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_reply_hosted_contents.json +13 -0
  609. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_shared_channel_teams.json +32 -0
  610. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_tag_members.json +31 -0
  611. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_tags.json +32 -0
  612. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_team_members.json +117 -0
  613. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scenarios/default/seed/teams_teams.json +193 -0
  614. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/scope.md +303 -0
  615. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/teams-types.json +1739 -0
  616. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/tests/routes.json +101 -0
  617. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/vendor-openapi.json +11280 -0
  618. package/runtime/gatewaysdk/environment/schema/connectors/microsoft-teams/world.json +926 -0
  619. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/api/handlers.py +571 -0
  620. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/connector.toml +1484 -0
  621. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/handlers.py +32 -0
  622. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/parity.json +77 -0
  623. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/provenance.json +303 -0
  624. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/instruction.md +11 -0
  625. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/scenario.toml +2 -0
  626. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_accounting_periods.json +107 -0
  627. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_accounts.json +514 -0
  628. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_classifications.json +64 -0
  629. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_contacts.json +90 -0
  630. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_credit_memos.json +112 -0
  631. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_currencies.json +37 -0
  632. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_customer_payments.json +108 -0
  633. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_customers.json +232 -0
  634. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_departments.json +80 -0
  635. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_employees.json +124 -0
  636. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_invoices.json +229 -0
  637. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_item_fulfillments.json +85 -0
  638. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_items.json +237 -0
  639. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_journal_entries.json +217 -0
  640. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_locations.json +62 -0
  641. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_price_levels.json +28 -0
  642. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_purchase_orders.json +152 -0
  643. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_sales_order_lines.json +235 -0
  644. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_sales_orders.json +219 -0
  645. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_subsidiaries.json +85 -0
  646. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_terms.json +48 -0
  647. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_vendor_bills.json +170 -0
  648. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scenarios/default/seed/netsuite_vendors.json +140 -0
  649. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/scope.toml +296 -0
  650. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/tests/tools.json +82 -0
  651. package/runtime/gatewaysdk/environment/schema/connectors/netsuite/world.json +39076 -0
  652. package/runtime/gatewaysdk/environment/schema/connectors/notion/api/handlers.py +1330 -0
  653. package/runtime/gatewaysdk/environment/schema/connectors/notion/connector.toml +386 -0
  654. package/runtime/gatewaysdk/environment/schema/connectors/notion/handlers.py +54 -0
  655. package/runtime/gatewaysdk/environment/schema/connectors/notion/scenarios/default/scenario.toml +2 -0
  656. package/runtime/gatewaysdk/environment/schema/connectors/notion/scenarios/default/seed/blocks.json +4197 -0
  657. package/runtime/gatewaysdk/environment/schema/connectors/notion/scenarios/default/seed/calendar_events.json +18 -0
  658. package/runtime/gatewaysdk/environment/schema/connectors/notion/scenarios/default/seed/collection_views.json +175 -0
  659. package/runtime/gatewaysdk/environment/schema/connectors/notion/scenarios/default/seed/comments.json +109 -0
  660. package/runtime/gatewaysdk/environment/schema/connectors/notion/scenarios/default/seed/databases.json +417 -0
  661. package/runtime/gatewaysdk/environment/schema/connectors/notion/scenarios/default/seed/favorites.json +3 -0
  662. package/runtime/gatewaysdk/environment/schema/connectors/notion/scenarios/default/seed/notifications.json +49 -0
  663. package/runtime/gatewaysdk/environment/schema/connectors/notion/scenarios/default/seed/pages.json +3758 -0
  664. package/runtime/gatewaysdk/environment/schema/connectors/notion/scenarios/default/seed/spaces.json +28 -0
  665. package/runtime/gatewaysdk/environment/schema/connectors/notion/scenarios/default/seed/teamspaces.json +3 -0
  666. package/runtime/gatewaysdk/environment/schema/connectors/notion/scenarios/default/seed/users.json +92 -0
  667. package/runtime/gatewaysdk/environment/schema/connectors/notion/tests/01-reads.json +165 -0
  668. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/assets/index-DQ36W7RG.css +1 -0
  669. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/assets/index-DythuuUy.js +67 -0
  670. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/avatars/eeee0000000000000000000000000002.svg +1 -0
  671. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/avatars/eeee0000000000000000000000000003.svg +1 -0
  672. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/avatars/eeee0000000000000000000000000004.svg +1 -0
  673. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/avatars/eeee0000000000000000000000000005.svg +1 -0
  674. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/avatars/eeee0000000000000000000000000006.svg +1 -0
  675. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/avatars/eeee0000000000000000000000000007.svg +1 -0
  676. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/avatars/eeee0000000000000000000000000008.svg +1 -0
  677. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/covers/dusk-harbor.png +0 -0
  678. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/covers/ember-coast.png +0 -0
  679. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/covers/green-ridge.png +0 -0
  680. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f30a.svg +1 -0
  681. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f331.svg +1 -0
  682. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f373.svg +1 -0
  683. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f3a7.svg +1 -0
  684. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f3a8.svg +1 -0
  685. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f3ac.svg +1 -0
  686. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f3af.svg +1 -0
  687. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f3c4.svg +1 -0
  688. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f3d6.svg +1 -0
  689. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f3e0.svg +1 -0
  690. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f44b.svg +1 -0
  691. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f4a1.svg +1 -0
  692. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f4b0.svg +1 -0
  693. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f4bc.svg +1 -0
  694. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f4c5.svg +1 -0
  695. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f4c8.svg +1 -0
  696. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f4cb.svg +1 -0
  697. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f4ce.svg +1 -0
  698. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f4d1.svg +1 -0
  699. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f4d3.svg +1 -0
  700. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f4d6.svg +1 -0
  701. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f4da.svg +1 -0
  702. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f4dd.svg +1 -0
  703. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f4ec.svg +1 -0
  704. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f4f7.svg +1 -0
  705. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f527.svg +1 -0
  706. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f55b.svg +1 -0
  707. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f5c2.svg +1 -0
  708. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f5d3.svg +1 -0
  709. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f680.svg +1 -0
  710. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f6a2.svg +1 -0
  711. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f9ca.svg +1 -0
  712. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f9e0.svg +1 -0
  713. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f9ea.svg +1 -0
  714. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f9ed.svg +1 -0
  715. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1f9f0.svg +1 -0
  716. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/1fab6.svg +1 -0
  717. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/2600.svg +1 -0
  718. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/2693.svg +1 -0
  719. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/2705.svg +1 -0
  720. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/2708.svg +1 -0
  721. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/270f.svg +1 -0
  722. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/emoji/2b50.svg +1 -0
  723. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/favicon.svg +1 -0
  724. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/fonts/SourceSerif4-latin.woff2 +0 -0
  725. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/index.html +31 -0
  726. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/learn/content-blocks.png +0 -0
  727. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/learn/databases.png +0 -0
  728. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/learn/sharing.png +0 -0
  729. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/learn/style-content.png +0 -0
  730. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/photos/home-icon.png +0 -0
  731. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/photos/viewer.png +0 -0
  732. package/runtime/gatewaysdk/environment/schema/connectors/notion/ui/static/photos/workspace.png +0 -0
  733. package/runtime/gatewaysdk/environment/schema/connectors/notion/world.json +2796 -0
  734. package/runtime/gatewaysdk/environment/schema/connectors/okta/scenarios/default/seed/okta_admin_role_assignments.json +44 -0
  735. package/runtime/gatewaysdk/environment/schema/connectors/okta/scenarios/default/seed/okta_app_assignments.json +40 -0
  736. package/runtime/gatewaysdk/environment/schema/connectors/okta/scenarios/default/seed/okta_app_group_assignments.json +59 -0
  737. package/runtime/gatewaysdk/environment/schema/connectors/okta/scenarios/default/seed/okta_applications.json +265 -0
  738. package/runtime/gatewaysdk/environment/schema/connectors/okta/scenarios/default/seed/okta_console_dashboards.json +91 -0
  739. package/runtime/gatewaysdk/environment/schema/connectors/okta/scenarios/default/seed/okta_device_users.json +32 -0
  740. package/runtime/gatewaysdk/environment/schema/connectors/okta/scenarios/default/seed/okta_devices.json +89 -0
  741. package/runtime/gatewaysdk/environment/schema/connectors/okta/scenarios/default/seed/okta_group_memberships.json +156 -0
  742. package/runtime/gatewaysdk/environment/schema/connectors/okta/scenarios/default/seed/okta_groups.json +100 -0
  743. package/runtime/gatewaysdk/environment/schema/connectors/okta/scenarios/default/seed/okta_orgs.json +20 -0
  744. package/runtime/gatewaysdk/environment/schema/connectors/okta/scenarios/default/seed/okta_policies.json +84 -0
  745. package/runtime/gatewaysdk/environment/schema/connectors/okta/scenarios/default/seed/okta_system_log_events.json +9656 -0
  746. package/runtime/gatewaysdk/environment/schema/connectors/okta/scenarios/default/seed/okta_users.json +744 -0
  747. package/runtime/gatewaysdk/environment/schema/connectors/outlook/api/handlers.py +624 -0
  748. package/runtime/gatewaysdk/environment/schema/connectors/outlook/connector.toml +381 -0
  749. package/runtime/gatewaysdk/environment/schema/connectors/outlook/handlers.py +54 -0
  750. package/runtime/gatewaysdk/environment/schema/connectors/outlook/provenance.json +408 -0
  751. package/runtime/gatewaysdk/environment/schema/connectors/outlook/scenarios/default/instruction.md +22 -0
  752. package/runtime/gatewaysdk/environment/schema/connectors/outlook/scenarios/default/scenario.toml +2 -0
  753. package/runtime/gatewaysdk/environment/schema/connectors/outlook/scenarios/default/seed/outlook_attachments.json +44 -0
  754. package/runtime/gatewaysdk/environment/schema/connectors/outlook/scenarios/default/seed/outlook_calendars.json +52 -0
  755. package/runtime/gatewaysdk/environment/schema/connectors/outlook/scenarios/default/seed/outlook_contacts.json +326 -0
  756. package/runtime/gatewaysdk/environment/schema/connectors/outlook/scenarios/default/seed/outlook_events.json +3050 -0
  757. package/runtime/gatewaysdk/environment/schema/connectors/outlook/scenarios/default/seed/outlook_mail_folders.json +84 -0
  758. package/runtime/gatewaysdk/environment/schema/connectors/outlook/scenarios/default/seed/outlook_mailbox_settings.json +35 -0
  759. package/runtime/gatewaysdk/environment/schema/connectors/outlook/scenarios/default/seed/outlook_mailboxes.json +14 -0
  760. package/runtime/gatewaysdk/environment/schema/connectors/outlook/scenarios/default/seed/outlook_messages.json +1400 -0
  761. package/runtime/gatewaysdk/environment/schema/connectors/outlook/scenarios/default/seed/outlook_system_senders.json +44 -0
  762. package/runtime/gatewaysdk/environment/schema/connectors/outlook/scenarios/default/seed/outlook_users.json +256 -0
  763. package/runtime/gatewaysdk/environment/schema/connectors/outlook/tests/routes.json +333 -0
  764. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/assets/index-DRVA5ahH.js +67 -0
  765. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/assets/index-kOnvVBhA.css +1 -0
  766. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/fonts/FluentSystemIcons-Filled.woff2 +0 -0
  767. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/fonts/FluentSystemIcons-Regular.woff2 +0 -0
  768. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/fonts/FluentSystemIcons-Resizable.woff2 +0 -0
  769. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/fonts/controlIcons.woff +0 -0
  770. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/fonts/segoeui-bold.woff2 +0 -0
  771. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/fonts/segoeui-light.woff2 +0 -0
  772. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/fonts/segoeui-regular.woff2 +0 -0
  773. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/fonts/segoeui-semibold.woff2 +0 -0
  774. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/fonts/segoeui-semilight.woff2 +0 -0
  775. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/bookings.svg +1 -0
  776. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/calendar.svg +35 -0
  777. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/copilot.png +0 -0
  778. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/excel.svg +1 -0
  779. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/mail.svg +32 -0
  780. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/my-day.svg +1 -0
  781. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/newsletters.svg +37 -0
  782. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/no-mail-selected-dark.svg +1 -0
  783. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/no-mail-selected.svg +1 -0
  784. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/onedrive.svg +1 -0
  785. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/onenote.svg +1 -0
  786. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/org-explorer.png +0 -0
  787. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/outlook.svg +1 -0
  788. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/people.svg +34 -0
  789. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/powerpoint.svg +1 -0
  790. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/ribbon-layout.svg +1 -0
  791. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/sharepoint.svg +1 -0
  792. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/teams-chat.svg +1 -0
  793. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/teams.svg +1 -0
  794. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/to-do.png +0 -0
  795. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/viva.svg +1 -0
  796. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/img/word.svg +1 -0
  797. package/runtime/gatewaysdk/environment/schema/connectors/outlook/ui/static/index.html +34 -0
  798. package/runtime/gatewaysdk/environment/schema/connectors/outlook/world.json +686 -0
  799. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/api/handlers.py +447 -0
  800. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/connector.toml +3478 -0
  801. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/handlers.py +885 -0
  802. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/parity.json +46 -0
  803. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/provenance.json +4286 -0
  804. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/instruction.md +8 -0
  805. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/scenario.toml +2 -0
  806. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_account_contact_relations.json +20 -0
  807. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_account_contact_roles.json +16 -0
  808. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_account_partners.json +18 -0
  809. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_account_team_members.json +16 -0
  810. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_accounts.json +38 -0
  811. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_assets.json +35 -0
  812. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_attachments.json +16 -0
  813. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_business_hours.json +16 -0
  814. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_campaign_member_statuses.json +16 -0
  815. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_campaign_members.json +38 -0
  816. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_campaigns.json +35 -0
  817. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_case_comments.json +14 -0
  818. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_case_histories.json +18 -0
  819. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_case_milestones.json +18 -0
  820. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_case_statuses.json +16 -0
  821. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_case_team_members.json +14 -0
  822. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_case_team_roles.json +12 -0
  823. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_cases.json +42 -0
  824. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_collaboration_group_members.json +16 -0
  825. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_collaboration_groups.json +16 -0
  826. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_contact_point_addresses.json +14 -0
  827. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_contact_point_emails.json +14 -0
  828. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_contact_point_phones.json +14 -0
  829. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_contacts.json +34 -0
  830. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_content_document_links.json +14 -0
  831. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_content_documents.json +18 -0
  832. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_content_folders.json +13 -0
  833. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_content_notes.json +12 -0
  834. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_content_versions.json +24 -0
  835. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_content_workspaces.json +16 -0
  836. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_contract_contact_roles.json +16 -0
  837. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_contract_line_items.json +32 -0
  838. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_contracts.json +40 -0
  839. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_dashboards.json +20 -0
  840. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_documents.json +22 -0
  841. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_email_message_relations.json +14 -0
  842. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_email_messages.json +21 -0
  843. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_email_templates.json +24 -0
  844. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_entitlements.json +32 -0
  845. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_events.json +26 -0
  846. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_feed_comments.json +19 -0
  847. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_feed_items.json +24 -0
  848. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_fiscal_year_settings.json +20 -0
  849. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_folders.json +18 -0
  850. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_group_members.json +12 -0
  851. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_groups.json +20 -0
  852. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_holidays.json +16 -0
  853. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_individuals.json +21 -0
  854. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_lead_statuses.json +14 -0
  855. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_leads.json +45 -0
  856. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_list_views.json +16 -0
  857. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_login_histories.json +18 -0
  858. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_milestone_types.json +14 -0
  859. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_notes.json +16 -0
  860. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_object_territory_associations.json +14 -0
  861. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_opportunities.json +48 -0
  862. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_opportunity_competitors.json +12 -0
  863. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_opportunity_contact_roles.json +16 -0
  864. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_opportunity_field_histories.json +18 -0
  865. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_opportunity_histories.json +20 -0
  866. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_opportunity_line_items.json +32 -0
  867. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_opportunity_partners.json +16 -0
  868. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_opportunity_stages.json +22 -0
  869. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_opportunity_team_members.json +18 -0
  870. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_order_items.json +33 -0
  871. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_orders.json +44 -0
  872. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_organizations.json +18 -0
  873. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_partners.json +18 -0
  874. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_periods.json +18 -0
  875. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_permission_set_assignments.json +16 -0
  876. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_permission_sets.json +18 -0
  877. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_pricebook_entries.json +22 -0
  878. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_pricebooks.json +16 -0
  879. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_products.json +20 -0
  880. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_profiles.json +14 -0
  881. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_queue_sobjects.json +12 -0
  882. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_quote_line_items.json +43 -0
  883. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_quotes.json +40 -0
  884. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_record_actions.json +16 -0
  885. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_record_types.json +18 -0
  886. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_reports.json +18 -0
  887. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_service_contracts.json +32 -0
  888. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_sla_processes.json +18 -0
  889. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_solutions.json +18 -0
  890. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_task_priorities.json +14 -0
  891. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_task_relations.json +14 -0
  892. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_task_statuses.json +16 -0
  893. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_tasks.json +26 -0
  894. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_territories.json +20 -0
  895. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_territory_models.json +16 -0
  896. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_territory_types.json +18 -0
  897. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_topic_assignments.json +12 -0
  898. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_topics.json +14 -0
  899. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_user_roles.json +16 -0
  900. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_user_territory_associations.json +16 -0
  901. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_users.json +57 -0
  902. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_web_links.json +26 -0
  903. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_work_order_line_items.json +42 -0
  904. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scenarios/default/seed/sf_work_orders.json +46 -0
  905. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/scope.toml +694 -0
  906. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/tests/tools.json +69 -0
  907. package/runtime/gatewaysdk/environment/schema/connectors/salesforce/world.json +21263 -0
  908. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/api/handlers.py +630 -0
  909. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/connector.toml +266 -0
  910. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/handlers.py +3 -0
  911. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/provenance.json +245 -0
  912. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/instruction.md +15 -0
  913. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/scenario.toml +1 -0
  914. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/10-snow_users.json +268 -0
  915. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/11-snow_user_groups.json +40 -0
  916. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/20-snow_configuration_items.json +684 -0
  917. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/30-snow_catalog_categories.json +52 -0
  918. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/31-snow_catalog_items.json +334 -0
  919. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/40-snow_incidents.json +3086 -0
  920. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/41-snow_incident_tasks.json +54 -0
  921. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/42-snow_task_slas.json +64 -0
  922. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/43-snow_problems.json +148 -0
  923. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/44-snow_change_requests.json +364 -0
  924. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/45-snow_knowledge_articles.json +214 -0
  925. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/46-snow_journal_entries.json +1612 -0
  926. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/60-snow_ui_current_users.json +19 -0
  927. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/61-snow_ui_navigation_applications.json +187 -0
  928. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/62-snow_ui_home_widgets.json +91 -0
  929. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/63-snow_ui_notifications.json +3 -0
  930. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/64-snow_ui_employee_center_pages.json +74 -0
  931. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/65-snow_ui_list_layouts.json +54 -0
  932. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/66-snow_ui_search_facets.json +29 -0
  933. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/67-snow_ui_activity_entries.json +1076 -0
  934. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scenarios/default/seed/68-snow_ui_instances.json +9 -0
  935. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/scope.toml +166 -0
  936. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/tests/routes.json +272 -0
  937. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/assets/index-5QHcQLCI.css +1 -0
  938. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/assets/index-BzeVnzFt.js +67 -0
  939. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/cabin-400-700-italic.woff2 +0 -0
  940. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/cabin-400-700.woff2 +0 -0
  941. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-0-lato-v17-latin-ext_latin-100.woff2 +0 -0
  942. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-1-lato-v17-latin-ext_latin-100.woff +0 -0
  943. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-10-lato-v17-latin-ext_latin-italic.woff2 +0 -0
  944. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-11-lato-v17-latin-ext_latin-italic.woff +0 -0
  945. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-12-lato-v17-latin-ext_latin-700.woff2 +0 -0
  946. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-13-lato-v17-latin-ext_latin-700.woff +0 -0
  947. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-14-lato-v17-latin-ext_latin-700italic.woff2 +0 -0
  948. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-15-lato-v17-latin-ext_latin-700italic.woff +0 -0
  949. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-16-source-sans-pro-v11-latin-300.woff2 +0 -0
  950. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-17-source-sans-pro-v11-latin-300.woff +0 -0
  951. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-18-source-sans-pro-v11-latin-regular.woff2 +0 -0
  952. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-19-source-sans-pro-v11-latin-regular.woff +0 -0
  953. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-2-lato-v17-latin-ext_latin-100italic.woff2 +0 -0
  954. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-20-source-sans-pro-v11-latin-600.woff2 +0 -0
  955. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-21-source-sans-pro-v11-latin-600.woff +0 -0
  956. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-22-source-sans-pro-v11-latin-700.woff2 +0 -0
  957. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-23-source-sans-pro-v11-latin-700.woff +0 -0
  958. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-3-lato-v17-latin-ext_latin-100italic.woff +0 -0
  959. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-4-lato-v17-latin-ext_latin-300.woff2 +0 -0
  960. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-5-lato-v17-latin-ext_latin-300.woff +0 -0
  961. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-6-lato-v17-latin-ext_latin-300italic.woff2 +0 -0
  962. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-7-lato-v17-latin-ext_latin-300italic.woff +0 -0
  963. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-8-lato-v17-latin-ext_latin-regular.woff2 +0 -0
  964. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/font-9-lato-v17-latin-ext_latin-regular.woff +0 -0
  965. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/index.json +122 -0
  966. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/lato-300.woff2 +0 -0
  967. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/lato-600-italic.woff2 +0 -0
  968. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/lato-600.woff2 +0 -0
  969. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/lato-bold-italic.woff2 +0 -0
  970. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/lato-bold.woff2 +0 -0
  971. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/lato-normal-italic.woff2 +0 -0
  972. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/fonts/lato-normal.woff2 +0 -0
  973. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/appsee-outline.svg +1 -0
  974. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/arrow-up-outline.svg +1 -0
  975. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/available.svg +1 -0
  976. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/bell-outline.svg +1 -0
  977. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/caret-down-fill.svg +1 -0
  978. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/check-fill.svg +1 -0
  979. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/chevron-right-outline.svg +1 -0
  980. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/circle-close-outline.svg +1 -0
  981. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/circle-info-outline.svg +1 -0
  982. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/circle-question-outline.svg +1 -0
  983. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/circleinfooutline.svg +1 -0
  984. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/ellipsis-v-outline.svg +1 -0
  985. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/eye-outline.svg +1 -0
  986. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-bell-fill.svg +1 -0
  987. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-caret-down-fill.svg +1 -0
  988. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-check-square.svg +1 -0
  989. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-chevron-right.svg +1 -0
  990. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-clock-outline.svg +1 -0
  991. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-comment-chat.svg +1 -0
  992. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-external-link.svg +1 -0
  993. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-facebook.svg +1 -0
  994. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-heart-fill.svg +1 -0
  995. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-heart-outline.svg +1 -0
  996. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-home-fill-teal.svg +1 -0
  997. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-home-fill.svg +1 -0
  998. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-linkedin.svg +1 -0
  999. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-list-alt-fill.svg +1 -0
  1000. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-pencil-square.svg +1 -0
  1001. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-question-circle-fill.svg +1 -0
  1002. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-times.svg +1 -0
  1003. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/fa-twitter.svg +1 -0
  1004. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/filter-outline.svg +1 -0
  1005. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/gear-outline.svg +1 -0
  1006. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/globe-outline.svg +1 -0
  1007. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/home-outline.svg +1 -0
  1008. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/icon-2.svg +17 -0
  1009. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/icon-3.svg +1 -0
  1010. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/icon-4.svg +1 -0
  1011. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/icon.svg +45 -0
  1012. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/keyboard-outline.svg +1 -0
  1013. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/link-icon-associated-to-view-all-adoption-blueprints.svg +1 -0
  1014. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/link-icon-associated-to-view-all-applications.svg +1 -0
  1015. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/list-fill.svg +1 -0
  1016. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/loading-2.svg +1 -0
  1017. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/loading.svg +1 -0
  1018. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/magnifying-glass-outline.svg +1 -0
  1019. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/ongoing-outline.svg +1 -0
  1020. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/open-link-right-fill.svg +1 -0
  1021. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/open-link-right-outline.svg +1 -0
  1022. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/pencil-page-outline.svg +1 -0
  1023. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/plus-fill.svg +1 -0
  1024. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/serverbox-outline.svg +1 -0
  1025. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/servicenow-wordmark.svg +20 -0
  1026. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/signal-live-outline.svg +1 -0
  1027. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/square-arrow-left-outline.svg +1 -0
  1028. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/star-outline.svg +1 -0
  1029. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/sync-outline.svg +1 -0
  1030. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/task-slas-related-list.svg +24 -0
  1031. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/thumbtack-outline.svg +1 -0
  1032. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/trending-downward.svg +1 -0
  1033. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/trending-neutral.svg +1 -0
  1034. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/unpinned-all-menu.svg +1 -0
  1035. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/unpinned-favorites-menu.svg +1 -0
  1036. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/unpinned-history-menu.svg +1 -0
  1037. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/icons/user-outline.svg +1 -0
  1038. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/img/adoption-blueprints.svg +40 -0
  1039. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/img/avatar-admin.jpg +0 -0
  1040. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/img/now-assist-admin.svg +17 -0
  1041. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/img/quick-link-desk.jpg +0 -0
  1042. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/img/quick-link-password.jpg +0 -0
  1043. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/img/quick-link-status.jpg +0 -0
  1044. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/img/topic-accessories.svg +1 -0
  1045. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/img/topic-computers.svg +1 -0
  1046. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/img/topic-developer.svg +1 -0
  1047. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/img/topic-email.svg +1 -0
  1048. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/img/topic-phone.svg +1 -0
  1049. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/img/topic-software-catalog.svg +1 -0
  1050. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/img/topic-software.svg +1 -0
  1051. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/img/topic-technology.svg +1 -0
  1052. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/ui/static/index.html +36 -0
  1053. package/runtime/gatewaysdk/environment/schema/connectors/servicenow/world.json +2004 -0
  1054. package/runtime/gatewaysdk/environment/schema/connectors/slack/MODEL.md +264 -0
  1055. package/runtime/gatewaysdk/environment/schema/connectors/slack/api/handlers.py +1880 -0
  1056. package/runtime/gatewaysdk/environment/schema/connectors/slack/capabilities.json +1056 -0
  1057. package/runtime/gatewaysdk/environment/schema/connectors/slack/connector.toml +892 -0
  1058. package/runtime/gatewaysdk/environment/schema/connectors/slack/handlers.py +762 -0
  1059. package/runtime/gatewaysdk/environment/schema/connectors/slack/parity.json +65 -0
  1060. package/runtime/gatewaysdk/environment/schema/connectors/slack/provenance.json +349 -0
  1061. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/scenario.toml +1 -0
  1062. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_apps.json +22 -0
  1063. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_bookmarks.json +22 -0
  1064. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_bots.json +19 -0
  1065. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_channels.json +206 -0
  1066. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_conversation_states.json +50 -0
  1067. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_emojis.json +19 -0
  1068. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_ephemeral_message_files.json +12 -0
  1069. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_ephemeral_message_threads.json +11 -0
  1070. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_ephemeral_messages.json +16 -0
  1071. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_file_channel_observations.json +16 -0
  1072. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_file_reaction_summaries.json +10 -0
  1073. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_file_reaction_users.json +10 -0
  1074. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_file_shares.json +29 -0
  1075. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_file_user_states.json +10 -0
  1076. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_files.json +64 -0
  1077. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_memberships.json +79 -0
  1078. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_message_files.json +18 -0
  1079. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_message_threads.json +10 -0
  1080. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_message_user_states.json +14 -0
  1081. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_messages.json +127 -0
  1082. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_pins.json +11 -0
  1083. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_presence.json +35 -0
  1084. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_reaction_summaries.json +25 -0
  1085. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_reaction_users.json +32 -0
  1086. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_scheduled_message_threads.json +10 -0
  1087. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_scheduled_messages.json +15 -0
  1088. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_unavailable_message_files.json +14 -0
  1089. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_user_profile_fields.json +28 -0
  1090. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_usergroup_channels.json +10 -0
  1091. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_usergroup_memberships.json +14 -0
  1092. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_usergroups.json +33 -0
  1093. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_users.json +228 -0
  1094. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_view_state_entries.json +22 -0
  1095. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_views.json +53 -0
  1096. package/runtime/gatewaysdk/environment/schema/connectors/slack/scenarios/default/seed/slack_workspaces.json +37 -0
  1097. package/runtime/gatewaysdk/environment/schema/connectors/slack/scope.toml +48 -0
  1098. package/runtime/gatewaysdk/environment/schema/connectors/slack/tests/api.json +177 -0
  1099. package/runtime/gatewaysdk/environment/schema/connectors/slack/tests/test_threads.py +49 -0
  1100. package/runtime/gatewaysdk/environment/schema/connectors/slack/tests/tools.json +92 -0
  1101. package/runtime/gatewaysdk/environment/schema/connectors/slack/ui/static/assets/index-BSqGskph.css +1 -0
  1102. package/runtime/gatewaysdk/environment/schema/connectors/slack/ui/static/assets/index-CKQh1igo.js +81 -0
  1103. package/runtime/gatewaysdk/environment/schema/connectors/slack/ui/static/fonts/README.md +15 -0
  1104. package/runtime/gatewaysdk/environment/schema/connectors/slack/ui/static/fonts/lato-black.woff2 +0 -0
  1105. package/runtime/gatewaysdk/environment/schema/connectors/slack/ui/static/fonts/lato-bold.woff2 +0 -0
  1106. package/runtime/gatewaysdk/environment/schema/connectors/slack/ui/static/fonts/lato-italic-black.woff2 +0 -0
  1107. package/runtime/gatewaysdk/environment/schema/connectors/slack/ui/static/fonts/lato-italic-bold.woff2 +0 -0
  1108. package/runtime/gatewaysdk/environment/schema/connectors/slack/ui/static/fonts/lato-italic-light.woff2 +0 -0
  1109. package/runtime/gatewaysdk/environment/schema/connectors/slack/ui/static/fonts/lato-italic.woff2 +0 -0
  1110. package/runtime/gatewaysdk/environment/schema/connectors/slack/ui/static/fonts/lato-light.woff2 +0 -0
  1111. package/runtime/gatewaysdk/environment/schema/connectors/slack/ui/static/fonts/lato-regular.woff2 +0 -0
  1112. package/runtime/gatewaysdk/environment/schema/connectors/slack/ui/static/fonts/slack-icons-v2.woff2 +0 -0
  1113. package/runtime/gatewaysdk/environment/schema/connectors/slack/ui/static/index.html +35 -0
  1114. package/runtime/gatewaysdk/environment/schema/connectors/slack/vendor-openapi.json +12515 -0
  1115. package/runtime/gatewaysdk/environment/schema/connectors/slack/world.json +5381 -0
  1116. package/runtime/gatewaysdk/environment/schema/connectors/workday/api/handlers.py +175 -0
  1117. package/runtime/gatewaysdk/environment/schema/connectors/workday/connector.toml +610 -0
  1118. package/runtime/gatewaysdk/environment/schema/connectors/workday/handlers.py +75 -0
  1119. package/runtime/gatewaysdk/environment/schema/connectors/workday/parity.json +69 -0
  1120. package/runtime/gatewaysdk/environment/schema/connectors/workday/provenance.json +407 -0
  1121. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/instruction.md +10 -0
  1122. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/scenario.toml +2 -0
  1123. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_compensations.json +219 -0
  1124. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_job_profiles.json +76 -0
  1125. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_locations.json +142 -0
  1126. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_organizations.json +124 -0
  1127. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_positions.json +280 -0
  1128. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_absence_leaves.json +66 -0
  1129. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_business_title_changes.json +44 -0
  1130. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_check_in_topics.json +48 -0
  1131. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_check_ins.json +46 -0
  1132. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_countries.json +28 -0
  1133. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_currencies.json +25 -0
  1134. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_job_change_reasons.json +28 -0
  1135. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_job_families.json +40 -0
  1136. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_job_profiles.json +202 -0
  1137. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_jobs.json +120 -0
  1138. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_organization_types.json +19 -0
  1139. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_organizations.json +24 -0
  1140. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_persons.json +100 -0
  1141. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_scorecard_results.json +57 -0
  1142. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_scorecards.json +68 -0
  1143. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_supervisory_organizations.json +64 -0
  1144. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_time_off_details.json +112 -0
  1145. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_time_off_entries.json +91 -0
  1146. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_worker_history_events.json +58 -0
  1147. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_rest_workers.json +90 -0
  1148. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_time_off_requests.json +181 -0
  1149. package/runtime/gatewaysdk/environment/schema/connectors/workday/scenarios/default/seed/workday_workers.json +492 -0
  1150. package/runtime/gatewaysdk/environment/schema/connectors/workday/scope.toml +344 -0
  1151. package/runtime/gatewaysdk/environment/schema/connectors/workday/tests/tools.json +81 -0
  1152. package/runtime/gatewaysdk/environment/schema/connectors/workday/vendor-openapi.json +10646 -0
  1153. package/runtime/gatewaysdk/environment/schema/connectors/workday/world.json +4186 -0
  1154. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/api/handlers.py +1183 -0
  1155. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/connector.toml +645 -0
  1156. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/handlers.py +377 -0
  1157. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/scenarios/default/instruction.md +22 -0
  1158. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/scenarios/default/scenario.toml +3 -0
  1159. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/scenarios/default/seed/zendesk_brands.json +25 -0
  1160. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/scenarios/default/seed/zendesk_group_memberships.json +49 -0
  1161. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/scenarios/default/seed/zendesk_groups.json +37 -0
  1162. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/scenarios/default/seed/zendesk_macros.json +154 -0
  1163. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/scenarios/default/seed/zendesk_organizations.json +65 -0
  1164. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/scenarios/default/seed/zendesk_ticket_audits.json +3328 -0
  1165. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/scenarios/default/seed/zendesk_ticket_comments.json +2642 -0
  1166. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/scenarios/default/seed/zendesk_tickets.json +1439 -0
  1167. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/scenarios/default/seed/zendesk_users.json +624 -0
  1168. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/scenarios/default/seed/zendesk_views.json +510 -0
  1169. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/scenarios/default/seed/zendesk_workspace_tabs.json +10 -0
  1170. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/ui/static/assets/index-JWq7XNO5.css +1 -0
  1171. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/ui/static/assets/index-bn8ezNTi.js +67 -0
  1172. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/ui/static/index.html +22 -0
  1173. package/runtime/gatewaysdk/environment/schema/connectors/zendesk/world.json +1707 -0
  1174. package/runtime/gatewaysdk/environment/schema/data.py +907 -0
  1175. package/runtime/gatewaysdk/environment/schema/dependencies.py +235 -0
  1176. package/runtime/gatewaysdk/environment/schema/extract.py +263 -0
  1177. package/runtime/gatewaysdk/environment/schema/host.py +2571 -0
  1178. package/runtime/gatewaysdk/environment/schema/host_surfaces.py +320 -0
  1179. package/runtime/gatewaysdk/environment/schema/ingest.py +528 -0
  1180. package/runtime/gatewaysdk/environment/schema/local.py +536 -0
  1181. package/runtime/gatewaysdk/environment/schema/mapping.py +944 -0
  1182. package/runtime/gatewaysdk/environment/schema/platform.py +1748 -0
  1183. package/runtime/gatewaysdk/environment/schema/reconcile.py +202 -0
  1184. package/runtime/gatewaysdk/environment/schema/redaction.py +378 -0
  1185. package/runtime/gatewaysdk/environment/schema/scaffold.py +311 -0
  1186. package/runtime/gatewaysdk/environment/schema/skill.py +119 -0
  1187. package/runtime/gatewaysdk/environment/schema/skills/agents/connector-template-author.md +202 -0
  1188. package/runtime/gatewaysdk/environment/schema/skills/benchmarks-getting-started/SKILL.md +391 -0
  1189. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/CONNECTORS.md +364 -0
  1190. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/CONVENTIONS.md +100 -0
  1191. package/runtime/gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +363 -0
  1192. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +243 -0
  1193. package/runtime/gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +460 -0
  1194. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +500 -0
  1195. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/cli-mcp-map.md +49 -0
  1196. package/runtime/gatewaysdk/environment/schema/skills/worlds-getting-started/references/ui-map.md +18 -0
  1197. package/runtime/gatewaysdk/environment/schema/slack.py +757 -0
  1198. package/runtime/gatewaysdk/environment/schema/snapshot.py +479 -0
  1199. package/runtime/gatewaysdk/environment/schema/store.py +1004 -0
  1200. package/runtime/gatewaysdk/environment/schema/tasks.py +530 -0
  1201. package/runtime/gatewaysdk/environment/schema/tools_world.py +689 -0
  1202. package/runtime/gatewaysdk/environment/schema/transform.py +200 -0
  1203. package/runtime/gatewaysdk/environment/schema/transforms.py +103 -0
  1204. package/runtime/gatewaysdk/environment/schema/ui.py +455 -0
  1205. package/runtime/gatewaysdk/environment/schema/ui_static/app.js +581 -0
  1206. package/runtime/gatewaysdk/environment/schema/ui_static/index.html +72 -0
  1207. package/runtime/gatewaysdk/environment/schema/validation.py +624 -0
  1208. package/runtime/gatewaysdk/environment/schema/worker.py +78 -0
  1209. package/runtime/gatewaysdk/environment/schema/workers.py +500 -0
  1210. package/runtime/gatewaysdk/environment/schema/world_tests.py +530 -0
  1211. package/skills/agents/connector-template-author.md +202 -0
  1212. package/skills/benchmarks-getting-started/SKILL.md +391 -0
  1213. package/skills/connector-schema-authoring/CONNECTORS.md +364 -0
  1214. package/skills/connector-schema-authoring/CONVENTIONS.md +100 -0
  1215. package/skills/connector-schema-authoring/SKILL.md +363 -0
  1216. package/skills/connector-schema-authoring/connector-worlds.md +355 -0
  1217. package/skills/connector-schema-authoring/world-schema.md +620 -0
  1218. package/skills/world-data-ingestion/ROWS.md +243 -0
  1219. package/skills/world-data-ingestion/SKILL.md +460 -0
  1220. package/skills/worlds-getting-started/SKILL.md +500 -0
  1221. package/skills/worlds-getting-started/references/cli-mcp-map.md +49 -0
  1222. package/skills/worlds-getting-started/references/ui-map.md +18 -0
package/dist/cli.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/worlds/session.ts","../src/worlds/hub.ts","../src/worlds/validate.ts","../src/worlds/index.ts","../src/cli.ts"],"sourcesContent":["import { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * LIVE WORLD SESSIONS from TypeScript: your agent, the platform's container.\n *\n * The other two ways of running a world each give up something. Pulling the\n * bundle and executing it locally tests your agent against a COPY — your\n * python, your sqlite, your machine's idea of the environment. Dispatching a\n * hosted run gives you the real container but runs the platform's agent\n * inside it, so your agent never touches the world.\n *\n * A session is both: the platform boots the task's container and holds it\n * warm, and every `call()` here executes inside THAT container. Your agent\n * stays where it is — this file is just the wire.\n *\n * const world = await openWorld(\"revenue-ops-sim@main\");\n * const session = await openSession(world.slug, \"revops-mara-dedupe-contacts\");\n * await session.ready(); // wait for the container\n * await session.call(\"crm_search\", { entity: \"deals\" });\n * const { reward, rewards } = await session.grade();\n * await session.close({ keepWarm: true }); // hand it back to the pool\n *\n * Every call is a row on the platform before it is an effect in a container,\n * so the episode is on the record — and the platform traces the session\n * itself, which is why these sessions show up under Sessions without the\n * caller instrumenting anything.\n */\n\nexport type WorldToolSpec = {\n name: string;\n /** The world's own signature, e.g. `crm_search(q=None, entity=\"deals\")`. */\n signature: string;\n doc: string | null;\n};\n\n/** What a model needs to call a world: the schemas to advertise, and the\n * implementations that run them in the container. */\nexport type WorldToolkit = {\n /** OpenAI-shaped tool definitions, derived from the world's signatures. */\n schemas: {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n }[];\n /** name -> implementation, each one a call into THIS session. */\n impls: Record<string, (args: Record<string, unknown>) => Promise<unknown>>;\n specs: WorldToolSpec[];\n};\n\nexport type WorldSessionState = {\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n /** The task's objective — present when the session was opened (not on a\n * bare status read), so a client never needs the bundle on disk. */\n instruction?: string | null;\n /** The tools this task serves. */\n tools?: WorldToolSpec[];\n};\n\nexport type GradeResult = {\n reward: number | null;\n rewards: Record<string, number>;\n raw: unknown;\n};\n\n/** How long `ready()` waits, and how often it asks. */\nconst READY_TIMEOUT_MS = 10 * 60_000;\nconst READY_POLL_MS = 2_000;\n/** How long one call may take end to end (container claim + execution). */\nconst CALL_TIMEOUT_MS = 3 * 60_000;\nconst CALL_POLL_MS = 400;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\n/**\n * Turn a world's Python signature into a JSON schema the model can call.\n *\n * `crm_update_deal(id, stage=None, owner=None, amount=None)` becomes an\n * object with `id` required and the rest optional. Types are read from the\n * DEFAULTS the world declares — a numeric default means a number, a boolean\n * default a boolean — because that is the only type information a signature\n * actually carries. Everything else is a string, which is what a tool CLI\n * receives anyway.\n */\nexport function schemaFromSignature(spec: WorldToolSpec): {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n} {\n const inside = /\\(([\\s\\S]*)\\)\\s*$/.exec(spec.signature.trim())?.[1] ?? \"\";\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n // Split on top-level commas only: a default like `{\"a\": 1}` has its own.\n const params: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of inside) {\n if (\"([{\".includes(ch)) depth++;\n if (\")]}\".includes(ch)) depth--;\n if (ch === \",\" && depth === 0) {\n params.push(current);\n current = \"\";\n } else current += ch;\n }\n if (current.trim()) params.push(current);\n\n for (const raw of params) {\n const param = raw.trim();\n if (!param || param.startsWith(\"*\") || param === \"self\") continue;\n const eq = param.indexOf(\"=\");\n const name = (eq === -1 ? param : param.slice(0, eq)).split(\":\")[0].trim();\n if (!name) continue;\n if (eq === -1) {\n properties[name] = { type: \"string\" };\n required.push(name);\n continue;\n }\n const value = param.slice(eq + 1).trim();\n if (/^-?\\d+(\\.\\d+)?$/.test(value)) properties[name] = { type: \"number\" };\n else if (value === \"True\" || value === \"False\")\n properties[name] = { type: \"boolean\" };\n else properties[name] = { type: \"string\" };\n }\n return {\n type: \"function\",\n function: {\n name: spec.name,\n description: spec.doc ?? spec.name,\n parameters: { type: \"object\", properties, required },\n },\n };\n}\n\nexport class WorldSessionTimeout extends Error {}\nexport class WorldSessionCallError extends Error {}\n\nexport class WorldSession {\n constructor(\n readonly sessionId: string,\n private state: WorldSessionState,\n private readonly options: WorldsClientOptions,\n ) {}\n\n get task(): string | null {\n return this.state.taskName;\n }\n\n /** What this task asks for — the bundle's own instruction.md. */\n get instruction(): string | null {\n return this.state.instruction ?? null;\n }\n\n get versionId(): string {\n return this.state.versionId;\n }\n\n /** The session's latest platform state (one request, no waiting). */\n async status(): Promise<WorldSessionState> {\n const fresh = await apiRequest<WorldSessionState>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n );\n // A status read does not carry the objective; keep the one we opened with.\n this.state = {\n instruction: this.state.instruction,\n tools: this.state.tools,\n ...fresh,\n };\n return this.state;\n }\n\n /**\n * Wait until the container is warm — meaning the process inside it has\n * asked the platform for work, not merely that a job was accepted.\n */\n async ready(opts: { timeoutMs?: number } = {}): Promise<WorldSessionState> {\n const deadline = Date.now() + (opts.timeoutMs ?? READY_TIMEOUT_MS);\n for (;;) {\n const state = await this.status();\n if (state.ready) return state;\n if (state.state === \"FAILED\" || state.state === \"STOPPED\")\n throw new WorldSessionCallError(\n `World session ${state.state.toLowerCase()} before it was ready.`,\n );\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n `World session still ${state.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1000)}s.`,\n );\n await sleep(READY_POLL_MS);\n }\n }\n\n /** Enqueue one interaction and wait for the container's answer. */\n private async exchange(\n body: { kind?: \"call\" | \"grade\" | \"close\"; tool?: string; args?: unknown },\n timeoutMs = CALL_TIMEOUT_MS,\n ): Promise<unknown> {\n const { callId } = await apiRequest<{ callId: string; seq: number }>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,\n body,\n );\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const call = await apiRequest<{\n done: boolean;\n state: string;\n result: unknown;\n error: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls/${encodeURIComponent(callId)}`,\n );\n if (call.done) {\n if (call.error) throw new WorldSessionCallError(call.error);\n return call.result;\n }\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n `Call ${callId} still ${call.state} after ${Math.round(timeoutMs / 1000)}s — the container may have died.`,\n );\n await sleep(CALL_POLL_MS);\n }\n }\n\n /**\n * Run one of the world's tools INSIDE the container. The arguments and the\n * result are the world's own contract — this layer neither validates nor\n * reshapes them, so a tool error reads exactly as it would in a hosted run.\n */\n async call(\n tool: string,\n args: Record<string, unknown> = {},\n opts: { timeoutMs?: number } = {},\n ): Promise<unknown> {\n return this.exchange({ kind: \"call\", tool, args }, opts.timeoutMs);\n }\n\n /**\n * THE WORLD'S TOOLS, READY TO HAND TO A MODEL. Schemas come from the\n * world's own signatures and implementations call into this session, so a\n * caller never writes — and never has to re-sync — a tool map of their own:\n *\n * const { schemas, impls } = await session.toolkit();\n * await runMyAgent(impls, schemas, session.instruction);\n *\n * A tool added to the world shows up here on the next run; a tool renamed\n * in the world renames here too, instead of failing at call time against a\n * hand-written map that still remembers the old name.\n */\n async toolkit(): Promise<WorldToolkit> {\n let specs = this.state.tools;\n if (!specs) specs = (await this.status()).tools ?? [];\n const impls: WorldToolkit[\"impls\"] = {};\n for (const spec of specs) {\n impls[spec.name] = (args: Record<string, unknown> = {}) =>\n this.call(spec.name, args);\n }\n return { schemas: specs.map(schemaFromSignature), impls, specs };\n }\n\n /** Run the task's grader against the container's END STATE. */\n async grade(opts: { timeoutMs?: number } = {}): Promise<GradeResult> {\n const raw = (await this.exchange(\n { kind: \"grade\" },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n const record = raw && typeof raw === \"object\" ? raw : {};\n const rewards: Record<string, number> = {};\n for (const [key, value] of Object.entries(record)) {\n if (key !== \"reward\" && typeof value === \"number\") rewards[key] = value;\n }\n return {\n reward: typeof record.reward === \"number\" ? record.reward : null,\n rewards,\n raw,\n };\n }\n\n /**\n * End the session. `keepWarm` hands the container back to the pool instead\n * of tearing it down, so the next session for the same task starts warm —\n * the pooled instance still obeys the fleet's idle TTL and pinning.\n */\n async close(opts: { keepWarm?: boolean } = {}): Promise<{ state: string }> {\n return apiRequest(\n this.options,\n \"DELETE\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n { keepWarm: opts.keepWarm ?? false },\n );\n }\n}\n\n/**\n * Attach to a session that already exists — resuming after a crash, or\n * driving a session someone else opened (a container started by hand on a\n * self-hosted install, a session opened by CI and handed to a developer).\n */\nexport async function attachSession(\n sessionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSession> {\n const state = await apiRequest<WorldSessionState>(\n options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(sessionId)}`,\n );\n return new WorldSession(sessionId, state, options);\n}\n\n/**\n * Open a live session against one task of a world. Returns as soon as the\n * platform has accepted it — call `ready()` to wait for the container.\n */\nexport async function openSession(\n slugOrRef: string,\n task: string,\n opts: {\n versionId?: string;\n reuseWarm?: boolean;\n options?: WorldsClientOptions;\n } = {},\n): Promise<WorldSession> {\n const options = opts.options ?? {};\n const at = slugOrRef.indexOf(\"@\");\n const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);\n const state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId ? { versionId: opts.versionId } : { slug }),\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n },\n );\n return new WorldSession(state.sessionId, state, options);\n}\n\n// ── running many tasks at once ───────────────────────────────────────────────\n\nexport type SessionRunResult = {\n task: string;\n sessionId: string;\n reward: number | null;\n rewards: Record<string, number>;\n /** Set when the task threw instead of grading. */\n error?: string;\n};\n\nexport type SessionRunReport = {\n results: SessionRunResult[];\n /** Mean reward over every task, counting failures as 0. */\n mean: number;\n /** True when `mean >= failUnder` (or no gate was set). */\n passed: boolean;\n};\n\n/**\n * RUN MANY TASKS IN PARALLEL, one warm container each.\n *\n * Parallelism against live worlds is the normal case — a suite is a dozen\n * tasks and each needs its own container, because two agents sharing one\n * world state would corrupt both episodes. Every caller was writing the same\n * pool, the same per-task open/ready/toolkit/grade/close, and the same\n * \"don't let one failure kill the run\" logic, so it belongs here:\n *\n * const report = await runSessions({\n * world: \"revenue-ops-sim@main\",\n * tasks, // default: every task in the world\n * concurrency: 4,\n * failUnder: 0.7,\n * agent: async ({ toolkit, instruction }) =>\n * myAgent(toolkit.impls, toolkit.schemas, instruction),\n * });\n *\n * The handler gets a ready session with its toolkit already bound; grading,\n * closing (warm) and aggregation are handled. A task that throws scores 0\n * and records why — the tasks that passed keep their results.\n */\nexport async function runSessions(opts: {\n world: string;\n tasks?: string[];\n concurrency?: number;\n failUnder?: number;\n /** Pin every session to one version (default: the world's head). */\n versionId?: string;\n /** Hand the containers back warm for the next run (default: true). */\n keepWarm?: boolean;\n agent: (ctx: {\n session: WorldSession;\n toolkit: WorldToolkit;\n instruction: string;\n task: string;\n }) => Promise<unknown>;\n onResult?: (result: SessionRunResult) => void;\n options?: WorldsClientOptions;\n}): Promise<SessionRunReport> {\n const options = opts.options ?? {};\n const concurrency = Math.max(1, opts.concurrency ?? 3);\n\n let tasks = opts.tasks;\n let versionId = opts.versionId;\n if (!tasks || !versionId) {\n // One resolve for the whole run: every session pins the SAME version, so\n // a push mid-suite cannot split the results across two worlds.\n const { openWorld } = await import(\"./index\");\n const world = await openWorld(opts.world, options);\n tasks = tasks ?? world.tasks.map((t) => t.name);\n versionId = versionId ?? world.version.versionId;\n }\n\n const results: SessionRunResult[] = [];\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {\n while (next < tasks!.length) {\n const task = tasks![next++];\n let session: WorldSession | null = null;\n try {\n session = await openSession(opts.world, task, {\n versionId,\n options,\n });\n await session.ready();\n const toolkit = await session.toolkit();\n await opts.agent({\n session,\n toolkit,\n instruction: session.instruction ?? task,\n task,\n });\n const graded = await session.grade();\n const result: SessionRunResult = {\n task,\n sessionId: session.sessionId,\n reward: graded.reward,\n rewards: graded.rewards,\n };\n results.push(result);\n opts.onResult?.(result);\n } catch (error) {\n const result: SessionRunResult = {\n task,\n sessionId: session?.sessionId ?? \"\",\n reward: 0,\n rewards: {},\n // An Error with an empty message would read as \"no error\" to any\n // caller checking truthiness; name the type instead.\n error:\n (error instanceof Error ? error.message : String(error)) ||\n (error instanceof Error ? error.name : \"Unknown error\"),\n };\n results.push(result);\n opts.onResult?.(result);\n } finally {\n // Always give the container back — a leaked session bills until the\n // fleet's idle TTL reaps it.\n await session\n ?.close({ keepWarm: opts.keepWarm ?? true })\n .catch(() => undefined);\n }\n }\n }),\n );\n\n const mean =\n results.reduce((sum, r) => sum + (r.reward ?? 0), 0) /\n (results.length || 1);\n return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n passed: opts.failUnder === undefined ? true : mean >= opts.failUnder,\n };\n}\n","import { createHash } from \"node:crypto\";\nimport { gzipSync, gunzipSync } from \"node:zlib\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The working-dir half of the TS CLI: push / pull / checkout / status /\n * branch / tag / propose — a faithful port of the Python client\n * (`gatewaysdk/benchmark_hub/client.py` + `_archive.py`).\n *\n * LOCKSTEP WARNING — the content hash is the version's identity and is\n * byte-compatible with Prime Intellect. It now has FOUR implementations that\n * must stay identical: worker `environmentAgent/tar.ts`, web\n * `benchmark-hub/server/benchmarkContentHash.ts`, Python `_archive.py`, and\n * this file. This one is a line-for-line port of the WEB TypeScript\n * implementation (same language, same crypto) — if the rule ever changes,\n * change all four or push identity splits by client.\n *\n * One deliberate refusal, same policy as the web upload path: a bundle with\n * a ROOT `.gitignore` is refused rather than mis-hashed — the Python CLI\n * honors it via `gitignore_parser`, and an imperfect reimplementation here\n * would produce a wrong, Prime-incompatible hash silently.\n */\n\nexport const DEFAULT_BRANCH = \"main\";\nconst META_RELPATH = path.join(\".gateway\", \".env-metadata.json\");\nconst SKIP_DIRS = new Set([\n \".git\",\n \"__pycache__\",\n \"node_modules\",\n \".venv\",\n \".mypy_cache\",\n \"dist\",\n \"build\",\n \"outputs\",\n]);\nconst ROOT_EXCLUDED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\"]);\n\n/** Gateway-only root markers that widen collection to every ordinary root\n * file. The FOURTH copy of this list (python SDK `_archive.py`, web\n * `benchmarkContentHash.ts`, worker `tar.ts`, and here) — all four MUST stay\n * identical or the same tree hashes differently per pusher. This copy\n * missing `gateway-api-world.toml` is exactly how an api world pushed from\n * TS landed on the hub with no OpenAPI contract and no marker: the root\n * files never entered the manifest, and nothing downstream could tell. */\nconst BROAD_ROOT_MARKERS = [\"gateway-env.toml\", \"gateway-api-world.toml\"];\n\n// ── content-hash rules (port of web benchmarkContentHash.ts) ───────────────\n\nfunction isExcludedDirComponent(component: string): boolean {\n return (\n component.startsWith(\".\") ||\n ROOT_EXCLUDED_DIRS.has(component) ||\n component.endsWith(\".egg-info\")\n );\n}\n\nexport function isIncludedInContentHash(\n relPath: string,\n includeAllRootFiles: boolean,\n): boolean {\n const parts = relPath.split(\"/\");\n const name = parts[parts.length - 1];\n const dirParts = parts.slice(0, -1);\n if (name.startsWith(\".\")) return false;\n if (parts.includes(\"__pycache__\")) return false;\n if (dirParts.length === 0) {\n return (\n includeAllRootFiles ||\n name === \"README.md\" ||\n name === \"pyproject.toml\" ||\n BROAD_ROOT_MARKERS.includes(name) ||\n name.endsWith(\".py\")\n );\n }\n return !dirParts.some(isExcludedDirComponent);\n}\n\n/** The archive-visible files of a working dir, as sorted relpaths. Throws on\n * a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n if (fs.existsSync(path.join(dir, \".gitignore\"))) {\n throw new Error(\n \"This bundle has a root .gitignore, which the Python CLI honors via \" +\n \"gitignore_parser. Reimplementing that imperfectly here would \" +\n \"silently produce a different content hash, so the TS CLI refuses. \" +\n \"Remove the .gitignore (or bake its effect into the tree) and retry.\",\n );\n }\n const out: string[] = [];\n const includeAllRootFiles = BROAD_ROOT_MARKERS.some((marker) =>\n fs.existsSync(path.join(dir, marker)),\n );\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!isExcludedDirComponent(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (isIncludedInContentHash(childRel, includeAllRootFiles)) {\n out.push(childRel);\n }\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nexport function computeContentHash(dir: string): string {\n const hasher = createHash(\"sha256\");\n for (const relPath of collectArchiveRelPaths(dir)) {\n hasher.update(Buffer.from(`file:${relPath}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(dir, relPath)));\n }\n return hasher.digest(\"hex\");\n}\n\n// ── deterministic tar.gz writer ─────────────────────────────────────────────\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(value.toString(8).padStart(length - 1, \"0\") + \"\\0\", \"ascii\");\n}\n\nfunction tarHeader(name: string, size: number): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(0o644, 8).copy(header, 100); // mode\n octal(0, 8).copy(header, 108); // uid\n octal(0, 8).copy(header, 116); // gid\n octal(size, 12).copy(header, 124);\n octal(0, 12).copy(header, 136); // mtime = 0 (deterministic)\n header.write(\" \", 148, \"ascii\"); // checksum placeholder = spaces\n header.write(\"0\", 156, \"ascii\"); // regular file\n header.write(\"ustar\", 257, \"ascii\");\n header.write(\"00\", 263, \"ascii\");\n let sum = 0;\n for (const byte of header) sum += byte;\n header.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n return header;\n}\n\nfunction tarMember(name: string, payload: Buffer): Buffer[] {\n const parts: Buffer[] = [];\n const nameBytes = Buffer.byteLength(name, \"utf-8\");\n if (nameBytes > 100) {\n // GNU long name: an 'L' member whose body is the real name.\n const body = Buffer.from(name + \"\\0\", \"utf-8\");\n const lHeader = tarHeader(\"././@LongLink\", body.length);\n lHeader.write(\"L\", 156, \"ascii\");\n let sum = 0;\n lHeader.write(\" \", 148, \"ascii\");\n for (const byte of lHeader) sum += byte;\n lHeader.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n parts.push(lHeader, body);\n const pad = body.length % 512 === 0 ? 0 : 512 - (body.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n parts.push(tarHeader(name.slice(0, 100), payload.length));\n } else {\n parts.push(tarHeader(name, payload.length));\n }\n parts.push(payload);\n const pad = payload.length % 512 === 0 ? 0 : 512 - (payload.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n return parts;\n}\n\n/** A deterministic .tar.gz of the source files (node's gzip stamps no mtime,\n * matching the Python's mtime=0 gzip). */\nexport function buildSourceTarball(dir: string): Buffer {\n const parts: Buffer[] = [];\n for (const relPath of collectArchiveRelPaths(dir)) {\n parts.push(...tarMember(relPath, fs.readFileSync(path.join(dir, relPath))));\n }\n parts.push(Buffer.alloc(1024)); // end-of-archive\n return gzipSync(Buffer.concat(parts), { level: 9 });\n}\n\n// ── local metadata (.gateway/.env-metadata.json) ────────────────────────────\n\nexport type LocalMeta = Record<string, unknown> & {\n slug?: string;\n branch?: string;\n versionId?: string;\n contentHash?: string;\n baseFiles?: Record<string, string>;\n};\n\nexport function readLocalMeta(dir: string): LocalMeta | null {\n try {\n const raw = fs.readFileSync(path.join(dir, META_RELPATH), \"utf-8\");\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" ? (parsed as LocalMeta) : null;\n } catch {\n return null;\n }\n}\n\nexport function writeLocalMeta(dir: string, meta: LocalMeta): void {\n fs.mkdirSync(path.join(dir, \".gateway\"), { recursive: true });\n fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));\n}\n\nexport function snapshotTreeHashes(dir: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const relPath of collectArchiveRelPaths(dir)) {\n out[relPath] = createHash(\"sha256\")\n .update(fs.readFileSync(path.join(dir, relPath)))\n .digest(\"hex\");\n }\n return out;\n}\n\nexport function localTreeState(dir: string): {\n meta: LocalMeta | null;\n dirty: string[];\n clean: boolean;\n} {\n const meta = readLocalMeta(dir);\n const base = meta?.baseFiles;\n if (!base || typeof base !== \"object\") {\n return { meta, dirty: [], clean: false };\n }\n const now = snapshotTreeHashes(dir);\n const dirty = new Set<string>();\n for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);\n for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);\n return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };\n}\n\n// ── protocol helpers ─────────────────────────────────────────────────────────\n\nconst sha256b64 = (data: Buffer) =>\n createHash(\"sha256\").update(data).digest(\"base64\");\n\nfunction readPyproject(dir: string): { name?: string; version?: string } {\n try {\n const text = fs.readFileSync(path.join(dir, \"pyproject.toml\"), \"utf-8\");\n // Minimal [project] reads — name and version only, quoted single-line form.\n const section = /\\[project\\]([\\s\\S]*?)(\\n\\[|$)/.exec(text)?.[1] ?? \"\";\n const name = /\\bname\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n const version = /\\bversion\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n return { name, version };\n } catch {\n return {};\n }\n}\n\nfunction buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n const entries: { path: string; isDirectory: boolean; size: number; sha256: string }[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(\".egg-info\")) {\n walk(childRel);\n }\n } else if (entry.isFile()) {\n const payload = fs.readFileSync(path.join(dir, childRel));\n entries.push({\n path: childRel,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n });\n }\n }\n };\n walk(\"\");\n return entries;\n}\n\nasync function putObject(url: string, data: Buffer, shaB64: string): Promise<void> {\n const resp = await fetch(url, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/gzip\",\n \"x-amz-checksum-sha256\": shaB64,\n },\n body: new Uint8Array(data),\n });\n if (!resp.ok) {\n throw new Error(`object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`);\n }\n}\n\n// ── the workflows ────────────────────────────────────────────────────────────\n\nexport async function push(\n dir: string,\n opts: {\n slug?: string;\n branch?: string;\n force?: boolean;\n message?: string;\n author?: string;\n /** Push on top of this version instead of the local meta's base — what a\n * CI checkout (which has no local meta) passes after resolving the\n * branch tip, so re-validating a PR replaces its own previous push\n * instead of 409ing against it. */\n baseVersionId?: string | null;\n options?: WorldsClientOptions;\n } = {},\n): Promise<{ slug: string; versionId: string; contentHash: string; branch: string }> {\n const options = opts.options ?? {};\n if (!fs.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch = opts.branch ?? (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;\n\n const contentHash = computeContentHash(dir);\n const pyproject = readPyproject(dir);\n const slug = opts.slug ?? pyproject.name ?? path.basename(path.resolve(dir));\n\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n { slug, name: pyproject.name ?? slug },\n );\n\n const tarball = buildSourceTarball(dir);\n const bundleSha256 = sha256b64(tarball);\n\n const version = await apiRequest<{\n versionId: string;\n uploadUrl?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/versions\", {\n containerId: resolve.containerId,\n contentHash,\n bundleSha256,\n bundleSizeBytes: tarball.length,\n ...(pyproject.version ? { semanticVersion: pyproject.version } : {}),\n pyprojectMeta: pyproject,\n fileManifest: buildFileManifest(dir),\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...(opts.message ? { changeReason: opts.message } : {}),\n ...(opts.author ? { author: opts.author } : {}),\n });\n\n if (version.uploadUrl) await putObject(version.uploadUrl, tarball, bundleSha256);\n\n await apiRequest(\n options,\n \"POST\",\n `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,\n { branch, baseVersionId, ...(opts.force ? { force: true } : {}) },\n );\n\n writeLocalMeta(dir, {\n ...localMeta,\n slug,\n ref: branch,\n branch,\n versionId: version.versionId,\n contentHash,\n semanticVersion: pyproject.version,\n forkedFromVersionId: baseVersionId,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, versionId: version.versionId, contentHash, branch };\n}\n\n/** Extract a downloaded bundle into `dir` (paths sanitized). */\nfunction extractBundle(bundle: Buffer, dir: string): number {\n const tar = gunzipSync(bundle);\n let offset = 0;\n let longName: string | null = null;\n let written = 0;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n offset += 512;\n if (header.every((b) => b === 0)) break;\n const rawName = header.subarray(0, 100).toString(\"utf-8\").replace(/\\0.*$/, \"\");\n const size = parseInt(header.subarray(124, 136).toString(\"ascii\").replace(/\\0.*$/, \"\").trim(), 8) || 0;\n const typeflag = header.subarray(156, 157).toString(\"ascii\");\n const body = tar.subarray(offset, offset + size);\n offset += size + (size % 512 === 0 ? 0 : 512 - (size % 512));\n if (typeflag === \"L\") {\n longName = body.toString(\"utf-8\").replace(/\\0.*$/, \"\");\n continue;\n }\n const name = (longName ?? rawName).replace(/^\\.\\//, \"\");\n longName = null;\n if (typeflag !== \"0\" && typeflag !== \"\") continue;\n // Safe extract: no absolute paths, no traversal.\n if (name.startsWith(\"/\") || name.split(\"/\").includes(\"..\")) continue;\n const target = path.join(dir, name);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, body);\n written++;\n }\n return written;\n}\n\nexport async function pull(\n slugRef: string,\n target?: string,\n options: WorldsClientOptions = {},\n): Promise<{ slug: string; dir: string; versionId: string; files: number }> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? \"latest\" : slugRef.slice(at + 1);\n\n const details = await apiRequest<{\n versionId: string;\n contentHash: string;\n semanticVersion?: string | null;\n downloadUrl?: string;\n bundleSha256?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ref,\n });\n if (!details.downloadUrl) {\n throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);\n }\n\n let dir = target ?? path.join(process.cwd(), slug);\n if (!target) {\n let i = 1;\n const base = dir;\n while (fs.existsSync(dir)) dir = `${base}-${i++}`;\n }\n fs.mkdirSync(dir, { recursive: true });\n\n const resp = await fetch(details.downloadUrl);\n if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);\n const bundle = Buffer.from(await resp.arrayBuffer());\n if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {\n throw new Error(\n `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`,\n );\n }\n\n const files = extractBundle(bundle, dir);\n const branch = ref === \"latest\" || /^\\d|^[0-9a-f]{8,}$/.test(ref) ? DEFAULT_BRANCH : ref;\n writeLocalMeta(dir, {\n slug,\n ref,\n branch,\n versionId: details.versionId,\n contentHash: details.contentHash,\n semanticVersion: details.semanticVersion ?? undefined,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, dir, versionId: details.versionId, files };\n}\n\nexport async function propose(\n dir: string,\n opts: { title: string; reason: string; targetBranch?: string; options?: WorldsClientOptions },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\"This dir has no pull/push base — run pull first, then edit, then propose.\");\n }\n const state = localTreeState(dir);\n if (state.clean) throw new Error(\"Nothing to propose — the tree matches its base.\");\n const changes = state.dirty.map((relPath) => {\n const abs = path.join(dir, relPath);\n if (!fs.existsSync(abs)) return { path: relPath, action: \"delete\" as const };\n return {\n path: relPath,\n action: \"write\" as const,\n newContent: fs.readFileSync(abs, \"utf-8\"),\n };\n });\n const res = await apiRequest<{ proposalId: string }>(\n opts.options ?? {},\n \"POST\",\n \"/api/public/benchmark-containers/proposals\",\n {\n slug: meta.slug,\n title: opts.title,\n changeReason: opts.reason,\n baseVersionId: meta.versionId,\n ...(opts.targetBranch ? { targetBranch: opts.targetBranch } : {}),\n changes,\n },\n );\n return res;\n}\n\nexport async function createRef(\n slug: string,\n name: string,\n kind: \"branch\" | \"tag\",\n versionId?: string,\n options: WorldsClientOptions = {},\n): Promise<{ name: string; kind: string; versionId: string }> {\n return apiRequest(options, \"POST\", \"/api/public/benchmark-containers/refs\", {\n slug,\n name,\n kind,\n ...(versionId ? { versionId } : {}),\n });\n}\n","/**\n * PR validation: push the checkout's world source, run it, gate on the graded\n * result — one composed call, because CI should not have to re-derive the\n * choreography from primitives.\n *\n * The differentiating property, stated so it stays true: validation runs the\n * PULL REQUEST'S OWN world source. The push files the checkout as a version on\n * the PR's branch (content-hash dedup makes re-runs cheap), the dispatch pins\n * that version, and the platform resolves the branch back to its open PR — so\n * the run page names the PR and the PR comment names the run. Nothing here\n * validates a standing deployment while pretending to validate the change.\n */\n\nimport {\n apiRequest,\n detectProvenance,\n listRunConfigs,\n waitForRun,\n type RunReport,\n type WorldsClientOptions,\n} from \"./index\";\nimport { push } from \"./hub\";\n\nexport type ValidatedRun = {\n model: string;\n runId: string;\n report: RunReport | null;\n /** Why this run fails the gate, or null when it passes. */\n failure: string | null;\n};\n\nexport type ValidateReport = {\n ok: boolean;\n slug: string;\n branch: string;\n versionId: string;\n contentHash: string;\n runConfig: { id: string; name: string };\n runs: ValidatedRun[];\n /** A PR-comment-ready summary of the whole validation. */\n markdown: string;\n};\n\nfunction fmtScore(score: number | null): string {\n return score === null ? \"no score\" : score.toFixed(3);\n}\n\nfunction buildMarkdown(\n report: Omit<ValidateReport, \"markdown\">,\n minScore: number | null,\n source?: { repoUrl?: string; commit?: string },\n): string {\n const lines: string[] = [];\n lines.push(\n `### World validation ${report.ok ? \"passed\" : \"failed\"} — \\`${report.slug}@${report.branch}\\``,\n );\n lines.push(\"\");\n // Name the exact source that ran: the commit on GitHub when we know it,\n // always the content hash the platform pinned.\n const commitLink =\n source?.repoUrl && source?.commit\n ? `[\\`${source.commit.slice(0, 12)}\\`](${source.repoUrl}/commit/${source.commit})`\n : null;\n lines.push(\n `Ran the pull request's own world source` +\n (commitLink ? ` (${commitLink} on \\`${report.branch}\\`` : ` (`) +\n `${commitLink ? \", \" : \"\"}pinned as \\`${report.contentHash.slice(0, 12)}\\`) ` +\n `through run config **${report.runConfig.name}**` +\n (minScore !== null ? `, gating at score ≥ ${minScore}.` : \".\"),\n );\n lines.push(\"\");\n lines.push(\"| Model | Status | Score | Run |\");\n lines.push(\"| --- | --- | ---: | --- |\");\n for (const run of report.runs) {\n const r = run.report;\n const link = r?.url ? `[open](${r.url})` : \"—\";\n const status = run.failure\n ? `❌ ${run.failure}`\n : `✅ ${r?.status ?? \"COMPLETED\"}`;\n lines.push(\n `| \\`${run.model}\\` | ${status} | ${fmtScore(r?.score ?? null)} | ${link} |`,\n );\n }\n const taskRows = report.runs.flatMap((run) =>\n (run.report?.samples ?? []).map((sample) => ({\n model: run.model,\n task: sample.task ?? \"?\",\n reward: sample.reward,\n })),\n );\n // Every scenario, in the open: a validation whose per-scenario grades hide\n // behind a fold reads as one opaque number. Fold only when the table is\n // genuinely long.\n if (taskRows.length > 0) {\n const fold = taskRows.length > 12;\n lines.push(\"\");\n if (fold) {\n lines.push(\n `<details><summary>Per-scenario rewards (${taskRows.length})</summary>`,\n );\n lines.push(\"\");\n } else {\n lines.push(`**Scenarios (${taskRows.length})**`);\n lines.push(\"\");\n }\n lines.push(\"| Scenario | Model | Reward |\");\n lines.push(\"| --- | --- | ---: |\");\n for (const row of taskRows) {\n lines.push(\n `| ${row.task} | \\`${row.model}\\` | ${row.reward === null ? \"no score\" : row.reward.toFixed(2)} |`,\n );\n }\n if (fold) {\n lines.push(\"\");\n lines.push(\"</details>\");\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Push `dir` on the current (or given) branch, dispatch the named run config\n * against the pushed version, wait for every run, and gate.\n *\n * The gate: every dispatch accepted, every run terminal COMPLETED, and — when\n * `minScore` is set — every run's score meets it. A run with NO score fails a\n * score gate rather than passing it: null is \"not scored\", never 0 and never\n * fine.\n */\nexport async function validateWorld(\n dir: string,\n opts: {\n slug?: string;\n runConfig: string;\n branch?: string;\n minScore?: number | null;\n timeoutMinutes?: number;\n onProgress?: (line: string) => void;\n options?: WorldsClientOptions;\n },\n): Promise<ValidateReport> {\n const options = opts.options ?? {};\n const progress = opts.onProgress ?? (() => {});\n const minScore = opts.minScore ?? null;\n\n const provenance = detectProvenance();\n const branch = opts.branch ?? provenance.branch;\n if (!branch)\n throw new Error(\n \"No branch to validate on: pass --branch or run inside a git checkout / GitHub Actions.\",\n );\n\n progress(`pushing ${dir} as ${opts.slug ?? \"(pyproject name)\"}@${branch}…`);\n // CI checkouts carry no local push meta, so a re-validation would 409\n // against the branch tip its own previous run created. Validation's\n // semantics are \"this branch's tip BECOMES the PR's source\": resolve the\n // current tip and push on top of it. A branch that does not exist yet\n // resolves to no base, which is a fresh branch — also correct.\n let tipVersionId: string | null = null;\n if (opts.slug) {\n try {\n const tip = await apiRequest<{ versionId?: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve-version\",\n { slug: opts.slug, ref: branch },\n );\n tipVersionId = tip.versionId ?? null;\n } catch {\n tipVersionId = null;\n }\n }\n const pushed = await push(dir, {\n slug: opts.slug,\n branch,\n baseVersionId: tipVersionId,\n message: `PR validation push (${provenance.commit?.slice(0, 12) ?? \"local\"})`,\n ...(provenance.actor?.name ? { author: provenance.actor.name } : {}),\n options,\n });\n progress(`pushed version ${pushed.versionId} (${pushed.contentHash.slice(0, 12)})`);\n\n // Resolve the run config by name (the stable handle CI configures) or id.\n const configs = await listRunConfigs(options);\n const runConfig =\n configs.find((c) => c.id === opts.runConfig) ??\n configs.find((c) => c.name === opts.runConfig);\n if (!runConfig) {\n const known = configs.map((c) => c.name).join(\", \") || \"(none)\";\n throw new Error(\n `Run config \"${opts.runConfig}\" not found in this project. Have: ${known}`,\n );\n }\n\n progress(`dispatching run config \"${runConfig.name}\" (${runConfig.models.join(\", \")})…`);\n const dispatched = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(options, \"POST\", \"/api/public/benchmark-containers/run-configs/dispatch\", {\n runConfigId: runConfig.id,\n versionId: pushed.versionId,\n ...provenance,\n });\n\n // The run's platform page. New deployments return it on the run report\n // (`url`); against an older deployment we build the same page from the\n // evaluation id, because a PR comment that cannot link the run defeats\n // the point of the comment.\n const host = (\n options.host ??\n process.env.GATEWAY_HOST ??\n \"https://withgateway.ai\"\n ).replace(/\\/+$/, \"\");\n let projectId: string | null = null;\n try {\n const projects = await apiRequest<{ data?: { id?: string }[] }>(\n options,\n \"GET\",\n \"/api/public/projects\",\n );\n projectId = projects.data?.[0]?.id ?? null;\n } catch {\n projectId = null;\n }\n const fallbackUrl = (report: RunReport): string | null => {\n if (report.url) return report.url;\n const evaluationId = report.evaluations[0]?.id;\n return projectId && evaluationId\n ? `${host}/project/${projectId}/environment/runs/${encodeURIComponent(evaluationId)}`\n : null;\n };\n\n const runs: ValidatedRun[] = [];\n for (const run of dispatched.runs) {\n if (!run.ok) {\n runs.push({\n model: run.model,\n runId: run.runId,\n report: null,\n failure: `dispatch failed: ${run.error ?? \"unknown error\"}`,\n });\n continue;\n }\n progress(`waiting on ${run.model} (run ${run.runId})…`);\n let report: RunReport | null = null;\n let failure: string | null = null;\n try {\n report = await waitForRun(run.runId, {\n timeoutMinutes: opts.timeoutMinutes ?? 45,\n options,\n onTick: (r) =>\n progress(\n `…${run.model}: ${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n });\n report = { ...report, url: fallbackUrl(report) };\n if (report.status.toUpperCase() !== \"COMPLETED\") {\n failure = report.status;\n } else if (minScore !== null) {\n if (report.score === null) failure = \"completed without a score\";\n else if (report.score < minScore)\n failure = `score ${fmtScore(report.score)} < ${minScore}`;\n }\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n runs.push({ model: run.model, runId: run.runId, report, failure });\n }\n\n const base = {\n ok: runs.length > 0 && runs.every((r) => r.failure === null),\n slug: pushed.slug,\n branch,\n versionId: pushed.versionId,\n contentHash: pushed.contentHash,\n runConfig: { id: runConfig.id, name: runConfig.name },\n runs,\n };\n return {\n ...base,\n markdown: buildMarkdown(base, minScore, {\n repoUrl: provenance.repoUrl,\n commit: provenance.commit,\n }),\n };\n}\n","/**\n * Worlds from TypeScript: identity, tasks, and HOSTED execution.\n *\n * The same three-level model as the Python SDK — WorldSet → Task — with one\n * deliberate difference: a world's tools are Python modules, so TypeScript\n * does not materialize task environments in-process. What a TS agent\n * codebase needs is exactly what this module provides: resolve a world ref\n * to its pinned version, read its task list, and dispatch HOSTED runs\n * (parallelism included) that execute the world server-side and file graded,\n * version-pinned rollouts. Local in-process execution stays a Python\n * capability by design, not by omission.\n */\n\nexport type WorldsClientOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n};\n\nexport type ResolvedWorldVersion = {\n versionId: string;\n semanticVersion: string | null;\n contentHash: string;\n state?: string;\n};\n\nexport type WorldTaskInfo = {\n name: string;\n variant: string | null;\n};\n\nexport type DispatchedRun = {\n model: string;\n runId: string;\n ok: boolean;\n error?: string;\n};\n\nfunction resolveEnv(options: WorldsClientOptions) {\n const host =\n options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\";\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n if (!publicKey || !secretKey) {\n throw new Error(\n \"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY \" +\n \"(or pass publicKey/secretKey).\",\n );\n }\n return { host: host.replace(/\\/+$/, \"\"), publicKey, secretKey };\n}\n\n/** Authenticated JSON request against the platform API — the primitive the\n * worlds helpers and the TS CLI share. */\nexport async function apiRequest<T>(\n options: WorldsClientOptions,\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\",\n path: string,\n body?: unknown,\n): Promise<T> {\n const { host, publicKey, secretKey } = resolveEnv(options);\n const res = await fetch(`${host}${path}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${publicKey}:${secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n const text = await res.text();\n if (!res.ok) {\n throw new Error(\n `${method} ${path} -> ${res.status}: ${text.slice(0, 400)}`,\n );\n }\n return JSON.parse(text) as T;\n}\n\n/** Set (or rotate) one environment secret — write-only: no API returns it. */\nexport async function setEnvSecret(\n slug: string,\n key: string,\n value: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; created: boolean }> {\n return apiRequest(\n options,\n \"PUT\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n value,\n },\n );\n}\n\n/** Keys and rotation timestamps only — never values. */\nexport async function listEnvSecretKeys(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; updatedAt: string }[]> {\n const res = await apiRequest<{\n secrets: { key: string; updatedAt: string }[];\n }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/secrets?slug=${encodeURIComponent(slug)}`,\n );\n return res.secrets;\n}\n\nexport async function deleteEnvSecret(\n slug: string,\n key: string,\n options: WorldsClientOptions = {},\n): Promise<void> {\n await apiRequest(\n options,\n \"DELETE\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n },\n );\n}\n\nexport type RunConfigSummary = {\n id: string;\n name: string;\n runType: string;\n createdAt: string;\n models: string[];\n parallelism: number;\n autoRunOnPush: boolean;\n agent: string | null;\n};\n\n/** Run configs in the project. CI resolves by NAME and dispatches by id. */\nexport async function listRunConfigs(\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary[]> {\n const res = await apiRequest<{ runConfigs: RunConfigSummary[] }>(\n options,\n \"GET\",\n \"/api/public/benchmark-containers/run-configs\",\n );\n return res.runConfigs;\n}\n\nexport type RunReport = {\n id: string;\n status: string;\n terminal: boolean;\n score: number | null;\n summary: string | null;\n model: string | null;\n versionLabel: string | null;\n parallelism: number;\n shardsCompleted: number | null;\n /** The run's page on the platform — what a PR comment should link. */\n url: string | null;\n evaluations: {\n id: string;\n status: string;\n avgReward: number | null;\n url: string | null;\n }[];\n samples: {\n task: string | null;\n reward: number | null;\n rewards: Record<string, unknown>;\n sessionId: string | null;\n }[];\n};\n\n/** The read half of dispatch: status, score, per-shard evaluations, and\n * per-task rewards — everything a CI gate needs. */\nexport async function getRun(\n runId: string,\n options: WorldsClientOptions = {},\n): Promise<RunReport> {\n return apiRequest(\n options,\n \"GET\",\n `/api/public/benchmark-containers/runs/${encodeURIComponent(runId)}`,\n );\n}\n\n/** Poll a run to terminal (default every 20s, up to `timeoutMinutes`). */\nexport async function waitForRun(\n runId: string,\n opts: {\n timeoutMinutes?: number;\n intervalSeconds?: number;\n onTick?: (run: RunReport) => void;\n options?: WorldsClientOptions;\n } = {},\n): Promise<RunReport> {\n const deadline = Date.now() + (opts.timeoutMinutes ?? 45) * 60_000;\n for (;;) {\n const run = await getRun(runId, opts.options ?? {});\n if (run.terminal) return run;\n if (Date.now() > deadline)\n throw new Error(\n `Run ${runId} still ${run.status} after the wait timeout.`,\n );\n opts.onTick?.(run);\n await new Promise((resolve) =>\n setTimeout(resolve, (opts.intervalSeconds ?? 20) * 1000),\n );\n }\n}\n\nexport type RunProvenance = {\n branch?: string;\n commit?: string;\n repoUrl?: string;\n actor?: { id?: string; name?: string; imageUrl?: string; kind?: string };\n};\n\n/**\n * Where a dispatch comes from, DETECTED rather than configured: the CI\n * checkout's branch/commit/actor under GitHub Actions, else the developer's\n * own git checkout. A run nobody can trace to a branch is a score with no\n * code attached, so every dispatch carries this unless overridden.\n */\nexport function detectProvenance(): RunProvenance {\n const env =\n (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env ?? {};\n const out: RunProvenance = {};\n const ref = env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME;\n if (ref) out.branch = ref;\n if (env.GITHUB_SHA) out.commit = env.GITHUB_SHA;\n const server = env.GITHUB_SERVER_URL ?? \"https://github.com\";\n if (env.GITHUB_REPOSITORY) out.repoUrl = `${server}/${env.GITHUB_REPOSITORY}`;\n if (env.GITHUB_ACTOR) {\n out.actor = {\n kind: \"ci\",\n id: env.GITHUB_ACTOR,\n name: env.GITHUB_ACTOR,\n // GitHub serves every account's avatar at /<login>.png.\n imageUrl: `${server}/${env.GITHUB_ACTOR}.png`,\n };\n }\n if (!out.branch || !out.commit) {\n try {\n const { execFileSync } =\n require(\"node:child_process\") as typeof import(\"node:child_process\");\n const git = (args: string[]) =>\n execFileSync(\"git\", args, {\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n out.branch = out.branch ?? git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n out.commit = out.commit ?? git([\"rev-parse\", \"HEAD\"]);\n if (!out.repoUrl) {\n const remote = git([\"config\", \"--get\", \"remote.origin.url\"]);\n if (remote) out.repoUrl = remote.replace(/\\.git$/, \"\");\n }\n if (!out.actor) {\n const name = git([\"config\", \"--get\", \"user.name\"]);\n if (name) out.actor = { kind: \"user\", name };\n }\n } catch {\n // No git here — dispatch without provenance rather than failing.\n }\n }\n return out;\n}\n\n/** One scenario of a world, as data. */\nexport class WorldTask {\n constructor(\n readonly world: WorldSet,\n readonly name: string,\n readonly variant: string | null,\n ) {}\n}\n\n/**\n * THE world, from a TS process: pinned identity + its tasks + hosted runs.\n *\n * const world = await openWorld(\"google-drive-sim@main\");\n * console.log(world.version.semanticVersion, world.tasks.length);\n * const runs = await world.dispatch(runConfigId);\n */\nexport class WorldSet {\n constructor(\n readonly slugRef: string,\n readonly slug: string,\n readonly ref: string | null,\n readonly version: ResolvedWorldVersion,\n public tasks: WorldTask[],\n private readonly options: WorldsClientOptions,\n ) {}\n\n task(variant: string): WorldTask {\n const hit = this.tasks.find(\n (t) => t.variant === variant || t.name.includes(variant),\n );\n if (!hit) {\n const known = this.tasks.map((t) => t.variant ?? t.name).join(\", \");\n throw new Error(`no task matches ${variant}; have: ${known}`);\n }\n return hit;\n }\n\n /**\n * Open a LIVE session against one of this world's tasks: the platform boots\n * (or reuses) a warm container, and your agent calls its tools through the\n * platform. See worlds/session.ts.\n */\n async open(\n task: string,\n opts: { reuseWarm?: boolean } = {},\n ): Promise<import(\"./session\").WorldSession> {\n const { openSession } = await import(\"./session\");\n return openSession(this.slug, task, {\n versionId: this.version.versionId,\n reuseWarm: opts.reuseWarm,\n options: this.options,\n });\n }\n\n /**\n * Start a HOSTED run of a run config against this world — the platform\n * executes the (Python) world in parallel containers per the config's\n * `parallelism` and files one graded run per model. Returns those runs.\n */\n async dispatch(\n runConfigId: string,\n opts: {\n containerId?: string;\n versionId?: string;\n /** Override the auto-detected branch/commit/actor. */\n provenance?: RunProvenance;\n } = {},\n ): Promise<{ versionLabel: string; runs: DispatchedRun[] }> {\n const provenance = opts.provenance ?? detectProvenance();\n return apiRequest(\n this.options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n {\n runConfigId,\n ...(opts.containerId ? { containerId: opts.containerId } : {}),\n versionId: opts.versionId ?? this.version.versionId,\n ...provenance,\n },\n );\n }\n}\n\n/**\n * Resolve `slug` / `slug@branch|tag|semver|hash` to its pinned version and\n * task list. The task list comes from the version's file manifest\n * (`tasks/<name>/task.toml`), so it needs no bundle download.\n */\nexport async function openWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? null : slugRef.slice(at + 1);\n\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...(ref ? { ref } : {}),\n });\n\n const world = new WorldSet(\n slugRef,\n slug,\n ref,\n {\n versionId: version.versionId,\n semanticVersion: version.semanticVersion ?? null,\n contentHash: version.contentHash,\n state: version.state,\n },\n [],\n options,\n );\n for (const name of version.taskNames ?? []) {\n const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;\n world.tasks.push(new WorldTask(world, name, variant));\n }\n return world;\n}\n\n// The session surface completes the worlds module, so `@withgateway/sdk/worlds`\n// carries both halves: running a world locally, and driving one the platform\n// hosts. (session.ts imports apiRequest from here; the cycle is function-level\n// only, and the build below is what proves it resolves.)\nexport * from \"./session\";\n\n// The hub half: push, pull, propose and the content-hash primitives the CLI\n// runs on. These were reachable only from inside the package, so a consumer\n// could drive a world but never publish one.\nexport * from \"./hub\";\n\n// PR validation: push-dispatch-wait-gate as one composed call, for CI.\nexport * from \"./validate\";\n","#!/usr/bin/env node\n/**\n * The TypeScript `gateway` CLI — full command parity with the Python CLI's\n * `bench` family, including the working-dir workflows (push/pull/checkout/\n * status/branch/tag/propose — see worlds/hub.ts and its LOCKSTEP WARNING on\n * the content hash). The one Python-only command is `eval`: it runs the\n * world locally on the Python engines, which a JS process cannot host —\n * hosted runs via `dispatch` are the equivalent.\n *\n * Auth: GATEWAY_HOST + GATEWAY_PUBLIC_KEY + GATEWAY_SECRET_KEY, same env as\n * the library.\n */\nimport * as fs from \"node:fs\";\n\nimport {\n apiRequest,\n deleteEnvSecret,\n getRun,\n listEnvSecretKeys,\n listRunConfigs,\n openWorld,\n setEnvSecret,\n waitForRun,\n} from \"./worlds/index\";\nimport {\n computeContentHash,\n createRef,\n localTreeState,\n propose,\n pull,\n push,\n} from \"./worlds/hub\";\nimport { validateWorld } from \"./worlds/validate\";\n\ntype Flags = Record<string, string | boolean>;\n\nfunction parseArgv(argv: string[]): { positional: string[]; flags: Flags } {\n const positional: string[] = [];\n const flags: Flags = {};\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (arg.startsWith(\"--\")) {\n const key = arg.slice(2);\n const next = argv[i + 1];\n if (next !== undefined && !next.startsWith(\"--\")) {\n flags[key] = next;\n i++;\n } else {\n flags[key] = true;\n }\n } else {\n positional.push(arg);\n }\n }\n return { positional, flags };\n}\n\nfunction str(flags: Flags, key: string): string | undefined {\n const value = flags[key];\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction fail(message: string): never {\n console.error(message);\n process.exit(2);\n}\n\nconst PYTHON_ONLY = new Set([\"eval\"]);\n\nconst HELP = `gateway bench <command> — worlds from TypeScript\n\n resolve <slug[@ref]> pinned version + task count\n tasks <slug[@ref]> the task list\n dispatch <runConfigId> [--container-id X] [--version-id Y]\n run <runId> [--wait] [--timeout-min N] status, score, per-task rewards\n run-configs list\n run-configs create --name N --models a,b [--parallelism K] [--tasks t1,t2] [--agent A] [--auto-run-on-push] [--id existing]\n run-configs delete --id X\n secrets set --env <slug> --key K [--value V] (omit --value to read stdin)\n secrets list --env <slug>\n secrets unset --env <slug> --key K\n refs <slug> branches and tags\n log <slug> [--branch B] [--limit N] version history\n proposals <slug> [--status open|applied|dismissed]\n\n pull <slug[@ref]> [--dir D] materialize a working dir\n push [dir] [--slug S] [--branch B] [--force] [--message M]\n validate [dir] --run-config NAME [--slug S] [--branch B] [--min-score X]\n [--summary-file F] [--timeout-min N]\n push this checkout, run it, gate — the PR-validation entry\n checkout <slug@ref> --dir D re-aim an existing working dir\n status [dir] clean/dirty vs base + hash check\n branch <slug> <name> [--version-id V] create a branch\n tag <slug> <name> [--version-id V] create a tag\n propose [dir] --title T --reason R [--target-branch B]\n\n eval (local engine runs) is Python-only — run hosted via 'dispatch'.\n\nAuth: GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY.`;\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf-8\").trim();\n}\n\nasync function main(): Promise<number> {\n const [group, command, ...rest] = process.argv.slice(2);\n if (!group || group === \"help\" || group === \"--help\") {\n console.log(HELP);\n return 0;\n }\n if (group !== \"bench\") {\n fail(\n `Unknown command group '${group}' — this CLI covers 'gateway bench'. Run 'gateway help'.`,\n );\n }\n if (!command) fail(HELP);\n if (PYTHON_ONLY.has(command)) {\n fail(\n `'gateway bench eval' runs the world locally on the PYTHON engines (verifiers/harbor) — it cannot exist in a JS process.\\n` +\n `Run hosted instead: gateway bench dispatch <runConfigId> — same worlds, graded on the platform.`,\n );\n }\n\n const { positional, flags } = parseArgv(rest);\n\n switch (command) {\n case \"resolve\": {\n const slugRef =\n positional[0] ?? fail(\"usage: gateway bench resolve <slug[@ref]>\");\n const world = await openWorld(slugRef);\n console.log(\n `${world.slug}@${world.ref ?? \"latest\"}: ${world.version.semanticVersion ?? \"-\"} ` +\n `(${world.version.contentHash.slice(0, 12)}) · ${world.version.state ?? \"?\"} · ${world.tasks.length} tasks`,\n );\n console.log(`versionId: ${world.version.versionId}`);\n return 0;\n }\n case \"tasks\": {\n const slugRef =\n positional[0] ?? fail(\"usage: gateway bench tasks <slug[@ref]>\");\n const world = await openWorld(slugRef);\n if (world.tasks.length === 0) {\n console.log(\"No task manifest served for this version.\");\n return 0;\n }\n for (const task of world.tasks) {\n console.log(`${task.name}${task.variant ? ` (${task.variant})` : \"\"}`);\n }\n return 0;\n }\n case \"dispatch\": {\n const runConfigId =\n positional[0] ?? fail(\"usage: gateway bench dispatch <runConfigId>\");\n const body: Record<string, string> = { runConfigId };\n const containerId = str(flags, \"container-id\");\n const versionId = str(flags, \"version-id\");\n if (containerId) body.containerId = containerId;\n if (versionId) body.versionId = versionId;\n const result = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(\n {},\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n body,\n );\n for (const run of result.runs) {\n console.log(\n `${run.model}: ${run.ok ? \"dispatched\" : `FAILED: ${run.error}`} run=${run.runId}`,\n );\n }\n console.log(`-> ${result.versionLabel}`);\n return result.runs.every((r) => r.ok) ? 0 : 1;\n }\n case \"run\": {\n const runId =\n positional[0] ?? fail(\"usage: gateway bench run <runId> [--wait]\");\n const report = flags.wait\n ? await waitForRun(runId, {\n timeoutMinutes: Number(str(flags, \"timeout-min\") ?? 45),\n onTick: (r) =>\n console.error(\n `…${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n })\n : await getRun(runId);\n console.log(\n `${report.id} ${report.status}${report.score !== null ? ` score=${report.score.toFixed(3)}` : \"\"}` +\n ` (${report.model ?? \"?\"} · ${report.versionLabel ?? \"?\"} · x${report.parallelism})`,\n );\n for (const sample of report.samples) {\n const subs = Object.entries(sample.rewards)\n .filter(([, v]) => typeof v === \"number\")\n .map(([k, v]) => `${k}=${(v as number).toFixed(2)}`)\n .join(\" \");\n console.log(\n ` ${(sample.reward ?? 0).toFixed(2)} ${sample.task ?? \"?\"}${subs ? ` [${subs}]` : \"\"}`,\n );\n }\n if (report.summary) console.log(` ${report.summary}`);\n return report.terminal && report.status.toUpperCase() === \"COMPLETED\"\n ? 0\n : 1;\n }\n case \"run-configs\": {\n const action = positional[0] ?? \"list\";\n if (action === \"list\") {\n const rows = await listRunConfigs();\n if (rows.length === 0) {\n console.log(\"No run configs in this project.\");\n return 0;\n }\n for (const row of rows) {\n const extras = [\n row.parallelism > 1 ? `x${row.parallelism} containers` : null,\n row.autoRunOnPush ? \"auto-on-push\" : null,\n ].filter(Boolean);\n console.log(\n `${row.id} ${row.name} (${row.models.join(\", \") || \"no models\"})${extras.length ? ` [${extras.join(\", \")}]` : \"\"}`,\n );\n }\n return 0;\n }\n if (action === \"delete\") {\n const id = str(flags, \"id\") ?? fail(\"--id is required for delete\");\n await apiRequest(\n {},\n \"DELETE\",\n \"/api/public/benchmark-containers/run-configs\",\n { id },\n );\n console.log(`Deleted ${id}.`);\n return 0;\n }\n if (action !== \"create\")\n fail(\"run-configs actions: list | create | delete\");\n const name = str(flags, \"name\") ?? fail(\"--name is required for create\");\n const models = (\n str(flags, \"models\") ?? fail(\"--models is required for create\")\n )\n .split(\",\")\n .map((m) => m.trim())\n .filter(Boolean);\n const body: Record<string, unknown> = { name, models };\n const parallelism = str(flags, \"parallelism\");\n if (parallelism) body.parallelism = Number(parallelism);\n const agent = str(flags, \"agent\");\n if (agent) body.agent = agent;\n const tasks = str(flags, \"tasks\");\n if (tasks)\n body.taskNames = tasks\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean);\n if (flags[\"auto-run-on-push\"]) body.autoRunOnPush = true;\n const id = str(flags, \"id\");\n if (id) body.id = id;\n const row = await apiRequest<{\n id: string;\n name: string;\n models: string[];\n }>({}, \"POST\", \"/api/public/benchmark-containers/run-configs\", body);\n console.log(`${row.id} ${row.name} (${row.models.join(\", \")})`);\n return 0;\n }\n case \"secrets\": {\n const action =\n positional[0] ?? fail(\"secrets actions: set | list | unset\");\n const env = str(flags, \"env\") ?? fail(\"--env <world slug> is required\");\n if (action === \"list\") {\n const rows = await listEnvSecretKeys(env);\n if (rows.length === 0) {\n console.log(`No secrets on ${env}.`);\n return 0;\n }\n for (const row of rows)\n console.log(`${row.key} (rotated ${row.updatedAt})`);\n return 0;\n }\n const key = str(flags, \"key\") ?? fail(`--key is required for ${action}`);\n if (action === \"unset\") {\n await deleteEnvSecret(env, key);\n console.log(`Deleted ${key} from ${env}.`);\n return 0;\n }\n if (action !== \"set\") fail(\"secrets actions: set | list | unset\");\n const value = str(flags, \"value\") ?? (await readStdin());\n if (!value)\n fail(\"empty value — nothing stored (pass --value or pipe stdin)\");\n const res = await setEnvSecret(env, key, value);\n console.log(\n `${res.created ? \"Added\" : \"Rotated\"} ${key} on ${env} — next hosted run receives it.`,\n );\n return 0;\n }\n case \"refs\": {\n const slug = positional[0] ?? fail(\"usage: gateway bench refs <slug>\");\n const res = await apiRequest<{\n refs: {\n name: string;\n kind: string;\n semanticVersion: string | null;\n contentHash: string | null;\n state: string | null;\n }[];\n }>(\n {},\n \"GET\",\n `/api/public/benchmark-containers/refs?slug=${encodeURIComponent(slug)}`,\n );\n for (const ref of res.refs) {\n console.log(\n `${ref.kind === \"tag\" ? \"tag \" : \"branch\"} ${ref.name} ${ref.semanticVersion ?? \"-\"} (${ref.contentHash?.slice(0, 12) ?? \"?\"}) ${ref.state ?? \"\"}`,\n );\n }\n return 0;\n }\n case \"log\": {\n const slug = positional[0] ?? fail(\"usage: gateway bench log <slug>\");\n const params = new URLSearchParams({ slug });\n const branch = str(flags, \"branch\");\n if (branch) params.set(\"branch\", branch);\n const limit = str(flags, \"limit\");\n if (limit) params.set(\"limit\", limit);\n const res = await apiRequest<{\n branch: string;\n entries: {\n versionId: string;\n contentHash: string;\n semanticVersion: string | null;\n state: string;\n author: string | null;\n changeReason: string | null;\n }[];\n }>(\n {},\n \"GET\",\n `/api/public/benchmark-containers/log?${params.toString()}`,\n );\n console.log(`branch: ${res.branch}`);\n for (const entry of res.entries) {\n console.log(\n `${entry.contentHash.slice(0, 12)} ${entry.semanticVersion ?? \"-\"} ${entry.state}` +\n `${entry.author ? ` by ${entry.author}` : \"\"}${entry.changeReason ? ` — ${entry.changeReason}` : \"\"}`,\n );\n }\n return 0;\n }\n case \"proposals\": {\n const slug =\n positional[0] ?? fail(\"usage: gateway bench proposals <slug>\");\n const params = new URLSearchParams({ slug });\n const status = str(flags, \"status\");\n if (status) params.set(\"status\", status);\n const res = await apiRequest<{\n proposals: {\n id: string;\n title?: string | null;\n status: string;\n createdAt?: string;\n }[];\n }>(\n {},\n \"GET\",\n `/api/public/benchmark-containers/proposals?${params.toString()}`,\n );\n if (res.proposals.length === 0) {\n console.log(\"No proposals.\");\n return 0;\n }\n for (const proposal of res.proposals) {\n console.log(\n `${proposal.id} [${proposal.status}] ${proposal.title ?? \"\"}`,\n );\n }\n return 0;\n }\n case \"pull\": {\n const slugRef =\n positional[0] ??\n fail(\"usage: gateway bench pull <slug[@ref]> [--dir D]\");\n const res = await pull(slugRef, str(flags, \"dir\"));\n console.log(\n `Pulled ${res.slug} -> ${res.dir} (${res.files} files, version ${res.versionId})`,\n );\n return 0;\n }\n case \"checkout\": {\n const slugRef =\n positional[0] ??\n fail(\"usage: gateway bench checkout <slug@ref> --dir D\");\n const dir =\n str(flags, \"dir\") ??\n fail(\"--dir is required for checkout (the working dir to re-aim)\");\n const res = await pull(slugRef, dir);\n console.log(\n `Checked out ${slugRef} into ${res.dir} (${res.files} files)`,\n );\n return 0;\n }\n case \"push\": {\n const dir = positional[0] ?? \".\";\n const res = await push(dir, {\n slug: str(flags, \"slug\"),\n branch: str(flags, \"branch\"),\n force: Boolean(flags.force),\n message: str(flags, \"message\"),\n author: str(flags, \"author\"),\n });\n console.log(\n `Pushed ${res.slug}@${res.branch}: version ${res.versionId} (${res.contentHash.slice(0, 12)})`,\n );\n return 0;\n }\n case \"validate\": {\n // The CI entry: push THIS checkout's world source on the PR's branch,\n // run it, gate on the graded result. Exit code is the check.\n const dir = positional[0] ?? \".\";\n const runConfig =\n str(flags, \"run-config\") ??\n fail(\n \"usage: gateway bench validate [dir] --run-config NAME [--slug S] [--branch B] [--min-score X] [--summary-file F] [--timeout-min N]\",\n );\n const minScoreRaw = str(flags, \"min-score\");\n const report = await validateWorld(dir, {\n slug: str(flags, \"slug\"),\n runConfig,\n branch: str(flags, \"branch\"),\n minScore: minScoreRaw === undefined ? null : Number(minScoreRaw),\n timeoutMinutes: Number(str(flags, \"timeout-min\") ?? 45),\n onProgress: (line) => console.error(line),\n });\n for (const run of report.runs) {\n console.log(\n `${run.model}: ${run.failure ? `FAIL — ${run.failure}` : \"pass\"}` +\n `${run.report?.score != null ? ` score=${run.report.score.toFixed(3)}` : \"\"}` +\n `${run.report?.url ? ` ${run.report.url}` : \"\"}`,\n );\n }\n // The markdown lands wherever the caller wants to publish it: a file\n // for a PR comment, and the step summary when GitHub provides one.\n const summaryFile = str(flags, \"summary-file\");\n if (summaryFile) fs.writeFileSync(summaryFile, report.markdown + \"\\n\");\n const stepSummary = process.env.GITHUB_STEP_SUMMARY;\n if (stepSummary) fs.appendFileSync(stepSummary, report.markdown + \"\\n\");\n console.log(report.ok ? \"validation passed\" : \"validation FAILED\");\n return report.ok ? 0 : 1;\n }\n case \"status\": {\n const dir = positional[0] ?? \".\";\n const state = localTreeState(dir);\n if (!state.meta) {\n console.log(\n \"Ad-hoc dir: no pull/push base recorded (.gateway missing).\",\n );\n return 0;\n }\n console.log(\n `base: ${state.meta.slug}@${state.meta.branch ?? \"?\"} version ${state.meta.versionId ?? \"?\"}`,\n );\n const localHash = computeContentHash(dir);\n const baseHash = state.meta.contentHash;\n console.log(\n `content hash: ${localHash.slice(0, 12)} ${localHash === baseHash ? \"== base (hash-verified)\" : `!= base ${String(baseHash).slice(0, 12)}`}`,\n );\n if (state.clean) {\n console.log(\"clean — tree matches its base.\");\n return 0;\n }\n console.log(`dirty (${state.dirty.length}):`);\n for (const p of state.dirty.slice(0, 40)) console.log(` ${p}`);\n return 0;\n }\n case \"branch\":\n case \"tag\": {\n const slug =\n positional[0] ?? fail(`usage: gateway bench ${command} <slug> <name>`);\n const name =\n positional[1] ?? fail(`usage: gateway bench ${command} <slug> <name>`);\n const ref = await createRef(\n slug,\n name,\n command as \"branch\" | \"tag\",\n str(flags, \"version-id\"),\n );\n console.log(`${ref.kind} ${ref.name} -> ${ref.versionId}`);\n return 0;\n }\n case \"propose\": {\n const dir = positional[0] ?? \".\";\n const title = str(flags, \"title\") ?? fail(\"--title is required\");\n const reason = str(flags, \"reason\") ?? fail(\"--reason is required\");\n const res = await propose(dir, {\n title,\n reason,\n targetBranch: str(flags, \"target-branch\"),\n });\n console.log(`Proposal ${res.proposalId} opened.`);\n return 0;\n }\n default:\n fail(`Unknown command 'bench ${command}'.\\n\\n${HELP}`);\n }\n}\n\nmain().then(\n (code) => process.exit(code),\n (error) => {\n console.error(error instanceof Error ? error.message : String(error));\n process.exit(1);\n },\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA2FO,SAAS,oBAAoB,MAOlC;AACA,QAAM,SAAS,oBAAoB,KAAK,KAA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EACL,CAAC,SAAS,QAAQ,KAAK,IAAI;AAAA,EAC3B,CAAC,UAAU;AACT,YAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACpE,YAAQ,KAAK,CAAC;AAAA,EAChB;AACF;","names":["openWorld","pad","resolve","path","resolve","openSession","fs","row","id"]}
1
+ {"version":3,"sources":["../src/cli/router.ts","../src/cli/config.ts","../src/cli/platform/shared.ts","../src/cli/runtime/local.ts","../src/cli/runtime/client.ts","../src/worlds/browser.ts","../src/worlds/session.ts","../src/worlds/tasks.ts","../src/worlds/hub.ts","../src/worlds/validate.ts","../src/worlds/describe.ts","../src/cli/platform/worldData/json.ts","../src/worlds/transforms.ts","../src/worlds/redaction.ts","../src/worlds/query.ts","../src/worlds/migrate.ts","../src/cli/runtime/data.ts","../src/cli/platform/worldData/transform.ts","../src/cli/platform/worldData/batches.ts","../src/cli/platform/worldData/chunker.ts","../src/cli/platform/worldData/push.ts","../src/worlds/ingest.ts","../src/worlds/index.ts","../src/cli/platform/skill.ts","../src/cli/platform/connector.ts","../src/cli/runtime/schema.ts","../src/cli/platform/worldData/traceCalls.ts","../src/cli/main.ts","../src/cli/platform/agent.ts","../src/cli/platform/auth.ts","../src/cli/platform/bench.ts","../src/cli/platform/benchmarks.ts","../src/benchmarks/index.ts","../src/benchmarks/container.ts","../src/cli/platform/environment.ts","../src/cli/platform/worlds.ts","../src/cli/platform/rows.ts","../src/cli/platform/index.ts","../src/cli/platform/data.ts","../src/cli/platform/worldData/callsPull.ts","../src/cli/platform/worldData/extract.ts","../src/cli/platform/worldData/rowSource.ts","../src/cli/platform/worldData/scanner.ts","../src/cli/platform/worldData/ingestMap.ts","../src/cli/platform/worldData/toml.ts","../src/cli/platform/worldData/records.ts","../src/cli/platform/worldData/manifest.ts","../src/cli/platform/worldData/worldConfig.ts","../src/cli/platform/worldData/driveIo.ts","../src/files/index.ts","../src/cli/platform/dataset.ts","../src/cli/platform/files.ts","../src/cli/platform/pythonOnly.ts","../src/cli/platform/release.ts","../src/cli/platform/run.ts","../src/cli/platform/secret.ts","../src/cli/platform/session.ts","../src/cli/platform/task.ts","../src/cli/platform/traces.ts","../src/traces/index.ts","../src/cli/runtime/index.ts","../src/cli/runtime/connector.ts","../src/cli/runtime/run.ts","../src/cli/runtime/serve.ts","../src/cli/runtime/test.ts","../src/cli/runtime/call.ts","../src/cli/runtime/scaffold.ts","../src/cli.ts"],"sourcesContent":["/**\n * The `gateway` command tree, with no dependency: groups hold commands, a\n * command declares its positionals and flags, help is generated from the\n * declarations so `gateway <group> --help` always matches what runs.\n *\n * Flags: `--name value`, `--name=value`, `--flag` (boolean), repeatable flags\n * collect into arrays when declared `repeat: true`. Anything after `--` is\n * positional.\n */\n\nexport type FlagSpec = {\n name: string;\n help: string;\n /** Short alias, e.g. \"m\" for --message. */\n short?: string;\n /** Boolean flags take no value. */\n boolean?: boolean;\n repeat?: boolean;\n default?: string | boolean;\n /** Environment variable that fills the flag when it is not given. */\n env?: string;\n};\n\nexport type PositionalSpec = {\n name: string;\n help: string;\n optional?: boolean;\n /** Collects every remaining positional. */\n variadic?: boolean;\n};\n\nexport type Parsed = {\n positionals: string[];\n flags: Record<string, string | boolean | string[] | undefined>;\n};\n\nexport type CommandSpec = {\n name: string;\n help: string;\n positionals?: PositionalSpec[];\n flags?: FlagSpec[];\n /** Long-form notes printed under the usage line in `--help`. */\n notes?: string;\n run: (args: Parsed, ctx: CommandContext) => Promise<number | void>;\n};\n\nexport type CommandContext = {\n stdout: (line: string) => void;\n stderr: (line: string) => void;\n /** Read all of stdin (for --value-less secrets, piped rows). */\n stdin: () => Promise<string>;\n /** Stdin as a stream, for inputs too large to hold (`worlds data import … -`). */\n stdinStream?: () => NodeJS.ReadableStream;\n};\n\nexport class CommandGroup {\n readonly groups = new Map<string, CommandGroup>();\n readonly commands = new Map<string, CommandSpec>();\n /** Long-form notes printed under the command list in `--help`. */\n notes?: string;\n constructor(\n readonly name: string,\n readonly help: string,\n ) {}\n group(name: string, help: string): CommandGroup {\n const existing = this.groups.get(name);\n if (existing) return existing;\n const created = new CommandGroup(name, help);\n this.groups.set(name, created);\n return created;\n }\n command(spec: CommandSpec): this {\n this.commands.set(spec.name, spec);\n return this;\n }\n}\n\nexport class CliError extends Error {\n constructor(\n message: string,\n readonly exitCode = 2,\n ) {\n super(message);\n }\n}\n\nexport function parseArgs(spec: CommandSpec, argv: string[]): Parsed {\n const flagSpecs = spec.flags ?? [];\n const byName = new Map<string, FlagSpec>();\n for (const f of flagSpecs) {\n byName.set(f.name, f);\n if (f.short) byName.set(f.short, f);\n }\n const positionals: string[] = [];\n const flags: Parsed[\"flags\"] = {};\n let onlyPositionals = false;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i]!;\n if (onlyPositionals || !arg.startsWith(\"-\") || arg === \"-\") {\n positionals.push(arg);\n continue;\n }\n if (arg === \"--\") {\n onlyPositionals = true;\n continue;\n }\n const bare = arg.replace(/^--?/, \"\");\n const [rawName, inlineValue] = bare.includes(\"=\")\n ? [bare.slice(0, bare.indexOf(\"=\")), bare.slice(bare.indexOf(\"=\") + 1)]\n : [bare, undefined];\n const f = byName.get(rawName);\n if (!f) throw new CliError(`Unknown flag --${rawName} for ${spec.name}`);\n if (f.boolean) {\n flags[f.name] =\n inlineValue === undefined ? true : inlineValue !== \"false\";\n continue;\n }\n let value = inlineValue;\n if (value === undefined) {\n const next = argv[i + 1];\n if (next === undefined || (next.startsWith(\"--\") && next.length > 2))\n throw new CliError(`--${f.name} needs a value`);\n value = next;\n i++;\n }\n if (f.repeat) {\n const current = flags[f.name];\n flags[f.name] = Array.isArray(current) ? [...current, value] : [value];\n } else flags[f.name] = value;\n }\n for (const f of flagSpecs) {\n if (flags[f.name] !== undefined) continue;\n const fromEnv = f.env ? process.env[f.env] : undefined;\n if (fromEnv !== undefined && fromEnv !== \"\") flags[f.name] = fromEnv;\n else if (f.default !== undefined) flags[f.name] = f.default;\n }\n const specs = spec.positionals ?? [];\n const required = specs.filter((p) => !p.optional && !p.variadic).length;\n if (positionals.length < required)\n throw new CliError(\n `${spec.name} needs ${specs\n .slice(0, required)\n .map((p) => `<${p.name}>`)\n .join(\" \")}`,\n );\n const variadic = specs.some((p) => p.variadic);\n if (!variadic && positionals.length > specs.length)\n throw new CliError(\n `${spec.name} takes ${specs.length} argument${specs.length === 1 ? \"\" : \"s\"}, got ${positionals.length}`,\n );\n return { positionals, flags };\n}\n\n/** Typed accessors so commands never repeat the narrowing. */\nexport const arg = {\n str(p: Parsed, name: string): string | undefined {\n const v = p.flags[name];\n return typeof v === \"string\" ? v : undefined;\n },\n bool(p: Parsed, name: string): boolean {\n return p.flags[name] === true;\n },\n list(p: Parsed, name: string): string[] {\n const v = p.flags[name];\n if (Array.isArray(v)) return v;\n return typeof v === \"string\" ? [v] : [];\n },\n int(p: Parsed, name: string): number | undefined {\n const v = arg.str(p, name);\n if (v === undefined) return undefined;\n const n = Number(v);\n if (!Number.isInteger(n))\n throw new CliError(`--${name} must be an integer`);\n return n;\n },\n};\n\nfunction usageLine(path: string[], spec: CommandSpec): string {\n const pos = (spec.positionals ?? [])\n .map((p) =>\n p.variadic\n ? `<${p.name}...>`\n : p.optional\n ? `[${p.name}]`\n : `<${p.name}>`,\n )\n .join(\" \");\n return `${path.join(\" \")} ${pos}`.trim();\n}\n\nexport function helpFor(\n path: string[],\n node: CommandGroup | CommandSpec,\n): string {\n if (node instanceof CommandGroup) {\n const lines = [`${path.join(\" \")} — ${node.help}`, \"\"];\n for (const [name, g] of node.groups)\n lines.push(` ${name.padEnd(16)} ${g.help}`);\n for (const [name, c] of node.commands)\n lines.push(` ${name.padEnd(16)} ${c.help}`);\n if (node.notes) lines.push(\"\", node.notes);\n lines.push(\"\", `Run '${path.join(\" \")} <command> --help' for details.`);\n return lines.join(\"\\n\");\n }\n const lines = [usageLine(path, node), \"\", ` ${node.help}`];\n const pos = node.positionals ?? [];\n if (pos.length) {\n lines.push(\"\", \"Arguments:\");\n for (const p of pos) lines.push(` ${p.name.padEnd(18)} ${p.help}`);\n }\n const flags = node.flags ?? [];\n if (flags.length) {\n lines.push(\"\", \"Options:\");\n for (const f of flags) {\n const label = `--${f.name}${f.short ? `, -${f.short}` : \"\"}${f.boolean ? \"\" : \" <value>\"}`;\n const extras = [\n f.default !== undefined ? `default ${String(f.default)}` : null,\n f.env ? `env ${f.env}` : null,\n ]\n .filter(Boolean)\n .join(\", \");\n lines.push(\n ` ${label.padEnd(28)} ${f.help}${extras ? ` (${extras})` : \"\"}`,\n );\n }\n }\n if (node.notes) lines.push(\"\", node.notes);\n return lines.join(\"\\n\");\n}\n\n/** Walk the tree and run: exit code 0 on success, 2 on usage error, 1 on failure. */\nexport async function dispatch(\n root: CommandGroup,\n argv: string[],\n ctx: CommandContext,\n): Promise<number> {\n let node: CommandGroup = root;\n const path = [root.name];\n let i = 0;\n while (i < argv.length) {\n const token = argv[i]!;\n if (token === \"--help\" || token === \"-h\") {\n ctx.stdout(helpFor(path, node));\n return 0;\n }\n const group = node.groups.get(token);\n if (group) {\n node = group;\n path.push(token);\n i++;\n continue;\n }\n const command = node.commands.get(token);\n if (command) {\n const rest = argv.slice(i + 1);\n if (rest.includes(\"--help\") || rest.includes(\"-h\")) {\n ctx.stdout(helpFor([...path, token], command));\n return 0;\n }\n try {\n const parsed = parseArgs(command, rest);\n const code = await command.run(parsed, ctx);\n return code ?? 0;\n } catch (error) {\n if (error instanceof CliError) {\n ctx.stderr(error.message);\n return error.exitCode;\n }\n ctx.stderr(error instanceof Error ? error.message : String(error));\n return 1;\n }\n }\n ctx.stderr(\n `Unknown command '${token}' under '${path.join(\" \")}'.\\n\\n${helpFor(path, node)}`,\n );\n return 2;\n }\n ctx.stdout(helpFor(path, node));\n return node === root ? 0 : 2;\n}\n","import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"./router\";\n\n/**\n * Where the CLI's credentials come from, in this order (the same as the\n * Python CLI): explicit --host, environment (GATEWAY_HOST, GATEWAY_PUBLIC_KEY,\n * GATEWAY_SECRET_KEY / GATEWAY_API_KEY), then ~/.gateway/config.json written\n * by `gateway auth login`. `GATEWAY_ENV_FILE=path` fills the environment from\n * a KEY=value file first (see `loadEnvFile`).\n */\nexport type StoredConfig = {\n host?: string;\n public_key?: string;\n api_key?: string;\n};\n\nexport function configPath(): string {\n return path.join(\n process.env.GATEWAY_CONFIG_DIR ?? path.join(os.homedir(), \".gateway\"),\n \"config.json\",\n );\n}\n\nexport function readConfig(): StoredConfig {\n try {\n return JSON.parse(fs.readFileSync(configPath(), \"utf8\")) as StoredConfig;\n } catch {\n return {};\n }\n}\n\nexport function writeConfig(config: StoredConfig): void {\n const file = configPath();\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });\n fs.writeFileSync(file, JSON.stringify(config, null, 2) + \"\\n\", { mode: 0o600 });\n}\n\nexport function clearConfig(): boolean {\n try {\n fs.unlinkSync(configPath());\n return true;\n } catch {\n return false;\n }\n}\n\nexport type Credentials = { host: string; publicKey: string; secretKey: string };\n\n/** The accepted env-file form, printed by `gateway --help` and the docs. */\nexport const ENV_FILE_FORM =\n \"GATEWAY_ENV_FILE=path loads a KEY=value file first: `KEY = value`, quoted values, \" +\n \"`export KEY=value` and `#` comments are all accepted; the shell's environment wins.\";\n\n/**\n * Parse a KEY=value file the way a person writes one, not the way `source`\n * reads one. Brex retrospective: the customer's `.env` had `GATEWAY_HOST = …`\n * (spaces around `=`), which the shell refused to source and the CLI could not\n * read either. Accepted: blank lines and `#` comments, an `export ` prefix,\n * spaces around `=`, single- or double-quoted values (quotes stripped, nothing\n * inside interpreted). Not accepted: a line without `=`, which is reported by\n * number rather than skipped, because a silently dropped credential shows up\n * later as \"API key not configured\".\n */\nexport function parseEnvFile(text: string): Record<string, string> {\n const values: Record<string, string> = {};\n const lines = text.split(/\\r?\\n/);\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index]!.trim();\n if (!line || line.startsWith(\"#\")) continue;\n const assignment = line.startsWith(\"export \") ? line.slice(\"export \".length).trim() : line;\n const eq = assignment.indexOf(\"=\");\n if (eq === -1) throw new CliError(`env file line ${index + 1} is not KEY=value: ${line}`);\n const key = assignment.slice(0, eq).trim();\n let value = assignment.slice(eq + 1).trim();\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))\n throw new CliError(`env file line ${index + 1} has an invalid variable name: ${key || line}`);\n const quote = value[0];\n if ((quote === '\"' || quote === \"'\") && value.length >= 2 && value.endsWith(quote))\n value = value.slice(1, -1);\n values[key] = value;\n }\n return values;\n}\n\n/**\n * Put `GATEWAY_ENV_FILE`'s variables into the process environment, without\n * overriding anything already set there. Explicit on purpose: the CLI never\n * reads a `.env` it was not pointed at. Vendor keys named by connector.toml\n * ride along, so a local capture sees them too. Returns the keys it set.\n */\nexport function loadEnvFile(): string[] {\n const file = process.env.GATEWAY_ENV_FILE;\n if (!file) return [];\n let text: string;\n try {\n text = fs.readFileSync(file, \"utf8\");\n } catch (error) {\n throw new CliError(`GATEWAY_ENV_FILE=${file} could not be read: ${(error as Error).message}`);\n }\n const set: string[] = [];\n for (const [key, value] of Object.entries(parseEnvFile(text))) {\n if (process.env[key] !== undefined) continue;\n process.env[key] = value;\n set.push(key);\n }\n return set;\n}\n\nexport function resolveCredentials(hostFlag?: string): Credentials {\n const stored = readConfig();\n const host = (hostFlag ?? process.env.GATEWAY_HOST ?? stored.host ?? \"\").replace(/\\/+$/, \"\");\n const publicKey = process.env.GATEWAY_PUBLIC_KEY ?? stored.public_key ?? \"\";\n const secretKey =\n process.env.GATEWAY_SECRET_KEY ?? process.env.GATEWAY_API_KEY ?? stored.api_key ?? \"\";\n if (!host)\n throw new CliError(\n \"Host not configured. Pass --host, set GATEWAY_HOST, or run `gateway auth login`.\",\n );\n if (!publicKey || !secretKey)\n throw new CliError(\n \"API key not configured. Set GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY, or run `gateway auth login`.\",\n );\n return { host, publicKey, secretKey };\n}\n\n/** A non-2xx answer from the platform: the status is a field, never something to regex out of the text. */\nexport class ApiError extends CliError {\n constructor(\n readonly status: number,\n readonly method: string,\n readonly route: string,\n readonly text: string,\n ) {\n super(`${method} ${route} -> ${status}: ${text.slice(0, 600)}`, 1);\n }\n}\n\n/** One JSON request against the platform, Basic-authenticated with the project key. */\nexport async function api<T = unknown>(\n creds: Credentials,\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n route: string,\n body?: unknown,\n init: { timeoutMs?: number } = {},\n): Promise<T> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), init.timeoutMs ?? 120_000);\n try {\n const res = await fetch(`${creds.host}${route}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n signal: controller.signal,\n });\n const text = await res.text();\n if (!res.ok) throw new ApiError(res.status, method, route, text);\n return (text ? JSON.parse(text) : {}) as T;\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport function printJson(ctx: { stdout: (line: string) => void }, value: unknown): void {\n ctx.stdout(JSON.stringify(value, null, 2));\n}\n","import * as fs from \"node:fs\";\n\nimport { resolveCredentials, type Credentials } from \"../config\";\nimport { arg, CliError, type CommandContext, type FlagSpec, type Parsed } from \"../router\";\nimport type { WorldsClientOptions } from \"../../worlds/index\";\n\n/** `--host` exactly as the Python CLI declares it (env GATEWAY_HOST). */\nexport const HOST_FLAG: FlagSpec = {\n name: \"host\",\n help: \"Gateway server URL (e.g. https://withgateway.ai).\",\n env: \"GATEWAY_HOST\",\n};\n\n/** `--api-key` where the Python command takes one (env GATEWAY_SECRET_KEY). */\nexport const API_KEY_FLAG: FlagSpec = {\n name: \"api-key\",\n help: \"Project secret key (sk-lf-...).\",\n env: \"GATEWAY_SECRET_KEY\",\n};\n\n/** Credentials for a command: --host / --api-key first, then env, then ~/.gateway/config.json. */\nexport function credentials(args: Parsed): Credentials {\n const creds = resolveCredentials(arg.str(args, \"host\"));\n const apiKey = arg.str(args, \"api-key\");\n return apiKey ? { ...creds, secretKey: apiKey } : creds;\n}\n\n/** The same credentials in the shape the `worlds/*` helpers take. */\nexport function worldsOptions(creds: Credentials): WorldsClientOptions {\n return { host: creds.host, publicKey: creds.publicKey, secretKey: creds.secretKey };\n}\n\nexport type RawResponse = {\n status: number;\n ok: boolean;\n text: string;\n json: () => unknown;\n};\n\n/**\n * One request whose status the command inspects itself (409 → update, 404 →\n * untested, …), where `api()`'s throw-on-non-2xx would hide the branch.\n */\nexport async function rawRequest(\n creds: Credentials,\n method: \"GET\" | \"POST\" | \"PUT\" | \"DELETE\",\n route: string,\n body?: unknown,\n): Promise<RawResponse> {\n const res = await fetch(`${creds.host}${route}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n const text = await res.text();\n return {\n status: res.status,\n ok: res.ok,\n text,\n json: () => (text ? JSON.parse(text) : {}),\n };\n}\n\nexport function query(params: Record<string, string | number | boolean | undefined | null>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null || value === \"\") continue;\n search.set(key, String(value));\n }\n const encoded = search.toString();\n return encoded ? `?${encoded}` : \"\";\n}\n\nexport function failed(status: number, text: string): CliError {\n return new CliError(`Failed (HTTP ${status}): ${text}`, 1);\n}\n\n/** Progress lines on stderr: on a TTY, or as GATEWAY_PROGRESS=1|0 says (the Python `tty_progress`). */\nexport function showProgress(): boolean {\n const forced = process.env.GATEWAY_PROGRESS;\n if (forced === \"1\") return true;\n if (forced === \"0\") return false;\n return Boolean(process.stderr.isTTY);\n}\n\nexport const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/** Where the Python CLI needed its own runtime: say so, name the equivalent, exit 2. */\nexport function pythonOnly(ctx: CommandContext, command: string, reason: string, equivalent: string): number {\n ctx.stderr(`'gateway ${command}' is Python-only: ${reason}\\n${equivalent}`);\n return 2;\n}\n\n/** Append a markdown block to $GITHUB_STEP_SUMMARY when Actions provides one; never fatal. */\nexport function appendStepSummary(text: string): void {\n const path = process.env.GITHUB_STEP_SUMMARY;\n if (!path) return;\n try {\n fs.appendFileSync(path, text + \"\\n\\n\");\n } catch {\n // the summary is a nicety; the exit code is the contract\n }\n}\n\n/** The platform's notices about a world's shape, one stderr line each, so a\n * script reading stdout never sees them and a person always does. */\nexport function printDeprecations(\n ctx: { stderr: (line: string) => void },\n deprecations: { code: string; message: string; replacement: string }[] | undefined,\n): void {\n for (const notice of deprecations ?? [])\n ctx.stderr(`deprecated (${notice.code}): ${notice.message} Instead: ${notice.replacement}`);\n}\n\n","import { spawn, spawnSync } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as net from \"node:net\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../router\";\nimport { type Credentials, resolveCredentials } from \"../config\";\nimport type { RuntimeRequest } from \"./client\";\n\n/**\n * The schema runtime, run on THIS machine. The npm package carries the SDK's\n * `gatewaysdk/environment` directory (stdlib-only Python, the same files the\n * platform's bridge executes), so any python3 >= 3.11 on the path runs it\n * exactly as the platform does — the same bootstrap, JSON in, JSON out. No\n * pip, no PyPI. When there is no such Python, callers fall back to\n * `POST /api/public/worlds/runtime`.\n *\n * `GATEWAY_RUNTIME=local|platform|auto` (default auto) forces one side;\n * `GATEWAY_PYTHON` names the interpreter (otherwise python3.13, python3.12,\n * python3.11, python3, python, then `uv python find` are tried in that order).\n */\n\nconst MIN_PYTHON: [number, number] = [3, 11];\nconst DIAGNOSTIC_TAIL = 600;\n\n/** The end of a failed run's output: a Python traceback names the exception last. */\nfunction tailOf(output: string): string {\n return output.length > DIAGNOSTIC_TAIL\n ? `…${output.slice(-DIAGNOSTIC_TAIL)}`\n : output;\n}\n\n/** The platform's own bootstrap: build the `gatewaysdk` package in memory from\n * the runtime root and run the bridge as __main__ (see worldSchemaRuntime.ts). */\nconst BRIDGE_BOOTSTRAP = `import sys,runpy,types,os\nroot=sys.argv[1]\npackage=types.ModuleType('gatewaysdk')\npackage.__path__=[os.path.join(root,'gatewaysdk')]\nsys.modules['gatewaysdk']=package\nrunpy.run_module('gatewaysdk.environment.schema.platform',run_name='__main__')`;\n\n/** The same, but running the schema module's own CLI (serve, connector-capture …)\n * with the arguments after the root. */\nconst MODULE_BOOTSTRAP = `import sys,runpy,types,os\nroot=sys.argv[1]\npackage=types.ModuleType('gatewaysdk')\npackage.__path__=[os.path.join(root,'gatewaysdk')]\nsys.modules['gatewaysdk']=package\nsys.argv=['gateway worlds']+sys.argv[2:]\nrunpy.run_module('gatewaysdk.environment.schema',run_name='__main__')`;\n\nexport type RuntimeMode = \"auto\" | \"local\" | \"platform\";\n\nexport function runtimeMode(): RuntimeMode {\n const raw = (process.env.GATEWAY_RUNTIME ?? \"auto\").toLowerCase();\n if (raw === \"local\" || raw === \"platform\" || raw === \"auto\") return raw;\n throw new CliError(\n `GATEWAY_RUNTIME must be local, platform or auto (got ${raw})`,\n );\n}\n\n/** Where the bundled runtime lives: `<package>/runtime` beside dist/, or the\n * monorepo's SDK source when running from the repository.\n *\n * The entry is `dist/cli.js` (the published bin) or `src/cli.ts` (from\n * source): one directory under the package root either way, so the Python\n * source is `<entry dir>/../../sdk/src` — `gatewaysdk/sdk/src`. It used to\n * walk one level too far (`<repo>/sdk/src`, which does not exist), so every\n * from-source run missed the runtime and fell back to the platform, demanding\n * a host for commands that need none (`schema init --connector salesforce`,\n * 2026-09-16). */\nexport function runtimeRoot(): string | null {\n const candidates: string[] = [];\n if (process.env.GATEWAY_RUNTIME_PATH)\n candidates.push(process.env.GATEWAY_RUNTIME_PATH);\n const entry =\n process.argv[1] && fs.existsSync(process.argv[1])\n ? path.dirname(fs.realpathSync(process.argv[1]))\n : null;\n if (entry) {\n candidates.push(path.resolve(entry, \"..\", \"runtime\"));\n candidates.push(path.resolve(entry, \"..\", \"..\", \"runtime\"));\n candidates.push(path.resolve(entry, \"..\", \"..\", \"sdk\", \"src\"));\n }\n candidates.push(path.resolve(process.cwd(), \"runtime\"));\n for (const root of candidates)\n if (\n fs.existsSync(\n path.join(root, \"gatewaysdk\", \"environment\", \"schema\", \"platform.py\"),\n )\n )\n return root;\n return null;\n}\n\nlet pythonCache: string | null | undefined;\n/** What the search saw, for the one line `pythonAdvice` prints: each candidate\n * and its version, or null when it did not run. */\nlet pythonProbes: { name: string; version: string | null }[] = [];\n\n/** Forget the cached interpreter (tests re-probe with a different PATH or env). */\nexport function resetPythonCache(): void {\n pythonCache = undefined;\n pythonProbes = [];\n}\n\n/** Versioned names first: on a Mac the bare `python3` is often the system 3.9,\n * while Homebrew, pyenv or uv put a `python3.12` beside it. Last, ask uv for\n * an interpreter it manages (`uv python find` prints a path and downloads\n * nothing). Brex retrospective: the customer had to discover GATEWAY_PYTHON\n * by hand because the CLI stopped at `python3` = 3.9. */\nconst PYTHON_CANDIDATES = [\n \"python3.13\",\n \"python3.12\",\n \"python3.11\",\n \"python3\",\n \"python\",\n];\nconst UV_FIND = [\"python\", \"find\", `>=${MIN_PYTHON.join(\".\")}`];\n\nfunction probeVersion(name: string): string | null {\n const probe = spawnSync(\n name,\n [\"-c\", \"import sys;print(sys.version_info[0],sys.version_info[1])\"],\n { encoding: \"utf8\", timeout: 10_000 },\n );\n if (probe.status !== 0) return null;\n const [major, minor] = probe.stdout.trim().split(/\\s+/).map(Number);\n return Number.isInteger(major) && Number.isInteger(minor)\n ? `${major}.${minor}`\n : null;\n}\n\nfunction atLeastMinimum(version: string): boolean {\n const [major, minor] = version.split(\".\").map(Number);\n return (\n major! > MIN_PYTHON[0] ||\n (major === MIN_PYTHON[0] && minor! >= MIN_PYTHON[1])\n );\n}\n\n/** The interpreter uv would hand out, or null when uv is absent or has none. */\nfunction uvPython(): string | null {\n const found = spawnSync(\"uv\", UV_FIND, { encoding: \"utf8\", timeout: 10_000 });\n if (found.status !== 0) return null;\n const line = found.stdout.trim().split(/\\r?\\n/)[0] ?? \"\";\n return line || null;\n}\n\n/** A python3 at or above 3.11, or null. Cached for the process. `GATEWAY_PYTHON`\n * names the interpreter and is the only candidate then; otherwise the versioned\n * names, the bare ones, then uv's. */\nexport function findPython(): string | null {\n if (pythonCache !== undefined) return pythonCache;\n const named = process.env.GATEWAY_PYTHON;\n const candidates = named ? [named] : PYTHON_CANDIDATES;\n for (const name of candidates) {\n const version = probeVersion(name);\n pythonProbes.push({ name, version });\n if (version && atLeastMinimum(version)) {\n pythonCache = name;\n return name;\n }\n }\n if (!named) {\n const fromUv = uvPython();\n const version = fromUv ? probeVersion(fromUv) : null;\n pythonProbes.push({ name: fromUv ?? \"uv python find\", version });\n if (fromUv && version && atLeastMinimum(version)) {\n pythonCache = fromUv;\n return fromUv;\n }\n }\n pythonCache = null;\n return null;\n}\n\n/** ONE actionable line for a machine without a usable Python: what was found\n * and how to point the CLI at a newer interpreter. */\nexport function pythonAdvice(): string {\n findPython();\n const floor = MIN_PYTHON.join(\".\");\n const named = process.env.GATEWAY_PYTHON;\n const seen = pythonProbes\n .filter((probe) => probe.version)\n .map((probe) => `${probe.name} is ${probe.version}`);\n const found = seen.length\n ? seen.join(\", \")\n : named\n ? `${named} did not run`\n : \"none on PATH\";\n return (\n `No python3 >= ${floor} usable (${found}); set GATEWAY_PYTHON to a newer interpreter, ` +\n `e.g. GATEWAY_PYTHON=\"$(brew --prefix python@3.12)/bin/python3.12\" or GATEWAY_PYTHON=\"$(uv python find 3.12)\".`\n );\n}\n\n/** Why `localRuntime()` answers null, in one line: the mode, the interpreter\n * or the bundled files — so a refusal never blames Python on a machine that\n * merely set GATEWAY_RUNTIME=platform. */\nexport function localRuntimeReason(): string {\n if (runtimeMode() === \"platform\")\n return \"GATEWAY_RUNTIME=platform forces the hosted side.\";\n if (!findPython()) return pythonAdvice();\n if (!runtimeRoot())\n return \"The bundled runtime is missing (set GATEWAY_RUNTIME_PATH).\";\n return \"\";\n}\n\n/** Can this machine run the runtime itself? Both a Python and the bundled files. */\nexport function localRuntime(): { python: string; root: string } | null {\n if (runtimeMode() === \"platform\") return null;\n const python = findPython();\n const root = runtimeRoot();\n if (!python || !root) {\n if (runtimeMode() === \"local\")\n throw new CliError(\n !python\n ? `GATEWAY_RUNTIME=local but ${pythonAdvice()}`\n : \"GATEWAY_RUNTIME=local but the bundled runtime is missing (set GATEWAY_RUNTIME_PATH)\",\n );\n return null;\n }\n return { python, root };\n}\n\n/** Does the local Python have PyYAML? `conform` needs it for .yaml specs. */\nexport function localPythonHasYaml(python: string): boolean {\n return (\n spawnSync(python, [\"-c\", \"import yaml\"], { timeout: 10_000 }).status === 0\n );\n}\n\n/** One bridge request through the local runtime: JSON in on stdin, JSON out. */\nexport async function localBridge<T = Record<string, unknown>>(\n request: RuntimeRequest,\n local: { python: string; root: string },\n opts: { timeoutMs?: number } = {},\n): Promise<T> {\n const input = JSON.stringify(request);\n return await new Promise<T>((resolve, reject) => {\n const child = spawn(\n local.python,\n [\"-I\", \"-B\", \"-c\", BRIDGE_BOOTSTRAP, local.root],\n {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n // This is the author's machine running the author's world: the one\n // place the runtime may import and run a world's own Python (check's\n // handler execution, `worlds call`, `worlds test` tool cases).\n env: {\n PATH: process.env.PATH ?? \"\",\n HOME: process.env.HOME ?? \"\",\n TMPDIR: process.env.TMPDIR ?? \"\",\n GATEWAY_RUNTIME_EXECUTE: \"1\",\n },\n },\n );\n const out: Buffer[] = [];\n const err: Buffer[] = [];\n const timer = setTimeout(\n () => child.kill(\"SIGKILL\"),\n opts.timeoutMs ?? 300_000,\n );\n child.stdout.on(\"data\", (chunk: Buffer) => out.push(chunk));\n child.stderr.on(\"data\", (chunk: Buffer) => err.push(chunk));\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n reject(\n new CliError(\n `local runtime could not start (${local.python}): ${error.message}`,\n 1,\n ),\n );\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n const text = Buffer.concat(out).toString(\"utf8\");\n const stderr = Buffer.concat(err).toString(\"utf8\");\n let payload: unknown = null;\n try {\n payload = text ? JSON.parse(text) : null;\n } catch {\n payload = null;\n }\n if (payload && typeof payload === \"object\") {\n resolve(payload as T);\n return;\n }\n reject(\n new CliError(\n `local runtime (${request.command}) exited ${code}: ${tailOf((stderr || text).trim()) || \"no output\"}`,\n 1,\n ),\n );\n });\n child.stdin.end(input);\n });\n}\n\n/** `pid <n> (<command>)` of whatever listens on `port`, from lsof when this\n * machine has it; null when nothing can be said. Best effort, never an error. */\nexport function portOwner(port: number): string | null {\n const found = spawnSync(\"lsof\", [\"-nP\", `-iTCP:${port}`, \"-sTCP:LISTEN\", \"-Fpc\"], {\n encoding: \"utf8\",\n timeout: 5_000,\n });\n if (found.error || found.status !== 0) return null;\n let pid: string | null = null;\n let command: string | null = null;\n for (const line of found.stdout.split(\"\\n\")) {\n if (line.startsWith(\"p\") && pid === null) pid = line.slice(1);\n else if (line.startsWith(\"c\") && pid !== null && command === null) command = line.slice(1);\n }\n if (pid === null) return null;\n return `pid ${pid}${command ? ` (${command})` : \"\"}`;\n}\n\n/** Refuse, by name, a port another process already holds — BEFORE the runtime\n * is spawned. The Python side refuses too, but a backgrounded serve's output\n * goes unread, and every curl after it hit whatever else answered on the port\n * (CRM dogfood, 2026-09-16): this serve never answers from another server. */\nexport async function assertPortFree(port: number, host = \"127.0.0.1\"): Promise<void> {\n const taken = await new Promise<boolean>((resolve) => {\n const probe = net.createServer();\n probe.once(\"error\", () => resolve(true));\n probe.listen(port, host, () => probe.close(() => resolve(false)));\n });\n if (!taken) return;\n const owner = portOwner(port);\n throw new CliError(\n `port ${port} on ${host} is already in use${owner ? ` by ${owner}` : \"\"}; ` +\n \"nothing was served there — pass another --port, or stop that server first\",\n 1,\n );\n}\n\n/** Run the schema module's own CLI in the foreground (serve, connector-capture …). */\nexport async function localModule(\n argv: string[],\n local: { python: string; root: string },\n opts: { env?: Record<string, string>; cwd?: string } = {},\n): Promise<number> {\n return await new Promise<number>((resolve, reject) => {\n const child = spawn(\n local.python,\n [\"-B\", \"-c\", MODULE_BOOTSTRAP, local.root, ...argv],\n {\n stdio: \"inherit\",\n cwd: opts.cwd,\n env: { ...process.env, ...opts.env },\n },\n );\n // The child owns the port (`worlds serve`); a signal that stops this\n // process must stop it too, or the server lives on with no way to reach\n // the foreground that started it. A SIGKILL, or a wrapper that swallows\n // the signal, reaches nothing here — for that the runtime's `serve`\n // watches its parent pid and closes when this process is gone.\n const forward = (signal: NodeJS.Signals) => () => {\n if (child.exitCode === null && child.signalCode === null) child.kill(signal);\n };\n const handlers: [NodeJS.Signals, () => void][] = [\n [\"SIGINT\", forward(\"SIGINT\")],\n [\"SIGTERM\", forward(\"SIGTERM\")],\n [\"SIGHUP\", forward(\"SIGHUP\")],\n ];\n for (const [signal, handler] of handlers) process.on(signal, handler);\n const release = () => {\n for (const [signal, handler] of handlers) process.off(signal, handler);\n };\n child.on(\"error\", (error) => {\n release();\n reject(\n new CliError(\n `local runtime could not start (${local.python}): ${error.message}`,\n 1,\n ),\n );\n });\n child.on(\"close\", (code, signal) => {\n release();\n resolve(code ?? (signal ? 130 : 1));\n });\n });\n}\n\n/** Credentials when the platform may be needed; null when a local runtime\n * will do and none are configured (a `schema check` needs no login). */\nexport function credentialsForRuntime(hostFlag?: string): Credentials | null {\n try {\n return resolveCredentials(hostFlag);\n } catch (error) {\n if (error instanceof CliError && localRuntime()) return null;\n throw error;\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../router\";\nimport { localBridge, localPythonHasYaml, localRuntime, localRuntimeReason } from \"./local\";\nimport type { Credentials } from \"../config\";\n\n/**\n * The wire to the schema runtime, which is Python and runs on the platform:\n * a world directory goes up as `[{path, content b64}]`, one bridge request\n * comes back verbatim, and any files in the answer land back in the\n * directory. Nothing here interprets a contract — that is the bridge's job.\n */\n\nexport type WorldFile = { path: string; content: string };\n\n/** Directories that are never part of a world's files. */\nconst SKIP_DIRS = new Set([\"__pycache__\", \".git\", \"node_modules\", \".gateway\"]);\n\n/** Every file under `dir` as base64 entries with forward-slash relative paths,\n * sorted so the same tree always produces the same request. */\n/** Compiled snapshots (`db/state.*`, `scenarios/<name>/state.*`) are build outputs\n * of the tree's data, never inputs: the runtime rebuilds them from the journals\n * and strips them from what it returns, and a real world's snapshots alone can\n * exceed the bridge's 64 MiB request cap. */\nconst BUILD_OUTPUT = /(^|\\/)state\\.(sqlite|json)$/;\n\nexport function isBuildOutput(relPath: string): boolean {\n return BUILD_OUTPUT.test(relPath);\n}\n\nexport function readWorldFiles(dir: string, opts: { buildOutputs?: boolean } = {}): WorldFile[] {\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())\n throw new CliError(`Not a directory: ${dir}`);\n const out: WorldFile[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n const entries = fs.readdirSync(abs, { withFileTypes: true });\n entries.sort((a, b) => a.name.localeCompare(b.name));\n for (const entry of entries) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (!opts.buildOutputs && isBuildOutput(childRel)) continue;\n out.push({\n path: childRel,\n content: fs.readFileSync(path.join(dir, childRel)).toString(\"base64\"),\n });\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));\n}\n\nfunction assertSafeRelPath(rel: string): void {\n const parts = rel.split(\"/\");\n if (\n !rel ||\n rel.startsWith(\"/\") ||\n rel.includes(\"\\\\\") ||\n /^[A-Za-z]:/.test(rel) ||\n parts.some((p) => p === \"\" || p === \".\" || p === \"..\")\n )\n throw new CliError(`The runtime returned an unsafe file path: ${rel}`, 1);\n}\n\n/** Write bridge files into `dir`. With `clean`, files the runtime did not\n * return are removed first (the skipped dirs are left alone), so the tree\n * becomes exactly what the runtime holds. Returns the written paths. */\nexport function writeWorldFiles(\n dir: string,\n files: WorldFile[],\n opts: { clean?: boolean } = {},\n): string[] {\n for (const file of files) assertSafeRelPath(file.path);\n if (opts.clean && fs.existsSync(dir)) {\n const keep = new Set(files.map((f) => f.path));\n for (const existing of readWorldFiles(dir)) {\n if (!keep.has(existing.path)) fs.rmSync(path.join(dir, existing.path));\n }\n pruneEmptyDirs(dir);\n }\n fs.mkdirSync(dir, { recursive: true });\n const written: string[] = [];\n for (const file of files) {\n const target = path.join(dir, file.path);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, Buffer.from(file.content, \"base64\"));\n written.push(file.path);\n }\n return written;\n}\n\nfunction pruneEmptyDirs(root: string): void {\n const walk = (abs: string): boolean => {\n let empty = true;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {\n const child = path.join(abs, entry.name);\n if (entry.isDirectory()) {\n if (SKIP_DIRS.has(entry.name)) {\n empty = false;\n continue;\n }\n if (walk(child)) fs.rmdirSync(child);\n else empty = false;\n } else empty = false;\n }\n return empty;\n };\n walk(root);\n}\n\n/** The bridge's structured diagnostic, exactly as the Python ContractError\n * carries it (`code`, `message`, `path`, `schema_path`, plus context). */\nexport type BridgeErrorDetail = {\n code: string;\n message: string;\n path?: string;\n schema_path?: string;\n [key: string]: unknown;\n};\n\n/** Rendered the way the Python CLI prints a ContractError:\n * `{code} at {schema_path or path or '/'}: {message}`. */\nexport function formatBridgeError(detail: BridgeErrorDetail): string {\n const where = detail.schema_path || detail.path || \"/\";\n return `${detail.code} at ${where}: ${detail.message}`;\n}\n\nexport class BridgeRejected extends CliError {\n constructor(readonly detail: BridgeErrorDetail) {\n super(formatBridgeError(detail), 1);\n }\n}\n\nexport function detailFrom(payload: unknown): BridgeErrorDetail | null {\n if (!payload || typeof payload !== \"object\") return null;\n const error = (payload as { error?: unknown }).error;\n if (!error || typeof error !== \"object\") return null;\n const detail = error as Record<string, unknown>;\n if (typeof detail.code !== \"string\" || typeof detail.message !== \"string\") return null;\n return detail as BridgeErrorDetail;\n}\n\nexport type RuntimeRequest = { command: string } & Record<string, unknown>;\n\n/**\n * How a world directory travels on a request that runs it (check, test, call):\n * in place, as `world`, when the bundled runtime runs on this machine — so the\n * `[dependencies]` paths beside it resolve and its handlers may run — and as\n * `files` when the platform's bridge answers, which takes a tree and runs no\n * authored code.\n */\nexport function worldPayload(dir: string): { world: string } | { files: WorldFile[] } {\n const abs = path.resolve(dir);\n if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) throw new CliError(`Not a directory: ${abs}`);\n return localRuntime() ? { world: abs } : { files: readWorldFiles(abs) };\n}\n\n/**\n * `POST /api/public/worlds/runtime` with the bridge request verbatim. A\n * rejection — whether the platform relays it with a 4xx or as a 200 with\n * `status: \"rejected\"` — becomes a BridgeRejected; anything else non-OK is a\n * plain CliError with the status and body excerpt.\n */\nexport async function runtime<T extends Record<string, unknown> = Record<string, unknown>>(\n creds: Credentials | null,\n request: RuntimeRequest,\n opts: { timeoutMs?: number } = {},\n): Promise<T> {\n // This machine first, when it can: the bundled runtime with a local\n // python3 is what the platform runs anyway, minus the round trip. A .yaml\n // conform spec needs PyYAML, which the vendored runtime does not carry.\n const local = localRuntime();\n const yamlSpec =\n request.command === \"conform\" &&\n Array.isArray(request.openapi) &&\n (request.openapi as { path?: string }[]).some((doc) => /\\.ya?ml$/i.test(doc.path ?? \"\"));\n if (local && !(yamlSpec && !localPythonHasYaml(local.python))) {\n const payload = await localBridge<Record<string, unknown>>(request, local, opts);\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n return payload as T;\n }\n if (!creds)\n throw new CliError(\n \"This needs the schema runtime (the CLI bundles it) or platform credentials (`gateway auth login`). \" +\n localRuntimeReason(),\n );\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? 180_000);\n const route = \"/api/public/worlds/runtime\";\n try {\n const res = await fetch(`${creds.host}${route}`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n },\n body: JSON.stringify(request),\n signal: controller.signal,\n });\n const text = await res.text();\n let payload: unknown = null;\n try {\n payload = text ? JSON.parse(text) : {};\n } catch {\n payload = null;\n }\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n if (!res.ok)\n throw new CliError(`POST ${route} (${request.command}) -> ${res.status}: ${text.slice(0, 600)}`, 1);\n if (payload === null) throw new CliError(`POST ${route} (${request.command}) returned non-JSON`, 1);\n return payload as T;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Basic-auth headers for the few non-runtime routes this track calls. */\nexport function authHeaders(creds: Credentials): Record<string, string> {\n return {\n accept: \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${creds.publicKey}:${creds.secretKey}`).toString(\"base64\"),\n };\n}\n\n/** Strip the `files` echo from a bridge report before printing it. */\nexport function withoutFiles<T extends Record<string, unknown>>(report: T): Omit<T, \"files\"> {\n const { files: _files, ...rest } = report;\n return rest;\n}\n\n/** JSON with sorted keys, the way the Python CLI prints bridge reports. */\nexport function sortedJson(value: unknown, indent = 2): string {\n const sort = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(sort);\n if (v && typeof v === \"object\") {\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(v as Record<string, unknown>).sort())\n out[key] = sort((v as Record<string, unknown>)[key]);\n return out;\n }\n return v;\n };\n return JSON.stringify(sort(value), null, indent);\n}\n","import { schemaFromSignature, type WorldToolkit } from \"./session\";\n\n/**\n * A BROWSER ON A WORLD'S UI — the computer-use half of a live session.\n *\n * A session answers on SURFACES. `tools` is always there (the world's own\n * operations over the rendezvous). An api-type world may also answer on\n * `api` (the service itself), `ui` (its dashboard, over the same state) and\n * `browser` — a headless Chromium the platform runs NEXT TO that UI, which\n * an agent drives through Playwright. This file is the TS client for the\n * last two, call for call with `gatewaysdk/world_browser.py`.\n *\n * const s = await openSession(\"payments-like\", \"refund-dispute\", {\n * surfaces: [\"ui\", \"browser\"],\n * });\n * await s.ready();\n * const b = await s.browser(); // hosted, next to the world\n * await b.goto(); // the UI's entry page\n * await b.click(\"text=Refund\");\n * const tools = computerUseToolkit(b); // the same actions as model tools\n * await b.close();\n *\n * Playwright is an OPTIONAL peer: nothing here imports it until a browser is\n * opened, so sessions that never touch a UI never load it.\n *\n * MODES. `hosted` connects to the session's own browser (a Playwright server\n * the pod exposes over an authenticated websocket). `local` launches Chromium\n * on this machine and points it at the UI — a laptop against a hosted twin,\n * or a test. `auto` prefers hosted. Asking for a mode the session cannot\n * serve throws `WorldSurfaceUnavailable`; there is no silent fallback to a\n * browser other than the one the episode is judged on.\n *\n * OBSERVABILITY. Every action a `WorldBrowser` takes (goto, click, type,\n * press, scroll, back) is reported to the platform as one event — what was\n * done, whether it worked, where the page ended up, and a JPEG of the screen\n * after — through a `BrowserActionRecorder`. Reporting is fire-and-forget\n * and never fails the action; the platform renders it as the session's\n * browser timeline. Text typed into secret-looking fields is redacted before\n * it leaves the process.\n */\n\nexport const SURFACE_KINDS = [\"tools\", \"api\", \"ui\", \"browser\"] as const;\nexport type WorldSurfaceKind = (typeof SURFACE_KINDS)[number];\n\nexport const DEFAULT_VIEWPORT = { width: 1280, height: 800 };\nconst SETTLE_TIMEOUT_MS = 5_000;\nconst SETTLE_QUIET_MS = 150;\nconst SETTLE_POLL_MS = 25;\n\nexport const EVENT_BATCH_SIZE = 10;\nexport const EVENT_FLUSH_INTERVAL_MS = 1_000;\nexport const EVENT_MAX_RETRIES = 3;\nconst EVENT_SCREENSHOT_QUALITY = 60;\nconst EVENT_MAX_STRING = 500;\n\nconst SECRET_KEY =\n /pass(word|wd)?|secret|token|api[-_]?key|authorization|cookie|(^|[-_ #.\\[\"'=])(otp|pin|cvv|ssn)([-_ \\]\"']|$)/i;\nconst SECRET_VALUE =\n /^((sk|pk|ghp|xox[abp])[-_][-_A-Za-z0-9]{8,}|AKIA[0-9A-Z]{12,}|Bearer [-_.A-Za-z0-9]{8,})/;\n\n/** The `surfaces` block of a session descriptor, as the platform sends it. */\nexport type SessionSurfaces = {\n tools: { kind: \"rendezvous\" };\n api?: {\n url: string;\n /** Per-session credential of a World Host session: send it as\n * `Authorization: Bearer <token>` (the header only; a token in the URL is\n * refused). Absent when the world\n * itself answers with its declared auth (a pod or a customer-hosted twin). */\n token?: string;\n };\n ui?: {\n url: string;\n entry: string;\n /** Same-origin prefix the UI proxies to the world API, e.g. `/__world-api`;\n * null when the UI only reaches the API server-side. */\n apiPath?: string | null;\n /** Per-session credential of a World Host UI. A browser navigation cannot\n * carry a header, so the first page load presents it once as `?token=`\n * and the host answers with an HttpOnly cookie. Absent for pod UIs. */\n token?: string;\n };\n browser?: {\n wsUrl: string;\n /** `cdp`: the platform's Chromium relay (any number of agents share one\n * browser, each in its own context). `playwright`: a `run-server` endpoint. */\n protocol: \"cdp\" | \"playwright\";\n viewport: { width: number; height: number };\n };\n};\n\nexport class WorldSurfaceUnavailable extends Error {\n constructor(\n readonly surface: WorldSurfaceKind,\n reason: string,\n ) {\n super(`World surface '${surface}' is unavailable: ${reason}`);\n }\n}\n\nexport function surfaceKinds(s: SessionSurfaces): WorldSurfaceKind[] {\n const kinds: WorldSurfaceKind[] = [\"tools\"];\n if (s.api) kinds.push(\"api\");\n if (s.ui) kinds.push(\"ui\");\n if (s.browser) kinds.push(\"browser\");\n return kinds;\n}\n\nconst UI_TOKEN_QUERY = \"token\";\n\n/** The URL of `path` on a UI surface, carrying the session token when the\n * surface has one. `path` may already have a query string; the token is\n * appended to it. */\nexport function uiUrl(\n ui: NonNullable<SessionSurfaces[\"ui\"]>,\n path: string,\n): string {\n const base = ui.url.replace(/\\/+$/, \"\");\n const rel = path.startsWith(\"/\") ? path : `/${path}`;\n if (!ui.token) return base + rel;\n const [beforeHash, hash] = splitHash(rel);\n const joiner = beforeHash.includes(\"?\") ? \"&\" : \"?\";\n const query = `${UI_TOKEN_QUERY}=${encodeURIComponent(ui.token)}`;\n return base + beforeHash + joiner + query + hash;\n}\n\nexport function uiEntryUrl(ui: NonNullable<SessionSurfaces[\"ui\"]>): string {\n return uiUrl(ui, ui.entry || \"/\");\n}\n\n/** `url` without its `token` query parameter: what may be logged or shown. */\nexport function withoutUiToken(url: string): string {\n const [beforeHash, hash] = splitHash(url);\n const q = beforeHash.indexOf(\"?\");\n if (q < 0) return url;\n const kept = beforeHash\n .slice(q + 1)\n .split(\"&\")\n .filter((pair) => pair !== \"\" && pair.split(\"=\")[0] !== UI_TOKEN_QUERY);\n return (\n beforeHash.slice(0, q) + (kept.length ? `?${kept.join(\"&\")}` : \"\") + hash\n );\n}\n\nfunction splitHash(url: string): [string, string] {\n const h = url.indexOf(\"#\");\n return h < 0 ? [url, \"\"] : [url.slice(0, h), url.slice(h)];\n}\n\n/** The slice of a Playwright `Page` this module drives. */\nexport type BrowserPage = {\n url(): string;\n goto(url: string, opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n click(selector: string): Promise<void>;\n fill(selector: string, value: string): Promise<void>;\n screenshot(opts?: {\n type?: \"png\" | \"jpeg\";\n quality?: number;\n fullPage?: boolean;\n }): Promise<Buffer>;\n innerText(selector: string): Promise<string>;\n content(): Promise<string>;\n goBack(opts?: { waitUntil?: \"load\" }): Promise<unknown>;\n waitForLoadState(state?: \"load\"): Promise<void>;\n waitForTimeout(ms: number): Promise<void>;\n on(\n event: \"request\" | \"requestfinished\" | \"requestfailed\",\n handler: (request: unknown) => void,\n ): unknown;\n title(): Promise<string>;\n keyboard: { press(key: string): Promise<void> };\n mouse: { wheel(dx: number, dy: number): Promise<void> };\n};\n\nexport type BrowserMode = \"auto\" | \"hosted\" | \"local\";\n\n// ── action events ────────────────────────────────────────────────────────────\n\n/** One browser action as the platform ingests it\n * (`POST /world-sessions/{id}/browser-events`). */\nexport type BrowserActionEvent = {\n agentId: string;\n seq: number;\n ts: string;\n action: string;\n args: Record<string, unknown>;\n ok: boolean;\n error: string | null;\n durationMs: number;\n url: string | null;\n title: string | null;\n mode: Exclude<BrowserMode, \"auto\">;\n viewport: { width: number; height: number };\n /** base64 JPEG of the screen after the action; null if it could not be taken. */\n screenshot: string | null;\n};\n\n/** What of an action's arguments may leave the process. Selectors, paths\n * and keys are what a reviewer needs; anything keyed like a credential, or\n * typed into a field whose selector names one, or shaped like a known key,\n * is replaced. Strings are capped, nested values dropped. */\nexport function redactActionArgs(\n action: string,\n args: Record<string, unknown>,\n): Record<string, unknown> {\n const secretField =\n action === \"browser_type\" && SECRET_KEY.test(String(args.selector ?? \"\"));\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(args)) {\n if (value === null || value === undefined) out[key] = null;\n else if (typeof value === \"boolean\" || typeof value === \"number\")\n out[key] = value;\n else if (typeof value === \"string\") {\n if (\n SECRET_KEY.test(key) ||\n SECRET_VALUE.test(value) ||\n (secretField && key === \"text\")\n )\n out[key] = \"[redacted]\";\n else\n out[key] =\n value.length <= EVENT_MAX_STRING\n ? value\n : value.slice(0, EVENT_MAX_STRING) + \"…\";\n } else out[key] = \"[omitted]\";\n }\n return out;\n}\n\n/**\n * Ships browser action events to the platform, off the action's hot path.\n *\n * `post` receives a batch of events (the request body's `events`). Events\n * are numbered here, so ordering survives batching and retries — the\n * platform dedups on `(agentId, seq)`. A batch that keeps failing is dropped\n * with a warning: telemetry must never stall or fail the agent.\n *\n * Numbering is durable across recorders: `nextSeq()` hands out a position\n * within this recorder, and the first send adds the base `resumeFrom`\n * reports — the platform's next free seq for this agent — so an agent id\n * reopened in a later process appends to its timeline instead of colliding\n * with (and being deduplicated against) what it already recorded. The base\n * is fixed once resolved, which keeps retries idempotent.\n */\nexport class BrowserActionRecorder {\n private seq = 0;\n private base: Promise<number> | null = null;\n private queue: BrowserActionEvent[] = [];\n private timer: ReturnType<typeof setTimeout> | null = null;\n private inflight: Promise<void> = Promise.resolve();\n sent = 0;\n dropped = 0;\n\n constructor(\n private readonly post: (events: BrowserActionEvent[]) => Promise<void>,\n readonly agentId: string,\n private readonly opts: {\n /** The platform's next free seq for `agentId`; 0 when not given. */\n resumeFrom?: () => Promise<number>;\n batchSize?: number;\n flushIntervalMs?: number;\n maxRetries?: number;\n sleep?: (ms: number) => Promise<void>;\n warn?: (message: string) => void;\n } = {},\n ) {}\n\n /** This recorder's next position; the wire seq is `resumeFrom() + this`. */\n nextSeq(): number {\n return this.seq++;\n }\n\n private resolveBase(): Promise<number> {\n if (this.base === null) {\n const resolve = this.opts.resumeFrom ?? (async () => 0);\n this.base = resolve().then((n) => {\n if (!Number.isInteger(n) || n < 0)\n throw new Error(\n `browser event base seq must be a non-negative integer, got ${String(n)}`,\n );\n return n;\n });\n // A failed lookup is retried with the batch, not remembered.\n this.base.catch(() => {\n this.base = null;\n });\n }\n return this.base;\n }\n\n record(event: BrowserActionEvent): void {\n this.queue.push(event);\n if (this.queue.length >= (this.opts.batchSize ?? EVENT_BATCH_SIZE)) {\n this.drain();\n } else if (this.timer === null) {\n this.timer = setTimeout(\n () => this.drain(),\n this.opts.flushIntervalMs ?? EVENT_FLUSH_INTERVAL_MS,\n );\n if (typeof this.timer === \"object\" && \"unref\" in this.timer)\n this.timer.unref();\n }\n }\n\n /** Resolve once everything recorded so far has been posted (or dropped). */\n async flush(): Promise<void> {\n this.drain();\n await this.inflight;\n }\n\n async close(): Promise<void> {\n await this.flush();\n }\n\n private drain(): void {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n if (this.queue.length === 0) return;\n const batch = this.queue;\n this.queue = [];\n this.inflight = this.inflight.then(() => this.send(batch));\n }\n\n private async send(batch: BrowserActionEvent[]): Promise<void> {\n const retries = this.opts.maxRetries ?? EVENT_MAX_RETRIES;\n const sleep =\n this.opts.sleep ??\n ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const base = await this.resolveBase();\n await this.post(\n base === 0 ? batch : batch.map((e) => ({ ...e, seq: base + e.seq })),\n );\n this.sent += batch.length;\n return;\n } catch (error) {\n if (attempt + 1 === retries) {\n this.dropped += batch.length;\n (this.opts.warn ?? console.warn)(\n `dropping ${batch.length} browser events after ${attempt + 1} attempts: ${String(error)}`,\n );\n return;\n }\n await sleep(500 * 2 ** attempt);\n }\n }\n }\n}\n\n/**\n * One Playwright page on the session's UI. Thin on purpose — `page` is the\n * real Playwright page for anything this wrapper does not cover.\n */\nexport class WorldBrowser {\n constructor(\n readonly page: BrowserPage,\n readonly ui: SessionSurfaces[\"ui\"] | undefined,\n readonly mode: Exclude<BrowserMode, \"auto\">,\n private readonly teardown: () => Promise<void>,\n readonly viewport: { width: number; height: number } = DEFAULT_VIEWPORT,\n readonly recorder: BrowserActionRecorder | null = null,\n ) {\n page.on(\"request\", () => {\n this.inflight += 1;\n this.lastNetwork = Date.now();\n });\n const done = () => {\n this.inflight = Math.max(0, this.inflight - 1);\n this.lastNetwork = Date.now();\n };\n page.on(\"requestfinished\", done);\n page.on(\"requestfailed\", done);\n }\n\n private inflight = 0;\n private lastNetwork = Date.now();\n\n get agentId(): string | null {\n return this.recorder?.agentId ?? null;\n }\n\n /** Run one action and report it: the event carries what was asked,\n * whether it worked, and the screen after — for failures too, so a\n * reviewer sees what the agent saw when the selector did not match. */\n private async act<T>(\n action: string,\n args: Record<string, unknown>,\n fn: () => Promise<T>,\n ): Promise<T> {\n const recorder = this.recorder;\n if (!recorder) return fn();\n const started = Date.now();\n let ok = true;\n let error: string | null = null;\n try {\n return await fn();\n } catch (err) {\n ok = false;\n error = (\n err instanceof Error ? `${err.name}: ${err.message}` : String(err)\n ).slice(0, 4000);\n throw err;\n } finally {\n recorder.record({\n agentId: recorder.agentId,\n seq: recorder.nextSeq(),\n ts: new Date().toISOString(),\n action,\n args: redactActionArgs(action, args),\n ok,\n error,\n durationMs: Date.now() - started,\n mode: this.mode,\n viewport: { ...this.viewport },\n ...(await this.observeForEvent()),\n });\n }\n }\n\n private async observeForEvent(): Promise<\n Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\">\n > {\n const out: Pick<BrowserActionEvent, \"url\" | \"title\" | \"screenshot\"> = {\n url: null,\n title: null,\n screenshot: null,\n };\n try {\n out.url = this.page.url();\n out.title = await this.page.title();\n const jpeg = await this.page.screenshot({\n type: \"jpeg\",\n quality: EVENT_SCREENSHOT_QUALITY,\n });\n out.screenshot = jpeg.toString(\"base64\");\n } catch {\n // a closed page still gets its event\n }\n return out;\n }\n\n /** Open a UI path (`/customers`), a full URL, or — with no argument — the\n * UI's declared entry page. */\n async goto(pathOrUrl?: string): Promise<string> {\n let target: string;\n if (pathOrUrl === undefined) {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"this session has no UI to navigate to\",\n );\n target = uiEntryUrl(this.ui);\n } else if (/^https?:\\/\\//.test(pathOrUrl)) {\n target = pathOrUrl;\n } else {\n if (!this.ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"relative paths need a UI surface\",\n );\n target = uiUrl(this.ui, pathOrUrl);\n }\n return this.act(\n \"browser_goto\",\n { path: pathOrUrl ?? null, url: withoutUiToken(target) },\n async () => {\n await this.page.goto(target, { waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n },\n );\n }\n\n async back(): Promise<string> {\n return this.act(\"browser_back\", {}, async () => {\n await this.page.goBack({ waitUntil: \"load\" });\n await this.settle();\n return this.page.url();\n });\n }\n\n /** Wait for the page to finish reacting to an action. `load` alone is not\n * enough for client-rendered UIs (React et al.): a click returns before the\n * fetch that re-renders the page, so an agent would read stale text.\n * Playwright's `networkidle` is per navigation and resolves at once after\n * the first one, so this tracks requests itself: done when nothing is in\n * flight and the network has been quiet for `SETTLE_QUIET_MS`, bounded so\n * long-polling UIs cannot hang us. */\n private async settle(): Promise<void> {\n await this.page.waitForLoadState(\"load\");\n const deadline = Date.now() + SETTLE_TIMEOUT_MS;\n while (Date.now() < deadline) {\n const quiet = Date.now() - this.lastNetwork >= SETTLE_QUIET_MS;\n if (this.inflight === 0 && quiet) return;\n await this.page.waitForTimeout(SETTLE_POLL_MS);\n }\n }\n\n async click(selector: string): Promise<void> {\n await this.act(\"browser_click\", { selector }, async () => {\n await this.page.click(selector);\n await this.settle();\n });\n }\n\n async type(selector: string, text: string): Promise<void> {\n await this.act(\"browser_type\", { selector, text }, () =>\n this.page.fill(selector, text),\n );\n }\n\n async press(key: string): Promise<void> {\n await this.act(\"browser_press\", { key }, async () => {\n await this.page.keyboard.press(key);\n await this.settle();\n });\n }\n\n async scroll(dy: number): Promise<void> {\n await this.act(\"browser_scroll\", { dy }, () =>\n this.page.mouse.wheel(0, dy),\n );\n }\n\n async screenshot(fullPage = false): Promise<Buffer> {\n return this.page.screenshot({ type: \"png\", fullPage });\n }\n\n async screenshotBase64(fullPage = false): Promise<string> {\n return (await this.screenshot(fullPage)).toString(\"base64\");\n }\n\n async text(selector = \"body\"): Promise<string> {\n return this.page.innerText(selector);\n }\n\n async html(): Promise<string> {\n return this.page.content();\n }\n\n get url(): string {\n return this.page.url();\n }\n\n async title(): Promise<string> {\n return this.page.title();\n }\n\n async close(): Promise<void> {\n try {\n await this.teardown();\n } finally {\n await this.recorder?.close();\n }\n }\n}\n\n/** The Playwright entry points this module needs, so tests can inject a fake. */\nexport type PlaywrightLike = {\n chromium: {\n connect(wsEndpoint: string): Promise<PlaywrightBrowserLike>;\n connectOverCDP(endpointURL: string): Promise<PlaywrightBrowserLike>;\n launch(opts?: { headless?: boolean }): Promise<PlaywrightBrowserLike>;\n };\n};\n\nexport type PlaywrightBrowserLike = {\n newContext(opts?: {\n viewport?: { width: number; height: number };\n }): Promise<{ newPage(): Promise<BrowserPage>; close(): Promise<void> }>;\n close(): Promise<void>;\n};\n\nasync function loadPlaywright(): Promise<PlaywrightLike> {\n try {\n // A string specifier keeps bundlers from resolving the optional peer.\n const name = \"playwright\";\n return (await import(name)) as PlaywrightLike;\n } catch (error) {\n throw new Error(\n \"Driving a world UI needs Playwright: npm install playwright \" +\n \"(and `npx playwright install chromium` for local mode).\",\n { cause: error },\n );\n }\n}\n\nexport function resolveBrowserMode(\n surfaces: SessionSurfaces,\n mode: BrowserMode,\n): Exclude<BrowserMode, \"auto\"> {\n if (!surfaces.ui && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n const resolved =\n mode === \"auto\" ? (surfaces.browser ? \"hosted\" : \"local\") : mode;\n if (resolved === \"hosted\" && !surfaces.browser)\n throw new WorldSurfaceUnavailable(\n \"browser\",\n \"open the session with surfaces: ['browser'] to get a hosted browser\",\n );\n return resolved;\n}\n\n/** Open a browser on the session's UI in `hosted`, `local` or `auto` mode. */\nexport async function openBrowser(\n surfaces: SessionSurfaces,\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n recorder?: BrowserActionRecorder | null;\n } = {},\n): Promise<WorldBrowser> {\n const mode = resolveBrowserMode(surfaces, opts.mode ?? \"auto\");\n const pw = opts.playwright ?? (await loadPlaywright());\n const viewport = surfaces.browser?.viewport ?? DEFAULT_VIEWPORT;\n const browser =\n mode === \"hosted\"\n ? surfaces.browser!.protocol === \"playwright\"\n ? await pw.chromium.connect(surfaces.browser!.wsUrl)\n : await pw.chromium.connectOverCDP(surfaces.browser!.wsUrl)\n : await pw.chromium.launch({ headless: opts.headless ?? true });\n const context = await browser.newContext({ viewport });\n const page = await context.newPage();\n return new WorldBrowser(\n page,\n surfaces.ui,\n mode,\n async () => {\n await context.close();\n await browser.close();\n },\n viewport,\n opts.recorder ?? null,\n );\n}\n\n// ── computer-use tools ───────────────────────────────────────────────────────\n\nexport const COMPUTER_USE_SPECS = [\n {\n name: \"browser_goto\",\n signature: \"browser_goto(path=None)\",\n doc: \"Open a page of the world's UI. `path` is a UI path like /customers, a full URL, or omitted for the entry page. Returns the URL and page text.\",\n },\n {\n name: \"browser_click\",\n signature: \"browser_click(selector)\",\n doc: \"Click an element by Playwright selector (CSS, `text=Refund`, `role=button[name=Save]`). Returns the page text after the click.\",\n },\n {\n name: \"browser_type\",\n signature: \"browser_type(selector, text)\",\n doc: \"Replace the value of an input/textarea found by selector with `text`.\",\n },\n {\n name: \"browser_press\",\n signature: \"browser_press(key)\",\n doc: \"Press a key (Enter, Tab, Escape, ArrowDown, ...). Returns the page text after.\",\n },\n {\n name: \"browser_scroll\",\n signature: \"browser_scroll(dy=600)\",\n doc: \"Scroll the page vertically by `dy` pixels (negative scrolls up).\",\n },\n {\n name: \"browser_screenshot\",\n signature: \"browser_screenshot(full_page=False)\",\n doc: \"Take a PNG screenshot; returns {image_base64, url}.\",\n },\n {\n name: \"browser_read\",\n signature: \"browser_read(selector='body')\",\n doc: \"Return the visible text of an element (default: whole page) plus the URL and title.\",\n },\n {\n name: \"browser_back\",\n signature: \"browser_back()\",\n doc: \"Go back one page in history.\",\n },\n] as const;\n\nconst str = (v: unknown, fallback: string): string =>\n typeof v === \"string\" && v.length > 0 ? v : fallback;\n\n/**\n * The browser as model tools, in the same `WorldToolkit` shape the world's\n * own tools come in — so an agent loop that already dispatches\n * `toolkit().impls` merges `computerUseToolkit(b).impls` and gains a screen\n * without a second dispatch path.\n */\nexport function computerUseToolkit(\n browser: WorldBrowser,\n opts: { maxText?: number } = {},\n): WorldToolkit {\n const maxText = opts.maxText ?? 20_000;\n const observe = async (selector = \"body\") => {\n const text = await browser.text(selector);\n return {\n url: browser.url,\n title: await browser.title(),\n text: text.slice(0, maxText),\n truncated: text.length > maxText,\n };\n };\n\n const impls: WorldToolkit[\"impls\"] = {\n browser_goto: async (a) => {\n await browser.goto(typeof a.path === \"string\" ? a.path : undefined);\n return observe();\n },\n browser_click: async (a) => {\n await browser.click(str(a.selector, \"\"));\n return observe();\n },\n browser_type: async (a) => {\n await browser.type(str(a.selector, \"\"), String(a.text ?? \"\"));\n return { ok: true, url: browser.url };\n },\n browser_press: async (a) => {\n await browser.press(str(a.key, \"Enter\"));\n return observe();\n },\n browser_scroll: async (a) => {\n await browser.scroll(typeof a.dy === \"number\" ? a.dy : 600);\n return { ok: true, url: browser.url };\n },\n browser_screenshot: async (a) => ({\n image_base64: await browser.screenshotBase64(a.full_page === true),\n url: browser.url,\n }),\n browser_read: async (a) => observe(str(a.selector, \"body\")),\n browser_back: async () => {\n await browser.back();\n return observe();\n },\n };\n\n const specs = COMPUTER_USE_SPECS.map((s) => ({ ...s }));\n return {\n schemas: specs.map((spec) => schemaFromSignature(spec)),\n impls,\n specs,\n };\n}\n","import { randomUUID } from \"node:crypto\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport {\n BrowserActionRecorder,\n SURFACE_KINDS,\n WorldSurfaceUnavailable,\n computerUseToolkit,\n openBrowser,\n uiEntryUrl,\n type BrowserActionEvent,\n type BrowserMode,\n type PlaywrightLike,\n type SessionSurfaces,\n type WorldBrowser,\n type WorldSurfaceKind,\n} from \"./browser\";\nimport type { WorldTaskSummary } from \"./tasks\";\n\n/**\n * LIVE WORLD SESSIONS from TypeScript: your agent, the platform's container.\n *\n * The other two ways of running a world each give up something. Pulling the\n * bundle and executing it locally tests your agent against a COPY — your\n * python, your sqlite, your machine's idea of the environment. Dispatching a\n * hosted run gives you the real container but runs the platform's agent\n * inside it, so your agent never touches the world.\n *\n * A session is both: the platform boots the task's container and holds it\n * warm, and every `call()` here executes inside THAT container. Your agent\n * stays where it is — this file is just the wire.\n *\n * const world = await openWorld(\"revenue-ops-sim@main\");\n * const session = await openSession(world.slug, { task: \"revops-mara-dedupe-contacts\" });\n * await session.ready(); // wait for the container\n * await session.call(\"crm_search\", { entity: \"deals\" });\n * const { reward, rewards } = await session.grade();\n * await session.close({ keepWarm: true }); // hand it back to the pool\n *\n * The task can also be YOURS rather than the bundle's — an instruction, the\n * rows the session starts with and how it is graded, for one end user:\n *\n * const session = await openSession(\"acme-billing@main\", {\n * task: {\n * instruction: \"Mark invoice INV-7 as paid.\",\n * seed: { rows: { invoices: [{ id: \"INV-7\", status: \"open\" }] } },\n * grader: { kind: \"assertions\", checks: [\n * { entity: \"invoices\", where: { id: \"INV-7\", status: \"paid\" } },\n * ] },\n * metadata: { externalUserId: \"u_42\" },\n * },\n * surfaces: [\"api\"],\n * });\n *\n * Every call is a row on the platform before it is an effect in a container,\n * so the episode is on the record — and the platform traces the session\n * itself, which is why these sessions show up under Sessions without the\n * caller instrumenting anything.\n */\n\nexport type WorldToolSpec = {\n name: string;\n /** The world's own signature, e.g. `crm_search(q=None, entity=\"deals\")`. */\n signature: string;\n doc: string | null;\n inputSchema?: Record<string, unknown>;\n};\n\n/** What a model needs to call a world: the schemas to advertise, and the\n * implementations that run them in the container. */\nexport type WorldToolkit = {\n /** OpenAI-shaped tool definitions, derived from the world's signatures. */\n schemas: {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n }[];\n /** name -> implementation, each one a call into THIS session. */\n impls: Record<string, (args: Record<string, unknown>) => Promise<unknown>>;\n specs: WorldToolSpec[];\n};\n\n// ── tasks ────────────────────────────────────────────────────────────────────\n\n/** A JSON scalar: what `where` filters and field predicates compare against. */\nexport type WorldTaskScalar = string | number | boolean | null;\n\n/** The rows a task starts the session with — the `seed()` contract, applied\n * by the host right after it clones the version's snapshot. `append`\n * (default) upserts by primary key onto the base data; `replace` makes the\n * named entities hold exactly these rows. */\nexport type WorldTaskSeed = {\n mode?: \"append\" | \"replace\";\n /** Redaction on the way in: `off` (default) stores the rows as given,\n * `apply` runs the world's `[redact]` policy over them first, `refuse`\n * rejects a row carrying plaintext in a redacted field. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n rows: Record<string, Record<string, unknown>[]>;\n};\n\nexport type WorldTaskFieldOp =\n \"eq\" | \"neq\" | \"in\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"contains\";\n\n/**\n * One declarative check over the session's final rows. `where` selects rows\n * of `entity` by equality (dotted paths reach into nested objects); the\n * assertion says what must hold of the selection:\n *\n * exists (default) / absent at least one row / none\n * count `count` bound on how many\n * all / any `field op value` on every / some selected row\n *\n * A check's `id` names its entry in `rewards`; the task's reward is the\n * weighted share of checks that passed.\n */\nexport type WorldTaskCheck = {\n id?: string;\n weight?: number;\n entity: string;\n where?: Record<string, WorldTaskScalar>;\n assert?: \"exists\" | \"absent\" | \"count\" | \"all\" | \"any\";\n count?: { eq?: number; gte?: number; lte?: number };\n field?: string;\n op?: WorldTaskFieldOp;\n value?: WorldTaskScalar | WorldTaskScalar[];\n};\n\n/** One thing a rubric judge scores in [0, 1]; `id` names its entry in\n * `rewards`, `weight` (default 1) its share of the task's reward. */\nexport type WorldTaskRubricCriterion = {\n id: string;\n description: string;\n weight?: number;\n};\n\n/** A rubric is prose: what a good outcome looks like. The platform (never the\n * host) has a model read the session's final state and its call log against\n * it; the project's default evaluation model judges unless `model` pins one.\n * `grade()` then resolves asynchronously — `pending: true` first, the reward\n * once the judge has answered. */\nexport type WorldTaskRubricGrader = {\n kind: \"rubric\";\n rubric: string;\n criteria?: WorldTaskRubricCriterion[];\n model?: { provider: string; model: string };\n};\n\n/** How a task is graded: checks the host evaluates in-process, a `verify.py`\n * body (state JSON on stdin, last stdout line `{reward, ...}`) run through the\n * host's confined verifier, or a rubric judged by a model on the platform. */\nexport type WorldTaskGrader =\n | { kind: \"assertions\"; checks: WorldTaskCheck[] }\n | { kind: \"python\"; source: string; timeoutSeconds?: number }\n | WorldTaskRubricGrader;\n\n/** A task supplied at open, for one session, instead of a bundled scenario.\n * `instruction` is what the agent is told; without `seed` the session starts\n * on the version's base data, without `grader` `grade()` answers\n * `reward: null`; `tools` is the allow-list of the version's tools the agent\n * may call in this session (unset: all of them; a call outside it is refused\n * and logged); `metadata` is yours (an end-user id, a ticket) and is echoed\n * on the session, never read. Limits: shared/domain/worldTasks.ts. */\nexport type WorldTaskSpec = {\n name?: string;\n instruction: string;\n seed?: WorldTaskSeed;\n grader?: WorldTaskGrader;\n tools?: string[];\n metadata?: Record<string, unknown>;\n};\n\n/** A stored task of the project (see worlds/tasks.ts), opened by id; the\n * session runs a copy of one version's spec — the current one by default. */\nexport type WorldTaskIdRef = { id: string; version?: number };\n\n/** What `openSession` takes as the task: a bundled scenario's name, a\n * stored task's `{ id, version? }`, or an inline spec. */\nexport type WorldTaskRef = string | WorldTaskIdRef | WorldTaskSpec;\n\n/** What a session's task is, on every session response. `hash` is the\n * content hash of the spec (inline or stored) — what warm reuse matches on;\n * `id`/`version` name the stored task the session was opened on. */\nexport type WorldSessionTask = {\n source: \"bundled\" | \"inline\" | \"stored\";\n name: string | null;\n hash: string | null;\n id?: string | null;\n version?: number | null;\n metadata: Record<string, unknown>;\n};\n\nexport const isTaskIdRef = (task: WorldTaskRef): task is WorldTaskIdRef =>\n typeof task === \"object\" && task !== null && \"id\" in task;\n\nexport const isTaskSpec = (task: WorldTaskRef): task is WorldTaskSpec =>\n typeof task === \"object\" && task !== null && \"instruction\" in task;\n\n/** The label a task goes by in results: its name, `inline:<hash>` for an\n * unnamed inline task once the platform has hashed it, or the stored task's\n * name (its id until the platform has answered). */\nexport const taskLabel = (\n task: WorldTaskRef,\n info?: WorldSessionTask | null,\n): string => {\n if (typeof task === \"string\") return task;\n if (isTaskIdRef(task)) return info?.name ?? task.id;\n if (task.name) return task.name;\n return info?.hash ? `inline:${info.hash.slice(0, 12)}` : \"inline\";\n};\n\nexport type SeedResult = {\n seeded: number;\n mode: \"append\" | \"replace\";\n entity_counts: Record<string, number>;\n};\n\n/** One row of the session's call log. */\nexport type WorldSessionCall = {\n seq: number;\n kind: string;\n tool: string | null;\n args: unknown;\n result: unknown;\n error: string | null;\n completedAt: string | null;\n};\n\nexport type WorldSessionState = {\n sessionId: string;\n state: string;\n ready: boolean;\n versionId: string;\n contentHash: string;\n taskName: string | null;\n /** Where the task came from and what it is; absent on platforms that\n * predate session tasks, in which case it is derived from `taskName`. */\n task?: WorldSessionTask;\n /** The task's objective — present when the session was opened (not on a\n * bare status read), so a client never needs the bundle on disk. */\n instruction?: string | null;\n /** The tools this task serves. */\n tools?: WorldToolSpec[];\n /** Where the session answers besides `tools` — see worlds/browser.ts. */\n surfaces?: SessionSurfaces;\n /** Notices about the world's shape (an api bundle is a deprecated layout;\n * schema worlds are the supported shape), with what to run instead. Empty\n * for a schema world; absent on platforms that predate the notice. */\n deprecations?: WorldDeprecation[];\n};\n\n/** One notice a worlds-path answer carries: a deprecated shape or layout\n * and the command that replaces it. A retired shape is refused instead,\n * with the stable message prefix `world_kind_retired:`. */\nexport type WorldDeprecation = {\n code: string;\n message: string;\n replacement: string;\n};\n\nexport type GradeResult = {\n reward: number | null;\n rewards: Record<string, number>;\n raw: unknown;\n};\n\n/** How long `ready()` waits, and how often it asks. */\nconst READY_TIMEOUT_MS = 10 * 60_000;\nconst READY_POLL_MS = 2_000;\n/** How long one call may take end to end (container claim + execution). */\nconst CALL_TIMEOUT_MS = 3 * 60_000;\nconst CALL_POLL_MS = 400;\n/** How long a grade the platform's judge finalizes may take: the model's own\n * timeout and retries, plus the worker's queue backoff. Polled slowly. */\nconst JUDGED_GRADE_TIMEOUT_MS = 15 * 60_000;\nconst JUDGED_GRADE_POLL_MS = 2_000;\nconst EXPORT_PAGE = 500;\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nconst modelToolName = (name: string): string =>\n name.replace(/[^A-Za-z0-9_-]/g, \"_\").slice(0, 64) || \"tool\";\n\n/**\n * Turn a world's Python signature into a JSON schema the model can call.\n *\n * `crm_update_deal(id, stage=None, owner=None, amount=None)` becomes an\n * object with `id` required and the rest optional. Types are read from the\n * DEFAULTS the world declares — a numeric default means a number, a boolean\n * default a boolean — because that is the only type information a signature\n * actually carries. Everything else is a string, which is what a tool CLI\n * receives anyway.\n */\nexport function schemaFromSignature(spec: WorldToolSpec): {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: Record<string, unknown>;\n };\n} {\n if (spec.inputSchema)\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: spec.inputSchema,\n },\n };\n const inside = /\\(([\\s\\S]*)\\)\\s*$/.exec(spec.signature.trim())?.[1] ?? \"\";\n const properties: Record<string, unknown> = {};\n const required: string[] = [];\n // Split on top-level commas only: a default like `{\"a\": 1}` has its own.\n const params: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of inside) {\n if (\"([{\".includes(ch)) depth++;\n if (\")]}\".includes(ch)) depth--;\n if (ch === \",\" && depth === 0) {\n params.push(current);\n current = \"\";\n } else current += ch;\n }\n if (current.trim()) params.push(current);\n\n for (const raw of params) {\n const param = raw.trim();\n if (!param || param.startsWith(\"*\") || param === \"self\") continue;\n const eq = param.indexOf(\"=\");\n const name = (eq === -1 ? param : param.slice(0, eq)).split(\":\")[0].trim();\n if (!name) continue;\n if (eq === -1) {\n properties[name] = { type: \"string\" };\n required.push(name);\n continue;\n }\n const value = param.slice(eq + 1).trim();\n if (/^-?\\d+(\\.\\d+)?$/.test(value)) properties[name] = { type: \"number\" };\n else if (value === \"True\" || value === \"False\")\n properties[name] = { type: \"boolean\" };\n else properties[name] = { type: \"string\" };\n }\n return {\n type: \"function\",\n function: {\n name: modelToolName(spec.name),\n description: spec.doc ?? spec.name,\n parameters: { type: \"object\", properties, required },\n },\n };\n}\n\nexport class WorldSessionTimeout extends Error {}\nexport class WorldSessionCallError extends Error {}\n\nexport class WorldSession {\n constructor(\n readonly sessionId: string,\n private current: WorldSessionState,\n private readonly options: WorldsClientOptions,\n ) {}\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). Same as `taskName`. */\n get task(): string | null {\n return this.current.taskName;\n }\n\n /** The task's display name: a bundled scenario's, or the inline spec's\n * `name` (null when the spec was unnamed). */\n get taskName(): string | null {\n return this.current.taskName;\n }\n\n /** The platform's notices about the world this session runs on (empty\n * for a schema world). Printed by the CLI on stderr at open. */\n get deprecations(): WorldDeprecation[] {\n return this.current.deprecations ?? [];\n }\n\n /** The task this session runs: bundled scenario, stored task or inline\n * spec, its name, hash and the caller's metadata. */\n get taskInfo(): WorldSessionTask {\n return (\n this.current.task ?? {\n source: \"bundled\",\n name: this.current.taskName,\n hash: null,\n metadata: {},\n }\n );\n }\n\n /** What this task asks for — the bundle's instruction.md, or the inline\n * spec's `instruction`. */\n get instruction(): string | null {\n return this.current.instruction ?? null;\n }\n\n get versionId(): string {\n return this.current.versionId;\n }\n\n /** Whether the session answered ready as of the last state read (the open,\n * a `status()`, or the poll inside `ready()`); no request is made. */\n get isReady(): boolean {\n return this.current.ready;\n }\n\n /** `api` / `ui` / `browser` are present exactly when the world declares\n * them AND the session was opened asking for them. */\n async surfaces(): Promise<SessionSurfaces> {\n if (!this.current.surfaces) await this.status();\n return this.current.surfaces ?? { tools: { kind: \"rendezvous\" } };\n }\n\n /** Base URL of the world's own HTTP API for this session. */\n async api(): Promise<string> {\n const { api } = await this.surfaces();\n if (!api)\n throw new WorldSurfaceUnavailable(\n \"api\",\n \"open the session with surfaces: ['api'] on an api-type world\",\n );\n return api.url;\n }\n\n /** Headers every request to `api()` needs. A World Host session gates its\n * api surface on a per-session token; a pod or hosted twin answers with the\n * world's own declared auth and this is `{}`. */\n async apiHeaders(): Promise<Record<string, string>> {\n const { api } = await this.surfaces();\n return api?.token ? { Authorization: `Bearer ${api.token}` } : {};\n }\n\n /** URL of the world's UI entry page for this session. */\n async ui(): Promise<string> {\n const { ui } = await this.surfaces();\n if (!ui)\n throw new WorldSurfaceUnavailable(\n \"ui\",\n \"open the session with surfaces: ['ui'] on a world that declares [ui]\",\n );\n return uiEntryUrl(ui);\n }\n\n /** A Playwright browser on this session's UI: `hosted` drives the one the\n * platform runs next to the world, `local` launches one here, `auto`\n * prefers hosted. Call `close()` when done.\n *\n * Every action is reported to the platform under `agentId` (default:\n * `GATEWAY_AGENT_ID` or a fresh `agent-<hex>`) so the session page shows\n * this agent's own timeline — several agents may share one session and\n * one hosted browser. `record: false` opts out. */\n async browser(\n opts: {\n mode?: BrowserMode;\n headless?: boolean;\n playwright?: PlaywrightLike;\n agentId?: string;\n record?: boolean;\n } = {},\n ): Promise<WorldBrowser> {\n const { agentId, record = true, ...rest } = opts;\n return openBrowser(await this.surfaces(), {\n ...rest,\n recorder: record ? this.browserRecorder(agentId) : null,\n });\n }\n\n /** The reporter `browser()` uses; exposed for a page you drive yourself. */\n browserRecorder(agentId?: string): BrowserActionRecorder {\n const path = `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/browser-events`;\n const id =\n agentId ??\n process.env.GATEWAY_AGENT_ID ??\n `agent-${randomUUID().replace(/-/g, \"\").slice(0, 8)}`;\n return new BrowserActionRecorder(\n async (events: BrowserActionEvent[]) => {\n await apiRequest(this.options, \"POST\", path, { events });\n },\n id,\n {\n // Continue this agent's timeline where the platform has it, so the\n // same id reopened later never re-numbers from zero.\n resumeFrom: async () => {\n const summary = await apiRequest<{\n agents: { agentId: string; nextSeq: number }[];\n }>(this.options, \"GET\", path);\n return summary.agents.find((a) => a.agentId === id)?.nextSeq ?? 0;\n },\n },\n );\n }\n\n /** Browser actions as model tools, in the same shape as `toolkit()`. */\n computerUseTools(browser: WorldBrowser): WorldToolkit {\n return computerUseToolkit(browser);\n }\n\n /** The session's latest platform state (one request, no waiting). */\n async status(): Promise<WorldSessionState> {\n const fresh = await apiRequest<WorldSessionState>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n );\n // A status read does not carry the objective; keep the one we opened with.\n this.current = {\n instruction: this.current.instruction,\n tools: this.current.tools,\n surfaces: this.current.surfaces,\n task: this.current.task,\n ...fresh,\n };\n return this.current;\n }\n\n /**\n * Wait until the container is warm — meaning the process inside it has\n * asked the platform for work, not merely that a job was accepted.\n */\n async ready(opts: { timeoutMs?: number } = {}): Promise<WorldSessionState> {\n const deadline = Date.now() + (opts.timeoutMs ?? READY_TIMEOUT_MS);\n for (;;) {\n const state = await this.status();\n if (state.ready) return state;\n if (state.state === \"FAILED\" || state.state === \"STOPPED\")\n throw new WorldSessionCallError(\n `World session ${state.state.toLowerCase()} before it was ready.`,\n );\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n `World session still ${state.state} after ${Math.round((opts.timeoutMs ?? READY_TIMEOUT_MS) / 1000)}s.`,\n );\n await sleep(READY_POLL_MS);\n }\n }\n\n /** Enqueue one interaction and wait for the container's answer. */\n private async exchange(\n body: {\n kind?: \"call\" | \"grade\" | \"reset\" | \"state\" | \"seed\" | \"close\";\n tool?: string;\n args?: unknown;\n },\n timeoutMs?: number,\n ): Promise<unknown> {\n const enqueued = await apiRequest<{\n callId: string;\n seq: number;\n /** The platform's worker finalizes this call (a rubric grade). */\n pending?: boolean;\n }>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls`,\n body,\n );\n const { callId } = enqueued;\n const judged = enqueued.pending === true;\n const budgetMs =\n timeoutMs ?? (judged ? JUDGED_GRADE_TIMEOUT_MS : CALL_TIMEOUT_MS);\n const pollMs = judged ? JUDGED_GRADE_POLL_MS : CALL_POLL_MS;\n const deadline = Date.now() + budgetMs;\n for (;;) {\n const call = await apiRequest<{\n done: boolean;\n state: string;\n result: unknown;\n error: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls/${encodeURIComponent(callId)}`,\n );\n if (call.done) {\n if (call.error) throw new WorldSessionCallError(call.error);\n return call.result;\n }\n if (Date.now() > deadline)\n throw new WorldSessionTimeout(\n judged\n ? `Grade ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the judge has not answered; the platform finalizes the call on its own, read it back with export().`\n : `Call ${callId} still ${call.state} after ${Math.round(budgetMs / 1000)}s — the container may have died.`,\n );\n await sleep(pollMs);\n }\n }\n\n /**\n * Run one of the world's tools INSIDE the container. The arguments and the\n * result are the world's own contract — this layer neither validates nor\n * reshapes them, so a tool error reads exactly as it would in a hosted run.\n */\n async call(\n tool: string,\n args: Record<string, unknown> = {},\n opts: { timeoutMs?: number } = {},\n ): Promise<unknown> {\n return this.exchange({ kind: \"call\", tool, args }, opts.timeoutMs);\n }\n\n /**\n * THE WORLD'S TOOLS, READY TO HAND TO A MODEL. Schemas come from the\n * world's own signatures and implementations call into this session, so a\n * caller never writes — and never has to re-sync — a tool map of their own:\n *\n * const { schemas, impls } = await session.toolkit();\n * await runMyAgent(impls, schemas, session.instruction);\n *\n * A tool added to the world shows up here on the next run; a tool renamed\n * in the world renames here too, instead of failing at call time against a\n * hand-written map that still remembers the old name.\n */\n async toolkit(): Promise<WorldToolkit> {\n let specs = this.current.tools;\n if (!specs) specs = (await this.status()).tools ?? [];\n const impls: WorldToolkit[\"impls\"] = Object.create(null);\n for (const spec of specs) {\n const alias = modelToolName(spec.name);\n if (Object.hasOwn(impls, alias))\n throw new WorldSessionCallError(`Model tool name collision: ${alias}`);\n impls[alias] = (args: Record<string, unknown> = {}) =>\n this.call(spec.name, args);\n }\n return { schemas: specs.map(schemaFromSignature), impls, specs };\n }\n\n /** Run the task's grader against the container's END STATE. Graders answer\n * in one of two shapes: the scalar with named rewards beside it\n * (`{reward, check_a, check_b}`, a task's own `grade.py`), or the named\n * rewards nested under `rewards` (the api, mock-tools and World Host\n * runners). Both land in `rewards`.\n *\n * A rubric grade is finalized by the platform's judge, not the container:\n * the platform answers the enqueue with `pending: true`, and this waits on\n * the judge's budget (15 min) instead of a call's. `timeoutMs` overrides\n * either. */\n async grade(opts: { timeoutMs?: number } = {}): Promise<GradeResult> {\n const raw = (await this.exchange(\n { kind: \"grade\" },\n opts.timeoutMs,\n )) as Record<string, unknown> | null;\n const record = raw && typeof raw === \"object\" ? raw : {};\n const rewards: Record<string, number> = {};\n const nested = record.rewards;\n if (nested && typeof nested === \"object\") {\n for (const [key, value] of Object.entries(nested)) {\n if (typeof value === \"number\") rewards[key] = value;\n }\n }\n for (const [key, value] of Object.entries(record)) {\n if (key !== \"reward\" && typeof value === \"number\") rewards[key] = value;\n }\n return {\n reward: typeof record.reward === \"number\" ? record.reward : null,\n rewards,\n raw,\n };\n }\n\n /**\n * Put rows into the LIVE world through its contract, in one batch:\n * `append` (default) upserts by primary key, `replace` makes the named\n * entities hold exactly these rows. Atomic — a refused row leaves the\n * session unchanged and the error names the entity, row and field.\n */\n async seed(\n rows: Record<string, Record<string, unknown>[]>,\n opts: {\n mode?: \"append\" | \"replace\";\n /** `apply` runs the world's `[redact]` policy over the rows first;\n * `refuse` rejects plaintext in a redacted field; default `off`. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n timeoutMs?: number;\n } = {},\n ): Promise<SeedResult> {\n const mode = opts.mode ?? \"append\";\n const redact = opts.redact ?? \"off\";\n return (await this.exchange(\n {\n kind: \"seed\",\n args: { mode, rows, ...(redact !== \"off\" ? { redact } : {}) },\n },\n opts.timeoutMs,\n )) as SeedResult;\n }\n\n /** Every entity's rows as the world holds them now — the same dump a\n * grader reads. The shape is the world runtime's: a schema world answers\n * `{<entity>: {<key>: row}, snapshot}`, a mock-tools world\n * `{entities: {<entity>: [row]}}`. */\n async state(opts: { timeoutMs?: number } = {}): Promise<unknown> {\n return this.exchange({ kind: \"state\" }, opts.timeoutMs);\n }\n\n /** Back to the opening state: the version's data plus the bundled\n * scenario's or the inline task's seed. Rows written since are gone; the\n * call log stays. */\n async reset(opts: { timeoutMs?: number } = {}): Promise<void> {\n await this.exchange({ kind: \"reset\" }, opts.timeoutMs);\n }\n\n /** The session's call log, oldest first: every tool call, seed, reset,\n * grade with its result — the record of the episode. */\n async export(): Promise<WorldSessionCall[]> {\n const calls: WorldSessionCall[] = [];\n let cursor: string | undefined;\n do {\n const params = new URLSearchParams({ limit: String(EXPORT_PAGE) });\n if (cursor) params.set(\"cursor\", cursor);\n const page = await apiRequest<{\n calls: Record<string, unknown>[];\n nextCursor?: string | null;\n }>(\n this.options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/calls?${params.toString()}`,\n );\n for (const call of page.calls) {\n calls.push({\n seq: Number(call.seq),\n kind: String(call.kind ?? \"call\"),\n tool: typeof call.tool === \"string\" ? call.tool : null,\n args: call.args ?? null,\n result: call.result ?? null,\n error: typeof call.error === \"string\" ? call.error : null,\n completedAt:\n typeof call.completedAt === \"string\" ? call.completedAt : null,\n });\n }\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n return calls;\n }\n\n /**\n * Promote this session's inline task into a stored task of the project\n * (version 1, pinned to the session's world unless `world` says otherwise),\n * so a task written for one end user can be reused and its grades\n * compared. The session then records the new task's id. A session on a\n * bundled task has nothing to save; one on a stored task is already saved.\n */\n async saveTask(\n opts: { name?: string; world?: string | null; message?: string } = {},\n ): Promise<WorldTaskSummary> {\n const task = await apiRequest<WorldTaskSummary>(\n this.options,\n \"POST\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}/task`,\n {\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.world !== undefined ? { world: opts.world } : {}),\n ...(opts.message !== undefined ? { message: opts.message } : {}),\n },\n );\n this.current = {\n ...this.current,\n taskName: task.name,\n task: {\n ...this.taskInfo,\n source: \"stored\",\n name: task.name,\n id: task.id,\n version: task.version,\n },\n };\n return task;\n }\n\n /**\n * End the session. `keepWarm` hands the container back to the pool instead\n * of tearing it down, so the next session for the same task starts warm —\n * the pooled instance still obeys the fleet's idle TTL and pinning.\n */\n async close(opts: { keepWarm?: boolean } = {}): Promise<{ state: string }> {\n return apiRequest(\n this.options,\n \"DELETE\",\n `/api/public/world-sessions/${encodeURIComponent(this.sessionId)}`,\n { keepWarm: opts.keepWarm ?? false },\n );\n }\n}\n\n/**\n * Attach to a session that already exists — resuming after a crash, or\n * driving a session someone else opened (a container started by hand on a\n * self-hosted install, a session opened by CI and handed to a developer).\n */\nexport async function attachSession(\n sessionId: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSession> {\n const state = await apiRequest<WorldSessionState>(\n options,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(sessionId)}`,\n );\n return new WorldSession(sessionId, state, options);\n}\n\nexport type OpenSessionOptions = {\n versionId?: string;\n reuseWarm?: boolean;\n /** More than `tools`: `[\"api\"]`, `[\"ui\"]`, `[\"browser\"]`. The platform\n * refuses (HTTP 400) rather than quietly serving less than asked. */\n surfaces?: WorldSurfaceKind[];\n options?: WorldsClientOptions;\n};\n\n/**\n * Open a live session against one task of a world. Returns as soon as the\n * platform has accepted it — call `ready()` to wait for the container.\n *\n * `task` is a bundled scenario's name, a stored task's `{ id, version? }`\n * or an inline `WorldTaskSpec` (the latter two need a host engine world — the\n * platform answers 400 for a pod world). The older positional form\n * `openSession(slug, \"task-name\", opts)` still works.\n */\nexport async function openSession(\n slugOrRef: string,\n task: OpenSessionOptions & { task: WorldTaskRef },\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n task: WorldTaskRef,\n opts?: OpenSessionOptions,\n): Promise<WorldSession>;\nexport async function openSession(\n slugOrRef: string,\n taskOrOpts: WorldTaskRef | (OpenSessionOptions & { task: WorldTaskRef }),\n positionalOpts: OpenSessionOptions = {},\n): Promise<WorldSession> {\n const { task, ...opts } =\n typeof taskOrOpts === \"object\" && \"task\" in taskOrOpts\n ? taskOrOpts\n : { task: taskOrOpts as WorldTaskRef, ...positionalOpts };\n if (\n task === undefined ||\n task === null ||\n (typeof task === \"string\" && !task) ||\n (isTaskIdRef(task) && !task.id) ||\n (isTaskSpec(task) && !task.instruction) ||\n (typeof task === \"object\" && !isTaskIdRef(task) && !isTaskSpec(task))\n )\n throw new Error(\n \"openSession needs a task: a bundled task name, a stored task { id, version? } or { instruction, seed?, grader?, metadata? }\",\n );\n const options = opts.options ?? {};\n const unknown = (opts.surfaces ?? []).filter(\n (s) => !(SURFACE_KINDS as readonly string[]).includes(s),\n );\n if (unknown.length)\n throw new Error(\n `Unknown world surfaces: ${unknown.join(\", \")}; choose from ${SURFACE_KINDS.join(\", \")}`,\n );\n const at = slugOrRef.indexOf(\"@\");\n const slug = at === -1 ? slugOrRef : slugOrRef.slice(0, at);\n const state = await apiRequest<WorldSessionState & { reusedWarm: boolean }>(\n options,\n \"POST\",\n \"/api/public/world-sessions\",\n {\n ...(opts.versionId ? { versionId: opts.versionId } : { slug }),\n task,\n ...(opts.reuseWarm === undefined ? {} : { reuseWarm: opts.reuseWarm }),\n ...(opts.surfaces?.length ? { surfaces: opts.surfaces } : {}),\n },\n );\n return new WorldSession(state.sessionId, state, options);\n}\n\n// ── running many tasks at once ───────────────────────────────────────────────\n\nexport type SessionRunResult = {\n /** The task's name, or `inline:<hash>` for an unnamed inline task. */\n task: string;\n sessionId: string;\n reward: number | null;\n rewards: Record<string, number>;\n /** Set when the task threw instead of grading. */\n error?: string;\n};\n\nexport type SessionRunReport = {\n results: SessionRunResult[];\n /** Mean reward over every task, counting failures as 0. */\n mean: number;\n /** True when `mean >= failUnder` (or no gate was set). */\n passed: boolean;\n};\n\n/**\n * RUN MANY TASKS IN PARALLEL, one warm container each.\n *\n * Parallelism against live worlds is the normal case — a suite is a dozen\n * tasks and each needs its own container, because two agents sharing one\n * world state would corrupt both episodes. Every caller was writing the same\n * pool, the same per-task open/ready/toolkit/grade/close, and the same\n * \"don't let one failure kill the run\" logic, so it belongs here:\n *\n * const report = await runSessions({\n * world: \"revenue-ops-sim@main\",\n * tasks, // default: every task in the world\n * concurrency: 4,\n * failUnder: 0.7,\n * agent: async ({ toolkit, instruction }) =>\n * myAgent(toolkit.impls, toolkit.schemas, instruction),\n * });\n *\n * The handler gets a ready session with its toolkit already bound; grading,\n * closing (warm) and aggregation are handled. A task that throws scores 0\n * and records why — the tasks that passed keep their results.\n */\nexport async function runSessions(opts: {\n world: string;\n /** Bundled task names, stored task refs and/or inline task specs\n * (default: every bundled task in the world). */\n tasks?: WorldTaskRef[];\n concurrency?: number;\n failUnder?: number;\n /** Pin every session to one version (default: the world's head). */\n versionId?: string;\n /** Hand the containers back warm for the next run (default: true). */\n keepWarm?: boolean;\n agent: (ctx: {\n session: WorldSession;\n toolkit: WorldToolkit;\n instruction: string;\n /** The task's label — see `SessionRunResult.task`. */\n task: string;\n /** The task as it was given: a bundled name, a stored ref or the\n * inline spec. */\n taskRef: WorldTaskRef;\n }) => Promise<unknown>;\n onResult?: (result: SessionRunResult) => void;\n options?: WorldsClientOptions;\n}): Promise<SessionRunReport> {\n const options = opts.options ?? {};\n const concurrency = Math.max(1, opts.concurrency ?? 3);\n\n let tasks = opts.tasks;\n let versionId = opts.versionId;\n if (!tasks || !versionId) {\n // One resolve for the whole run: every session pins the SAME version, so\n // a push mid-suite cannot split the results across two worlds.\n const { openWorld } = await import(\"./index\");\n const world = await openWorld(opts.world, options);\n tasks = tasks ?? world.tasks.map((t) => t.name);\n versionId = versionId ?? world.version.versionId;\n }\n\n const results: SessionRunResult[] = [];\n let next = 0;\n await Promise.all(\n Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {\n while (next < tasks!.length) {\n const taskRef = tasks![next++];\n let task = taskLabel(taskRef);\n let session: WorldSession | null = null;\n try {\n session = await openSession(opts.world, {\n task: taskRef,\n versionId,\n options,\n });\n task = taskLabel(taskRef, session.taskInfo);\n await session.ready();\n const toolkit = await session.toolkit();\n await opts.agent({\n session,\n toolkit,\n instruction:\n session.instruction ??\n (isTaskSpec(taskRef) ? taskRef.instruction : task),\n task,\n taskRef,\n });\n const graded = await session.grade();\n const result: SessionRunResult = {\n task,\n sessionId: session.sessionId,\n reward: graded.reward,\n rewards: graded.rewards,\n };\n results.push(result);\n opts.onResult?.(result);\n } catch (error) {\n const result: SessionRunResult = {\n task,\n sessionId: session?.sessionId ?? \"\",\n reward: 0,\n rewards: {},\n // An Error with an empty message would read as \"no error\" to any\n // caller checking truthiness; name the type instead.\n error:\n (error instanceof Error ? error.message : String(error)) ||\n (error instanceof Error ? error.name : \"Unknown error\"),\n };\n results.push(result);\n opts.onResult?.(result);\n } finally {\n // Always give the container back — a leaked session bills until the\n // fleet's idle TTL reaps it.\n await session\n ?.close({ keepWarm: opts.keepWarm ?? true })\n .catch(() => undefined);\n }\n }\n }),\n );\n\n const mean =\n results.reduce((sum, r) => sum + (r.reward ?? 0), 0) /\n (results.length || 1);\n return {\n results: results.sort((a, b) => a.task.localeCompare(b.task)),\n mean,\n passed: opts.failUnder === undefined ? true : mean >= opts.failUnder,\n };\n}\n","import { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { WorldTaskSpec } from \"./session\";\n\n/**\n * STORED WORLD TASKS: a task spec kept by the project, outside any bundle.\n *\n * An inline task (`openSession(world, { task: { instruction, … } })`) belongs\n * to one session. A stored task is the same spec as a named, versioned\n * project resource: create it once, open as many sessions on it as you like\n * with `{ task: { id } }`, and every grade attributes back to the task and\n * its version. Updating the spec never rewrites history — it appends a\n * version, and a session opened on `{ id, version: 2 }` keeps running v2\n * after v3 exists.\n *\n * const task = await createTask({\n * name: \"refund-late-invoice\",\n * world: \"acme-billing\",\n * spec: { instruction: \"…\", seed: {…}, grader: {…} },\n * });\n * const session = await openSession(\"acme-billing\", { task: { id: task.id } });\n *\n * Tasks are project-scoped: another project's task id is not found (404),\n * never forbidden. `world` pins a task to one world's slug (validated against\n * that world's contract); null leaves it usable with any world.\n */\n\nexport type WorldTaskSummary = {\n id: string;\n name: string;\n world: string | null;\n version: number;\n hash: string;\n spec: WorldTaskSpec;\n createdAt: string;\n updatedAt: string;\n createdBy: string;\n updatedBy: string;\n /** On create, when the task is pinned to a world of a deprecated shape (an\n * api bundle): what to run instead. A retired shape is refused. */\n deprecations?: { code: string; message: string; replacement: string }[];\n};\n\nexport type WorldTaskVersionSummary = {\n version: number;\n hash: string;\n createdAt: string;\n createdBy: string;\n message: string | null;\n};\n\nexport type WorldTaskDetail = WorldTaskSummary & {\n versions: WorldTaskVersionSummary[];\n};\n\nexport type WorldTaskPage = {\n tasks: WorldTaskSummary[];\n meta: { page: number; limit: number; totalItems: number; totalPages: number };\n};\n\nexport type WorldTaskValidation = {\n taskId: string;\n version: number;\n /** The world version the task was checked against. */\n versionId: string;\n ok: boolean;\n /** `entities` when the world's contract was read and every seed and check\n * entity was matched against it; `none` when the version has no contract\n * to check (a mock-tools world), in which case `ok` says only that the\n * version exists and is READY. */\n checked: \"entities\" | \"none\";\n problems: string[];\n entities: string[] | null;\n};\n\nconst TASKS = \"/api/public/world-tasks\";\nconst taskRoute = (id: string) => `${TASKS}/${encodeURIComponent(id)}`;\n\nconst compact = (body: Record<string, unknown>) =>\n Object.fromEntries(Object.entries(body).filter(([, v]) => v !== undefined));\n\n/** Store a task. `name` defaults to `spec.name`; one of the two is needed. */\nexport async function createTask(\n input: {\n spec: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n return apiRequest<WorldTaskSummary>(\n options,\n \"POST\",\n TASKS,\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** Change a task. A new `spec` becomes the next version (the old ones stay\n * readable and openable); `name` and `world` change in place. */\nexport async function updateTask(\n taskId: string,\n input: {\n spec?: WorldTaskSpec;\n name?: string;\n world?: string | null;\n message?: string;\n },\n options: WorldsClientOptions = {},\n): Promise<WorldTaskSummary> {\n if (\n input.spec === undefined &&\n input.name === undefined &&\n input.world === undefined\n )\n throw new Error(\"updateTask: nothing to update — pass spec, name or world\");\n return apiRequest<WorldTaskSummary>(\n options,\n \"PATCH\",\n taskRoute(taskId),\n compact({\n spec: input.spec,\n name: input.name,\n world: input.world,\n message: input.message,\n }),\n );\n}\n\n/** The project's tasks, newest change first. `world` keeps only tasks\n * pinned to that slug; `metadata` keeps tasks whose spec metadata carries\n * every given key/value (`{ externalUserId: \"u_42\" }`). */\nexport async function listTasks(\n filter: {\n world?: string;\n metadata?: Record<string, string>;\n page?: number;\n limit?: number;\n } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskPage> {\n const params = new URLSearchParams();\n if (filter.world) params.set(\"world\", filter.world);\n if (filter.page !== undefined) params.set(\"page\", String(filter.page));\n if (filter.limit !== undefined) params.set(\"limit\", String(filter.limit));\n for (const [key, value] of Object.entries(filter.metadata ?? {}))\n params.set(`metadata.${key}`, value);\n const query = params.toString();\n return apiRequest<WorldTaskPage>(\n options,\n \"GET\",\n query ? `${TASKS}?${query}` : TASKS,\n );\n}\n\n/** One task with its version history; `version` reads that version's spec\n * instead of the current one. */\nexport async function getTask(\n taskId: string,\n opts: { version?: number } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskDetail> {\n const query =\n opts.version === undefined ? \"\" : `?version=${String(opts.version)}`;\n return apiRequest<WorldTaskDetail>(\n options,\n \"GET\",\n `${taskRoute(taskId)}${query}`,\n );\n}\n\n/** Remove a task and every version. Sessions already opened on it keep\n * their copy of the spec. */\nexport async function deleteTask(\n taskId: string,\n options: WorldsClientOptions = {},\n): Promise<{ id: string; name: string }> {\n return apiRequest(options, \"DELETE\", taskRoute(taskId));\n}\n\n/** Check a task against a world version without opening a session: every\n * seed entity and every check's entity must exist in the world's contract.\n * `slug` checks against that world's head, `versionId` against an exact\n * version, neither against the task's own `world` pin. */\nexport async function validateTask(\n taskId: string,\n target: { version?: number; slug?: string; versionId?: string } = {},\n options: WorldsClientOptions = {},\n): Promise<WorldTaskValidation> {\n return apiRequest<WorldTaskValidation>(\n options,\n \"POST\",\n `${taskRoute(taskId)}/validate`,\n compact({\n version: target.version,\n slug: target.slug,\n versionId: target.versionId,\n }),\n );\n}\n","import { createHash } from \"node:crypto\";\nimport { gzipSync, gunzipSync } from \"node:zlib\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\n/**\n * The working-dir half of the TS CLI: push / pull / checkout / status /\n * branch / tag / propose — a faithful port of the Python client\n * (`gatewaysdk/benchmark_hub/client.py` + `_archive.py`).\n *\n * LOCKSTEP WARNING — the content hash is the version's identity and is\n * byte-compatible with Prime Intellect. It now has FOUR implementations that\n * must stay identical: worker `environmentAgent/tar.ts`, web\n * `benchmark-hub/server/benchmarkContentHash.ts`, Python `_archive.py`, and\n * this file. This one is a line-for-line port of the WEB TypeScript\n * implementation (same language, same crypto) — if the rule ever changes,\n * change all four or push identity splits by client.\n *\n * One deliberate refusal, same policy as the web upload path: a bundle with\n * a ROOT `.gitignore` is refused rather than mis-hashed — the Python CLI\n * honors it via `gitignore_parser`, and an imperfect reimplementation here\n * would produce a wrong, Prime-incompatible hash silently.\n */\n\nexport const DEFAULT_BRANCH = \"main\";\nconst META_RELPATH = path.join(\".gateway\", \".env-metadata.json\");\nconst SKIP_DIRS = new Set([\n \".git\",\n \"__pycache__\",\n \"node_modules\",\n \".venv\",\n \".mypy_cache\",\n \"dist\",\n \"build\",\n \"outputs\",\n]);\nconst ROOT_EXCLUDED_DIRS = new Set([\"dist\", \"build\", \"outputs\", \"__pycache__\"]);\n\n/** Gateway-only root markers that widen collection to every ordinary root\n * file. The FOURTH copy of this list (python SDK `_archive.py`, web\n * `benchmarkContentHash.ts`, worker `tar.ts`, and here) — all four MUST stay\n * identical or the same tree hashes differently per pusher. This copy\n * missing `gateway-api-world.toml` is exactly how an api world pushed from\n * TS landed on the hub with no OpenAPI contract and no marker: the root\n * files never entered the manifest, and nothing downstream could tell. */\nconst BROAD_ROOT_MARKERS = [\"gateway-env.toml\", \"gateway-api-world.toml\"];\n\n// ── content-hash rules (port of web benchmarkContentHash.ts) ───────────────\n\nfunction isExcludedDirComponent(component: string): boolean {\n return (\n component.startsWith(\".\") ||\n ROOT_EXCLUDED_DIRS.has(component) ||\n component.endsWith(\".egg-info\")\n );\n}\n\nexport function isIncludedInContentHash(\n relPath: string,\n includeAllRootFiles: boolean,\n): boolean {\n const parts = relPath.split(\"/\");\n const name = parts[parts.length - 1];\n const dirParts = parts.slice(0, -1);\n if (name.startsWith(\".\")) return false;\n if (parts.includes(\"__pycache__\")) return false;\n if (dirParts.length === 0) {\n return (\n includeAllRootFiles ||\n name === \"README.md\" ||\n name === \"pyproject.toml\" ||\n BROAD_ROOT_MARKERS.includes(name) ||\n name.endsWith(\".py\")\n );\n }\n return !dirParts.some(isExcludedDirComponent);\n}\n\n/** The archive-visible files of a working dir, as sorted relpaths. Throws on\n * a root .gitignore (see the header). */\nexport function collectArchiveRelPaths(dir: string): string[] {\n if (fs.existsSync(path.join(dir, \".gitignore\"))) {\n throw new Error(\n \"This bundle has a root .gitignore, which the Python CLI honors via \" +\n \"gitignore_parser. Reimplementing that imperfectly here would \" +\n \"silently produce a different content hash, so the TS CLI refuses. \" +\n \"Remove the .gitignore (or bake its effect into the tree) and retry.\",\n );\n }\n const out: string[] = [];\n const includeAllRootFiles = BROAD_ROOT_MARKERS.some((marker) =>\n fs.existsSync(path.join(dir, marker)),\n );\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!isExcludedDirComponent(entry.name)) walk(childRel);\n } else if (entry.isFile()) {\n if (isIncludedInContentHash(childRel, includeAllRootFiles)) {\n out.push(childRel);\n }\n }\n }\n };\n walk(\"\");\n return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nexport function computeContentHash(dir: string): string {\n const hasher = createHash(\"sha256\");\n for (const relPath of collectArchiveRelPaths(dir)) {\n hasher.update(Buffer.from(`file:${relPath}`, \"utf-8\"));\n hasher.update(fs.readFileSync(path.join(dir, relPath)));\n }\n return hasher.digest(\"hex\");\n}\n\n// ── deterministic tar.gz writer ─────────────────────────────────────────────\n\nfunction octal(value: number, length: number): Buffer {\n return Buffer.from(value.toString(8).padStart(length - 1, \"0\") + \"\\0\", \"ascii\");\n}\n\nfunction tarHeader(name: string, size: number): Buffer {\n const header = Buffer.alloc(512);\n header.write(name, 0, 100, \"utf-8\");\n octal(0o644, 8).copy(header, 100); // mode\n octal(0, 8).copy(header, 108); // uid\n octal(0, 8).copy(header, 116); // gid\n octal(size, 12).copy(header, 124);\n octal(0, 12).copy(header, 136); // mtime = 0 (deterministic)\n header.write(\" \", 148, \"ascii\"); // checksum placeholder = spaces\n header.write(\"0\", 156, \"ascii\"); // regular file\n header.write(\"ustar\", 257, \"ascii\");\n header.write(\"00\", 263, \"ascii\");\n let sum = 0;\n for (const byte of header) sum += byte;\n header.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n return header;\n}\n\nfunction tarMember(name: string, payload: Buffer): Buffer[] {\n const parts: Buffer[] = [];\n const nameBytes = Buffer.byteLength(name, \"utf-8\");\n if (nameBytes > 100) {\n // GNU long name: an 'L' member whose body is the real name.\n const body = Buffer.from(name + \"\\0\", \"utf-8\");\n const lHeader = tarHeader(\"././@LongLink\", body.length);\n lHeader.write(\"L\", 156, \"ascii\");\n let sum = 0;\n lHeader.write(\" \", 148, \"ascii\");\n for (const byte of lHeader) sum += byte;\n lHeader.write(sum.toString(8).padStart(6, \"0\") + \"\\0 \", 148, \"ascii\");\n parts.push(lHeader, body);\n const pad = body.length % 512 === 0 ? 0 : 512 - (body.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n parts.push(tarHeader(name.slice(0, 100), payload.length));\n } else {\n parts.push(tarHeader(name, payload.length));\n }\n parts.push(payload);\n const pad = payload.length % 512 === 0 ? 0 : 512 - (payload.length % 512);\n if (pad) parts.push(Buffer.alloc(pad));\n return parts;\n}\n\n/** A deterministic .tar.gz of the source files (node's gzip stamps no mtime,\n * matching the Python's mtime=0 gzip). */\nexport function buildSourceTarball(dir: string): Buffer {\n const parts: Buffer[] = [];\n for (const relPath of collectArchiveRelPaths(dir)) {\n parts.push(...tarMember(relPath, fs.readFileSync(path.join(dir, relPath))));\n }\n parts.push(Buffer.alloc(1024)); // end-of-archive\n return gzipSync(Buffer.concat(parts), { level: 9 });\n}\n\n// ── local metadata (.gateway/.env-metadata.json) ────────────────────────────\n\nexport type LocalMeta = Record<string, unknown> & {\n slug?: string;\n branch?: string;\n versionId?: string;\n contentHash?: string;\n baseFiles?: Record<string, string>;\n};\n\nexport function readLocalMeta(dir: string): LocalMeta | null {\n try {\n const raw = fs.readFileSync(path.join(dir, META_RELPATH), \"utf-8\");\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" ? (parsed as LocalMeta) : null;\n } catch {\n return null;\n }\n}\n\nexport function writeLocalMeta(dir: string, meta: LocalMeta): void {\n fs.mkdirSync(path.join(dir, \".gateway\"), { recursive: true });\n fs.writeFileSync(path.join(dir, META_RELPATH), JSON.stringify(meta, null, 2));\n}\n\nexport function snapshotTreeHashes(dir: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const relPath of collectArchiveRelPaths(dir)) {\n out[relPath] = createHash(\"sha256\")\n .update(fs.readFileSync(path.join(dir, relPath)))\n .digest(\"hex\");\n }\n return out;\n}\n\nexport function localTreeState(dir: string): {\n meta: LocalMeta | null;\n dirty: string[];\n clean: boolean;\n} {\n const meta = readLocalMeta(dir);\n const base = meta?.baseFiles;\n if (!base || typeof base !== \"object\") {\n return { meta, dirty: [], clean: false };\n }\n const now = snapshotTreeHashes(dir);\n const dirty = new Set<string>();\n for (const [p, h] of Object.entries(now)) if (base[p] !== h) dirty.add(p);\n for (const p of Object.keys(base)) if (!(p in now)) dirty.add(p);\n return { meta, dirty: [...dirty].sort(), clean: dirty.size === 0 };\n}\n\n// ── protocol helpers ─────────────────────────────────────────────────────────\n\nconst sha256b64 = (data: Buffer) =>\n createHash(\"sha256\").update(data).digest(\"base64\");\n\nfunction readPyproject(dir: string): { name?: string; version?: string } {\n try {\n const text = fs.readFileSync(path.join(dir, \"pyproject.toml\"), \"utf-8\");\n // Minimal [project] reads — name and version only, quoted single-line form.\n const section = /\\[project\\]([\\s\\S]*?)(\\n\\[|$)/.exec(text)?.[1] ?? \"\";\n const name = /\\bname\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n const version = /\\bversion\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n return { name, version };\n } catch {\n return {};\n }\n}\n\n/** A schema world's own version: `x-gateway.package.version` of its contract\n * (`schema/world.json`, or `server/world/schema/world.json` in an api bundle).\n * What a connector world has instead of a pyproject, so its versions read\n * \"1.0.0\" rather than \"unversioned\" on the platform. */\nfunction readWorldContractVersion(dir: string): { name?: string; version?: string } {\n for (const rel of [\"schema/world.json\", path.join(\"server\", \"world\", \"schema\", \"world.json\")]) {\n try {\n const parsed = JSON.parse(fs.readFileSync(path.join(dir, rel), \"utf-8\")) as {\n \"x-gateway\"?: { package?: { id?: string; version?: string } };\n };\n const pkg = parsed[\"x-gateway\"]?.package;\n if (pkg?.version) return { name: pkg.id, version: pkg.version };\n } catch {\n // not a schema world, or not at this root\n }\n }\n return {};\n}\n\nfunction buildFileManifest(\n dir: string,\n): { path: string; isDirectory: boolean; size: number; sha256: string }[] {\n const entries: { path: string; isDirectory: boolean; size: number; sha256: string }[] = [];\n const walk = (rel: string) => {\n const abs = rel ? path.join(dir, rel) : dir;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.endsWith(\".egg-info\")) {\n walk(childRel);\n }\n } else if (entry.isFile()) {\n const payload = fs.readFileSync(path.join(dir, childRel));\n entries.push({\n path: childRel,\n isDirectory: false,\n size: payload.length,\n sha256: createHash(\"sha256\").update(payload).digest(\"hex\"),\n });\n }\n }\n };\n walk(\"\");\n return entries;\n}\n\nasync function putObject(url: string, data: Buffer, shaB64: string): Promise<void> {\n const resp = await fetch(url, {\n method: \"PUT\",\n headers: {\n \"Content-Type\": \"application/gzip\",\n \"x-amz-checksum-sha256\": shaB64,\n },\n body: new Uint8Array(data),\n });\n if (!resp.ok) {\n throw new Error(`object PUT -> ${resp.status}: ${(await resp.text()).slice(0, 300)}`);\n }\n}\n\n// ── the workflows ────────────────────────────────────────────────────────────\n\nexport async function push(\n dir: string,\n opts: {\n slug?: string;\n branch?: string;\n force?: boolean;\n message?: string;\n author?: string;\n /** Push on top of this version instead of the local meta's base — what a\n * CI checkout (which has no local meta) passes after resolving the\n * branch tip, so re-validating a PR replaces its own previous push\n * instead of 409ing against it. */\n baseVersionId?: string | null;\n /** Container metadata recorded on resolve — the Python CLI's --name,\n * --description, --tag and --visibility. */\n name?: string;\n description?: string;\n tags?: string[];\n visibility?: string;\n /** Pre-built OCI image ref for image/agentic envs (recorded on the version). */\n imageRef?: string;\n options?: WorldsClientOptions;\n } = {},\n): Promise<{\n containerId: string;\n slug: string;\n versionId: string;\n contentHash: string;\n branch: string;\n state: string | null;\n alreadyUploaded: boolean;\n}> {\n const options = opts.options ?? {};\n if (!fs.statSync(dir).isDirectory()) throw new Error(`Not a directory: ${dir}`);\n const localMeta = readLocalMeta(dir) ?? {};\n const branch = opts.branch ?? (localMeta.branch as string | undefined) ?? DEFAULT_BRANCH;\n const baseVersionId = opts.baseVersionId ?? localMeta.versionId ?? null;\n\n const contentHash = computeContentHash(dir);\n const pyproject = readPyproject(dir);\n // A connector world carries its version on its contract, not a pyproject.\n const contractVersion = pyproject.version ? undefined : readWorldContractVersion(dir).version;\n if (contractVersion) pyproject.version = contractVersion;\n const slug = opts.slug ?? pyproject.name ?? path.basename(path.resolve(dir));\n\n const resolve = await apiRequest<{ containerId: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve\",\n {\n slug,\n name: opts.name ?? pyproject.name ?? slug,\n ...(opts.description ? { description: opts.description } : {}),\n ...(opts.tags?.length ? { tags: opts.tags } : {}),\n ...(opts.visibility ? { visibility: opts.visibility } : {}),\n },\n );\n\n const tarball = buildSourceTarball(dir);\n const bundleSha256 = sha256b64(tarball);\n\n const version = await apiRequest<{\n versionId: string;\n uploadUrl?: string;\n alreadyUploaded?: boolean;\n }>(options, \"POST\", \"/api/public/benchmark-containers/versions\", {\n containerId: resolve.containerId,\n contentHash,\n bundleSha256,\n bundleSizeBytes: tarball.length,\n ...(pyproject.version ? { semanticVersion: pyproject.version } : {}),\n pyprojectMeta: pyproject,\n fileManifest: buildFileManifest(dir),\n branch,\n baseVersionId,\n ...(opts.force ? { force: true } : {}),\n ...(opts.message ? { changeReason: opts.message } : {}),\n ...(opts.author ? { author: opts.author } : {}),\n ...(opts.imageRef ? { imageRef: opts.imageRef } : {}),\n });\n\n if (version.uploadUrl) await putObject(version.uploadUrl, tarball, bundleSha256);\n\n const final = await apiRequest<{ state?: string; branch?: string }>(\n options,\n \"POST\",\n `/api/public/benchmark-containers/versions/${version.versionId}/finalize`,\n { branch, baseVersionId, ...(opts.force ? { force: true } : {}) },\n );\n\n writeLocalMeta(dir, {\n ...localMeta,\n slug,\n ref: branch,\n branch,\n versionId: version.versionId,\n contentHash,\n semanticVersion: pyproject.version,\n forkedFromVersionId: baseVersionId,\n baseFiles: snapshotTreeHashes(dir),\n });\n return {\n containerId: resolve.containerId,\n slug,\n versionId: version.versionId,\n contentHash,\n branch: final.branch ?? branch,\n state: final.state ?? null,\n alreadyUploaded: Boolean(version.alreadyUploaded),\n };\n}\n\n/** Extract a downloaded bundle into `dir` (paths sanitized). */\nfunction extractBundle(bundle: Buffer, dir: string): number {\n const tar = gunzipSync(bundle);\n let offset = 0;\n let longName: string | null = null;\n let written = 0;\n while (offset + 512 <= tar.length) {\n const header = tar.subarray(offset, offset + 512);\n offset += 512;\n if (header.every((b) => b === 0)) break;\n const rawName = header.subarray(0, 100).toString(\"utf-8\").replace(/\\0.*$/, \"\");\n const size = parseInt(header.subarray(124, 136).toString(\"ascii\").replace(/\\0.*$/, \"\").trim(), 8) || 0;\n const typeflag = header.subarray(156, 157).toString(\"ascii\");\n const body = tar.subarray(offset, offset + size);\n offset += size + (size % 512 === 0 ? 0 : 512 - (size % 512));\n if (typeflag === \"L\") {\n longName = body.toString(\"utf-8\").replace(/\\0.*$/, \"\");\n continue;\n }\n const name = (longName ?? rawName).replace(/^\\.\\//, \"\");\n longName = null;\n if (typeflag !== \"0\" && typeflag !== \"\") continue;\n // Safe extract: no absolute paths, no traversal.\n if (name.startsWith(\"/\") || name.split(\"/\").includes(\"..\")) continue;\n const target = path.join(dir, name);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, body);\n written++;\n }\n return written;\n}\n\nexport async function pull(\n slugRef: string,\n target?: string,\n options: WorldsClientOptions = {},\n): Promise<{ slug: string; dir: string; versionId: string; files: number }> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? \"latest\" : slugRef.slice(at + 1);\n\n const details = await apiRequest<{\n versionId: string;\n contentHash: string;\n semanticVersion?: string | null;\n downloadUrl?: string;\n bundleSha256?: string;\n }>(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ref,\n });\n if (!details.downloadUrl) {\n throw new Error(`${slug}@${ref} resolved but has no uploaded bundle`);\n }\n\n let dir = target ?? path.join(process.cwd(), slug);\n if (!target) {\n let i = 1;\n const base = dir;\n while (fs.existsSync(dir)) dir = `${base}-${i++}`;\n }\n fs.mkdirSync(dir, { recursive: true });\n\n const resp = await fetch(details.downloadUrl);\n if (!resp.ok) throw new Error(`bundle download -> ${resp.status}`);\n const bundle = Buffer.from(await resp.arrayBuffer());\n if (details.bundleSha256 && sha256b64(bundle) !== details.bundleSha256) {\n throw new Error(\n `bundle integrity check failed for ${slug}@${ref}: downloaded sha256 != recorded bundleSha256`,\n );\n }\n\n const files = extractBundle(bundle, dir);\n const branch = ref === \"latest\" || /^\\d|^[0-9a-f]{8,}$/.test(ref) ? DEFAULT_BRANCH : ref;\n writeLocalMeta(dir, {\n slug,\n ref,\n branch,\n versionId: details.versionId,\n contentHash: details.contentHash,\n semanticVersion: details.semanticVersion ?? undefined,\n baseFiles: snapshotTreeHashes(dir),\n });\n return { slug, dir, versionId: details.versionId, files };\n}\n\nexport async function propose(\n dir: string,\n opts: { title: string; reason: string; targetBranch?: string; options?: WorldsClientOptions },\n): Promise<{ proposalId: string }> {\n const meta = readLocalMeta(dir);\n if (!meta?.slug || !meta.baseFiles) {\n throw new Error(\"This dir has no pull/push base — run pull first, then edit, then propose.\");\n }\n const state = localTreeState(dir);\n if (state.clean) throw new Error(\"Nothing to propose — the tree matches its base.\");\n const changes = state.dirty.map((relPath) => {\n const abs = path.join(dir, relPath);\n if (!fs.existsSync(abs)) return { path: relPath, action: \"delete\" as const };\n return {\n path: relPath,\n action: \"write\" as const,\n newContent: fs.readFileSync(abs, \"utf-8\"),\n };\n });\n const res = await apiRequest<{ proposalId: string }>(\n opts.options ?? {},\n \"POST\",\n \"/api/public/benchmark-containers/proposals\",\n {\n slug: meta.slug,\n title: opts.title,\n changeReason: opts.reason,\n baseVersionId: meta.versionId,\n ...(opts.targetBranch ? { targetBranch: opts.targetBranch } : {}),\n changes,\n },\n );\n return res;\n}\n\nexport async function createRef(\n slug: string,\n name: string,\n kind: \"branch\" | \"tag\",\n versionId?: string,\n options: WorldsClientOptions = {},\n): Promise<{ name: string; kind: string; versionId: string }> {\n return apiRequest(options, \"POST\", \"/api/public/benchmark-containers/refs\", {\n slug,\n name,\n kind,\n ...(versionId ? { versionId } : {}),\n });\n}\n","/**\n * PR validation: push the checkout's world source, run it, gate on the graded\n * result — one composed call, because CI should not have to re-derive the\n * choreography from primitives.\n *\n * The differentiating property, stated so it stays true: validation runs the\n * PULL REQUEST'S OWN world source. The push files the checkout as a version on\n * the PR's branch (content-hash dedup makes re-runs cheap), the dispatch pins\n * that version, and the platform resolves the branch back to its open PR — so\n * the run page names the PR and the PR comment names the run. Nothing here\n * validates a standing deployment while pretending to validate the change.\n */\n\nimport {\n apiRequest,\n detectProvenance,\n listRunConfigs,\n waitForRun,\n type RunReport,\n type WorldsClientOptions,\n} from \"./index\";\nimport { push } from \"./hub\";\n\nexport type ValidatedRun = {\n model: string;\n runId: string;\n report: RunReport | null;\n /** Why this run fails the gate, or null when it passes. */\n failure: string | null;\n};\n\nexport type ValidateReport = {\n ok: boolean;\n slug: string;\n branch: string;\n versionId: string;\n contentHash: string;\n runConfig: { id: string; name: string };\n runs: ValidatedRun[];\n /** A PR-comment-ready summary of the whole validation. */\n markdown: string;\n};\n\nfunction fmtScore(score: number | null): string {\n return score === null ? \"no score\" : score.toFixed(3);\n}\n\nfunction buildMarkdown(\n report: Omit<ValidateReport, \"markdown\">,\n minScore: number | null,\n source?: { repoUrl?: string; commit?: string },\n): string {\n const lines: string[] = [];\n lines.push(\n `### World validation ${report.ok ? \"passed\" : \"failed\"} — \\`${report.slug}@${report.branch}\\``,\n );\n lines.push(\"\");\n // Name the exact source that ran: the commit on GitHub when we know it,\n // always the content hash the platform pinned.\n const commitLink =\n source?.repoUrl && source?.commit\n ? `[\\`${source.commit.slice(0, 12)}\\`](${source.repoUrl}/commit/${source.commit})`\n : null;\n lines.push(\n `Ran the pull request's own world source` +\n (commitLink ? ` (${commitLink} on \\`${report.branch}\\`` : ` (`) +\n `${commitLink ? \", \" : \"\"}pinned as \\`${report.contentHash.slice(0, 12)}\\`) ` +\n `through run config **${report.runConfig.name}**` +\n (minScore !== null ? `, gating at score ≥ ${minScore}.` : \".\"),\n );\n lines.push(\"\");\n lines.push(\"| Model | Status | Score | Run |\");\n lines.push(\"| --- | --- | ---: | --- |\");\n for (const run of report.runs) {\n const r = run.report;\n const link = r?.url ? `[open](${r.url})` : \"—\";\n const status = run.failure\n ? `❌ ${run.failure}`\n : `✅ ${r?.status ?? \"COMPLETED\"}`;\n lines.push(\n `| \\`${run.model}\\` | ${status} | ${fmtScore(r?.score ?? null)} | ${link} |`,\n );\n }\n const taskRows = report.runs.flatMap((run) =>\n (run.report?.samples ?? []).map((sample) => ({\n model: run.model,\n task: sample.task ?? \"?\",\n reward: sample.reward,\n })),\n );\n // Every scenario, in the open: a validation whose per-scenario grades hide\n // behind a fold reads as one opaque number. Fold only when the table is\n // genuinely long.\n if (taskRows.length > 0) {\n const fold = taskRows.length > 12;\n lines.push(\"\");\n if (fold) {\n lines.push(\n `<details><summary>Per-scenario rewards (${taskRows.length})</summary>`,\n );\n lines.push(\"\");\n } else {\n lines.push(`**Scenarios (${taskRows.length})**`);\n lines.push(\"\");\n }\n lines.push(\"| Scenario | Model | Reward |\");\n lines.push(\"| --- | --- | ---: |\");\n for (const row of taskRows) {\n lines.push(\n `| ${row.task} | \\`${row.model}\\` | ${row.reward === null ? \"no score\" : row.reward.toFixed(2)} |`,\n );\n }\n if (fold) {\n lines.push(\"\");\n lines.push(\"</details>\");\n }\n }\n return lines.join(\"\\n\");\n}\n\n/**\n * Push `dir` on the current (or given) branch, dispatch the named run config\n * against the pushed version, wait for every run, and gate.\n *\n * The gate: every dispatch accepted, every run terminal COMPLETED, and — when\n * `minScore` is set — every run's score meets it. A run with NO score fails a\n * score gate rather than passing it: null is \"not scored\", never 0 and never\n * fine.\n */\nexport async function validateWorld(\n dir: string,\n opts: {\n slug?: string;\n runConfig: string;\n branch?: string;\n minScore?: number | null;\n timeoutMinutes?: number;\n onProgress?: (line: string) => void;\n options?: WorldsClientOptions;\n },\n): Promise<ValidateReport> {\n const options = opts.options ?? {};\n const progress = opts.onProgress ?? (() => {});\n const minScore = opts.minScore ?? null;\n\n const provenance = detectProvenance();\n const branch = opts.branch ?? provenance.branch;\n if (!branch)\n throw new Error(\n \"No branch to validate on: pass --branch or run inside a git checkout / GitHub Actions.\",\n );\n\n progress(`pushing ${dir} as ${opts.slug ?? \"(pyproject name)\"}@${branch}…`);\n // CI checkouts carry no local push meta, so a re-validation would 409\n // against the branch tip its own previous run created. Validation's\n // semantics are \"this branch's tip BECOMES the PR's source\": resolve the\n // current tip and push on top of it. A branch that does not exist yet\n // resolves to no base, which is a fresh branch — also correct.\n let tipVersionId: string | null = null;\n if (opts.slug) {\n try {\n const tip = await apiRequest<{ versionId?: string }>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/resolve-version\",\n { slug: opts.slug, ref: branch },\n );\n tipVersionId = tip.versionId ?? null;\n } catch {\n tipVersionId = null;\n }\n }\n const pushed = await push(dir, {\n slug: opts.slug,\n branch,\n baseVersionId: tipVersionId,\n message: `PR validation push (${provenance.commit?.slice(0, 12) ?? \"local\"})`,\n ...(provenance.actor?.name ? { author: provenance.actor.name } : {}),\n options,\n });\n progress(`pushed version ${pushed.versionId} (${pushed.contentHash.slice(0, 12)})`);\n\n // Resolve the run config by name (the stable handle CI configures) or id.\n const configs = await listRunConfigs(options);\n const runConfig =\n configs.find((c) => c.id === opts.runConfig) ??\n configs.find((c) => c.name === opts.runConfig);\n if (!runConfig) {\n const known = configs.map((c) => c.name).join(\", \") || \"(none)\";\n throw new Error(\n `Run config \"${opts.runConfig}\" not found in this project. Have: ${known}`,\n );\n }\n\n progress(`dispatching run config \"${runConfig.name}\" (${runConfig.models.join(\", \")})…`);\n const dispatched = await apiRequest<{\n versionLabel: string;\n runs: { model: string; runId: string; ok: boolean; error?: string }[];\n }>(options, \"POST\", \"/api/public/benchmark-containers/run-configs/dispatch\", {\n runConfigId: runConfig.id,\n versionId: pushed.versionId,\n ...provenance,\n });\n\n // The run's platform page. New deployments return it on the run report\n // (`url`); against an older deployment we build the same page from the\n // evaluation id, because a PR comment that cannot link the run defeats\n // the point of the comment.\n const host = (\n options.host ??\n process.env.GATEWAY_HOST ??\n \"https://withgateway.ai\"\n ).replace(/\\/+$/, \"\");\n let projectId: string | null = null;\n try {\n const projects = await apiRequest<{ data?: { id?: string }[] }>(\n options,\n \"GET\",\n \"/api/public/projects\",\n );\n projectId = projects.data?.[0]?.id ?? null;\n } catch {\n projectId = null;\n }\n const fallbackUrl = (report: RunReport): string | null => {\n if (report.url) return report.url;\n const evaluationId = report.evaluations[0]?.id;\n return projectId && evaluationId\n ? `${host}/project/${projectId}/environment/runs/${encodeURIComponent(evaluationId)}`\n : null;\n };\n\n const runs: ValidatedRun[] = [];\n for (const run of dispatched.runs) {\n if (!run.ok) {\n runs.push({\n model: run.model,\n runId: run.runId,\n report: null,\n failure: `dispatch failed: ${run.error ?? \"unknown error\"}`,\n });\n continue;\n }\n progress(`waiting on ${run.model} (run ${run.runId})…`);\n let report: RunReport | null = null;\n let failure: string | null = null;\n try {\n report = await waitForRun(run.runId, {\n timeoutMinutes: opts.timeoutMinutes ?? 45,\n options,\n onTick: (r) =>\n progress(\n `…${run.model}: ${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`,\n ),\n });\n report = { ...report, url: fallbackUrl(report) };\n if (report.status.toUpperCase() !== \"COMPLETED\") {\n failure = report.status;\n } else if (minScore !== null) {\n if (report.score === null) failure = \"completed without a score\";\n else if (report.score < minScore)\n failure = `score ${fmtScore(report.score)} < ${minScore}`;\n }\n } catch (error) {\n failure = error instanceof Error ? error.message : String(error);\n }\n runs.push({ model: run.model, runId: run.runId, report, failure });\n }\n\n const base = {\n ok: runs.length > 0 && runs.every((r) => r.failure === null),\n slug: pushed.slug,\n branch,\n versionId: pushed.versionId,\n contentHash: pushed.contentHash,\n runConfig: { id: runConfig.id, name: runConfig.name },\n runs,\n };\n return {\n ...base,\n markdown: buildMarkdown(base, minScore, {\n repoUrl: provenance.repoUrl,\n commit: provenance.commit,\n }),\n };\n}\n","/**\n * `describeWorld(slug)` — what a world holds and how each field is stored,\n * from `GET /api/public/worlds/{slug}`: the entities (primary key, unique\n * keys, relationships, row count, fields with their `[redact]` policy) and\n * the `[redact]` table itself, so `storedForms(world, field, plaintext)`\n * can compute a lookup value without Python. The CLI twin is\n * `gateway worlds describe <slug>`; for a directory the CLI asks the schema\n * runtime instead and merges the same shape.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { RedactPolicy, Redaction } from \"./redaction\";\n\nexport type WorldField = {\n name: string;\n type: string | null;\n required: boolean;\n /** How the store holds it; null means in the clear (queryable by plaintext as given). */\n redaction: Redaction | null;\n};\n\nexport type WorldRelationship = {\n fields: string[];\n target: string;\n on_delete?: string;\n};\n\nexport type WorldEntityMapping = {\n localEntity: string;\n localField: string;\n depEntity: string;\n depField: string;\n /** A closed set, applied left to right before each world's own redaction. */\n transform: string[];\n};\n\nexport type WorldDependency = {\n alias: string;\n dependsOn: { slug: string | null; versionId: string };\n task: string | null;\n tools: string[];\n entities: WorldEntityMapping[];\n};\n\nexport type WorldEntity = {\n name: string;\n primaryKey: string[];\n unique: string[][];\n relationships: WorldRelationship[];\n /** Rows in the head version; null when the platform does not count this kind. */\n rowCount: number | null;\n fields: WorldField[];\n};\n\nexport type WorldDescription = {\n slug: string;\n name: string;\n description: string | null;\n kind: string;\n version: { id: string; contentHash: string; semanticVersion: string | null };\n url: string;\n hostedUrl: string | null;\n tools: { name: string; signature: string; doc: string | null }[];\n taskCount: number;\n links: { tasks: string; sessions: string };\n /** World-to-world links from `[dependencies]`, resolved at commit, with the\n * entity mappings `--across` follows. */\n dependencies?: WorldDependency[];\n entities: WorldEntity[];\n redact: RedactPolicy | null;\n};\n\n/** The world's head version, described. The route reads the head only, so a\n * `slug@ref` is refused rather than silently served as the head. */\nexport async function describeWorld(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<WorldDescription> {\n if (slug.includes(\"@\"))\n throw new Error(\n `describeWorld reads a world's head version: pass the slug without @ref (got ${slug})`,\n );\n return apiRequest<WorldDescription>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}`,\n );\n}\n","/**\n * JSON as the Python CLI sees it, so both CLIs write the same bytes.\n *\n * `JSON.parse` + `JSON.stringify` are not enough for parity with\n * `json.loads` + `json.dumps(separators=(\",\", \":\"), ensure_ascii=False)`:\n * JavaScript loses `1.0` vs `1` (Python keeps the float), rounds integers past\n * 2^53, moves integer-like keys to the front of an object, and spells\n * exponents differently (`1e-7` vs `1e-07`). Here a number keeps its source\n * text and its Python type, an object is a Map (insertion order, always), and\n * `dumps` renders exactly what CPython renders.\n */\n\nexport class JsonNumber {\n /** The lexeme as it appeared, e.g. \"1.0\", \"-0\", \"1e21\". */\n constructor(readonly text: string) {}\n /** A float in Python's eyes: a fraction, an exponent, or a non-finite literal. */\n get isFloat(): boolean {\n return /[.eE]/.test(this.text) || /[nN]/.test(this.text);\n }\n get value(): number {\n return Number(this.text);\n }\n}\n\nexport type JsonObject = Map<string, JsonValue>;\nexport type JsonValue = null | boolean | string | JsonNumber | JsonValue[] | JsonObject;\n\nexport class JsonSyntaxError extends Error {}\n\nexport const isObject = (value: JsonValue | undefined): value is JsonObject => value instanceof Map;\n\n// ------------------------------------------------------------------ parsing\n\n/** Parse one JSON text (a line, a row, a document) into the model above.\n * Accepts what `json.loads` accepts, including NaN/Infinity literals. */\nexport function parseJson(text: string): JsonValue {\n const p = new Parser(text);\n p.skipWs();\n const value = p.value();\n p.skipWs();\n if (p.i < text.length) throw new JsonSyntaxError(`Extra data at ${p.i}`);\n return value;\n}\n\nclass Parser {\n i = 0;\n constructor(readonly s: string) {}\n\n skipWs(): void {\n const s = this.s;\n while (this.i < s.length) {\n const c = s.charCodeAt(this.i);\n if (c === 0x20 || c === 0x0a || c === 0x0d || c === 0x09) this.i++;\n else break;\n }\n }\n\n fail(what: string): never {\n throw new JsonSyntaxError(`${what} at ${this.i}`);\n }\n\n value(): JsonValue {\n const s = this.s;\n if (this.i >= s.length) this.fail(\"Expecting value\");\n const c = s[this.i]!;\n if (c === \"{\") return this.object();\n if (c === \"[\") return this.array();\n if (c === '\"') return this.string();\n if (c === \"t\") return this.literal(\"true\", true);\n if (c === \"f\") return this.literal(\"false\", false);\n if (c === \"n\") return this.literal(\"null\", null);\n if (c === \"N\") return this.literal(\"NaN\", new JsonNumber(\"NaN\"));\n if (c === \"I\") return this.literal(\"Infinity\", new JsonNumber(\"Infinity\"));\n return this.number();\n }\n\n literal<T extends JsonValue>(word: string, value: T): T {\n if (!this.s.startsWith(word, this.i)) this.fail(\"Expecting value\");\n this.i += word.length;\n return value;\n }\n\n number(): JsonNumber {\n const s = this.s;\n const start = this.i;\n if (s[this.i] === \"-\") {\n this.i++;\n if (s.startsWith(\"Infinity\", this.i)) {\n this.i += 8;\n return new JsonNumber(\"-Infinity\");\n }\n }\n const intStart = this.i;\n if (s[this.i] === \"0\") this.i++;\n else {\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === intStart) this.fail(\"Expecting value\");\n }\n if (s[this.i] === \".\") {\n this.i++;\n const fracStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === fracStart) this.fail(\"Invalid number\");\n }\n if (s[this.i] === \"e\" || s[this.i] === \"E\") {\n this.i++;\n if (s[this.i] === \"+\" || s[this.i] === \"-\") this.i++;\n const expStart = this.i;\n while (this.i < s.length && isDigit(s.charCodeAt(this.i))) this.i++;\n if (this.i === expStart) this.fail(\"Invalid number\");\n }\n return new JsonNumber(s.slice(start, this.i));\n }\n\n string(): string {\n const s = this.s;\n this.i++; // opening quote\n let out = \"\";\n let runStart = this.i;\n for (;;) {\n if (this.i >= s.length) this.fail(\"Unterminated string\");\n const c = s.charCodeAt(this.i);\n if (c === 0x22) {\n out += s.slice(runStart, this.i);\n this.i++;\n return out;\n }\n if (c < 0x20) this.fail(\"Invalid control character\");\n if (c !== 0x5c) {\n this.i++;\n continue;\n }\n out += s.slice(runStart, this.i);\n this.i++;\n const e = s[this.i];\n switch (e) {\n case '\"':\n case \"\\\\\":\n case \"/\":\n out += e;\n break;\n case \"b\":\n out += \"\\b\";\n break;\n case \"f\":\n out += \"\\f\";\n break;\n case \"n\":\n out += \"\\n\";\n break;\n case \"r\":\n out += \"\\r\";\n break;\n case \"t\":\n out += \"\\t\";\n break;\n case \"u\": {\n const hex = s.slice(this.i + 1, this.i + 5);\n if (!/^[0-9a-fA-F]{4}$/.test(hex)) this.fail(\"Invalid \\\\u escape\");\n out += String.fromCharCode(parseInt(hex, 16));\n this.i += 4;\n break;\n }\n default:\n this.fail(\"Invalid escape\");\n }\n this.i++;\n runStart = this.i;\n }\n }\n\n array(): JsonValue[] {\n this.i++;\n const out: JsonValue[] = [];\n this.skipWs();\n if (this.s[this.i] === \"]\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n out.push(this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"]\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n\n object(): JsonObject {\n this.i++;\n const out: JsonObject = new Map();\n this.skipWs();\n if (this.s[this.i] === \"}\") {\n this.i++;\n return out;\n }\n for (;;) {\n this.skipWs();\n if (this.s[this.i] !== '\"') this.fail(\"Expecting property name enclosed in double quotes\");\n const key = this.string();\n this.skipWs();\n if (this.s[this.i] !== \":\") this.fail(\"Expecting ':' delimiter\");\n this.i++;\n this.skipWs();\n out.set(key, this.value());\n this.skipWs();\n const c = this.s[this.i];\n if (c === \",\") {\n this.i++;\n continue;\n }\n if (c === \"}\") {\n this.i++;\n return out;\n }\n this.fail(\"Expecting ',' delimiter\");\n }\n }\n}\n\nconst isDigit = (c: number): boolean => c >= 0x30 && c <= 0x39;\n\n// ------------------------------------------------------------ serialising\n\n/** `json.dumps(value, separators=(\",\", \":\"), ensure_ascii=False)`, byte for byte. */\nexport function dumps(value: JsonValue): string {\n if (value === null) return \"null\";\n if (value === true) return \"true\";\n if (value === false) return \"false\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (value instanceof JsonNumber) return numberText(value);\n if (Array.isArray(value)) return \"[\" + value.map(dumps).join(\",\") + \"]\";\n const parts: string[] = [];\n for (const [key, item] of value) parts.push(JSON.stringify(key) + \":\" + dumps(item));\n return \"{\" + parts.join(\",\") + \"}\";\n}\n\n/** How `json.dumps` spells a parsed number: ints verbatim (`-0` becomes `0`),\n * floats through `float.__repr__`, non-finite as NaN/Infinity. */\nexport function numberText(n: JsonNumber): string {\n if (!n.isFloat) return /^-0+$/.test(n.text) ? \"0\" : n.text;\n const value = n.value;\n if (Number.isNaN(value)) return \"NaN\";\n if (value === Infinity) return \"Infinity\";\n if (value === -Infinity) return \"-Infinity\";\n return pyFloatRepr(value);\n}\n\n/** `str(value)` for the values the redaction digest sees: str, int, float, bool. */\nexport function pyStr(value: string | boolean | JsonNumber): string {\n if (typeof value === \"string\") return value;\n if (typeof value === \"boolean\") return value ? \"True\" : \"False\";\n if (!value.isFloat) return numberText(value);\n const v = value.value;\n if (Number.isNaN(v)) return \"nan\";\n if (v === Infinity) return \"inf\";\n if (v === -Infinity) return \"-inf\";\n return pyFloatRepr(v);\n}\n\n/**\n * CPython's `repr(float)`: the shortest digits that round-trip (which\n * JavaScript's `String(x)` also produces), laid out Python's way — a\n * trailing `.0` on integral values, scientific notation only below 1e-4 or\n * from 1e16, and exponents of at least two digits with a sign.\n */\nexport function pyFloatRepr(x: number): string {\n if (x === 0) return Object.is(x, -0) ? \"-0.0\" : \"0.0\";\n const sign = x < 0 ? \"-\" : \"\";\n const js = String(Math.abs(x));\n const [mantissa, exponentPart] = js.split(\"e\");\n let exponent = exponentPart ? Number(exponentPart) : 0;\n const [intPart, fracPart = \"\"] = mantissa!.split(\".\");\n let digits = intPart! + fracPart;\n // decpt: how many digits sit before the decimal point (may be <= 0 or > length).\n let decpt = intPart!.length + exponent;\n const leading = digits.match(/^0*/)![0].length;\n digits = digits.slice(leading);\n decpt -= leading;\n digits = digits.replace(/0+$/, \"\");\n if (digits === \"\") return sign + \"0.0\";\n const sci = decpt - 1;\n if (sci >= -4 && sci < 16) {\n if (decpt <= 0) return sign + \"0.\" + \"0\".repeat(-decpt) + digits;\n if (decpt >= digits.length) return sign + digits + \"0\".repeat(decpt - digits.length) + \".0\";\n return sign + digits.slice(0, decpt) + \".\" + digits.slice(decpt);\n }\n exponent = sci;\n const mag = String(Math.abs(exponent)).padStart(2, \"0\");\n return sign + digits[0] + (digits.length > 1 ? \".\" + digits.slice(1) : \"\") + \"e\" + (exponent < 0 ? \"-\" : \"+\") + mag;\n}\n\n/**\n * Python's `round(x, ndigits)` for the redaction policy: an int is returned\n * unchanged, a float is correctly rounded on its exact binary value with ties\n * to even (`round(0.125, 2) == 0.12`), then re-read as the nearest double.\n */\nexport function pyRound(n: JsonNumber, ndigits: number): JsonNumber {\n if (!n.isFloat) return n;\n const x = n.value;\n if (!Number.isFinite(x)) return n;\n const sign = x < 0 ? -1 : 1;\n const magnitude = Math.abs(x);\n // Every double at or above 2^53 is an integer already.\n if (magnitude >= 9007199254740992) return new JsonNumber(pyFloatRepr(x));\n const { m, k } = exactFraction(magnitude); // magnitude = m / 2^k, m odd (or zero)\n let rounded: number;\n if (k <= ndigits) rounded = magnitude; // exact at this precision\n else if (k !== ndigits + 1) rounded = Number(magnitude.toFixed(ndigits)); // no tie possible: correctly rounded\n else {\n // Exactly k = ndigits + 1 fractional digits, the last one a 5: a tie. Half to even.\n const scaled = m * 5n ** BigInt(k); // magnitude * 10^k, an integer\n let kept = scaled / 10n; // magnitude * 10^ndigits, truncated\n if (kept % 2n === 1n) kept += 1n;\n const text = kept.toString().padStart(ndigits + 1, \"0\");\n rounded = ndigits === 0 ? Number(text) : Number(text.slice(0, -ndigits) + \".\" + text.slice(-ndigits));\n }\n return new JsonNumber(pyFloatRepr(sign * rounded));\n}\n\n/** A finite non-negative double as m / 2^k with m odd (m = 0, k = 0 for zero). */\nfunction exactFraction(x: number): { m: bigint; k: number } {\n if (x === 0) return { m: 0n, k: 0 };\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, x);\n const bits = view.getBigUint64(0);\n const exponent = Number((bits >> 52n) & 0x7ffn);\n let mantissa = bits & ((1n << 52n) - 1n);\n let e: number;\n if (exponent === 0) e = -1074;\n else {\n mantissa |= 1n << 52n;\n e = exponent - 1075;\n }\n while (mantissa !== 0n && (mantissa & 1n) === 0n) {\n mantissa >>= 1n;\n e += 1;\n }\n if (e >= 0) return { m: mantissa << BigInt(e), k: 0 };\n return { m: mantissa, k: -e };\n}\n","/**\n * Named plaintext transforms for cross-world entity mappings.\n *\n * A mapping between two worlds' fields is rarely a raw equality: SpyCloud\n * keeps `phone` as bare digits where a Torchlight client sends\n * `+1 (559) 779-1433`; one world keys people by `email`, another by\n * `email_username`. A transform normalises the plaintext on BOTH sides of a\n * mapping before `storedForms` salts it under each world's slug, so a\n * cross-world query is answerable from the plaintext alone, with no stored\n * join.\n *\n * The set is closed and named — no expressions, no user code — because any\n * client must reproduce a transform from the manifest by itself. This is the\n * TypeScript twin of the Python runtime's `environment/schema/transforms.py`;\n * the golden vectors in `__tests__/transforms.test.ts` and the Python\n * `tests/environment/test_schema_transforms.py` pin the two to each other,\n * byte for byte.\n *\n * Whitespace, for `trim` and `collapse_ws`, is the ASCII set `\" \\t\\n\\r\\f\\v\"`\n * by definition (Python's `str.split()` and JavaScript's `\\s` disagree at the\n * edges of Unicode; `nfkc` first folds a no-break space into a plain one).\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { pyFloatRepr } from \"../cli/platform/worldData/json\";\n\nexport type Transform = (value: string) => string;\n\nexport const WHITESPACE = \" \\t\\n\\r\\f\\v\";\nconst WHITESPACE_EDGES = /^[ \\t\\n\\r\\f\\v]+|[ \\t\\n\\r\\f\\v]+$/g;\nconst WHITESPACE_RUN = /[ \\t\\n\\r\\f\\v]+/g;\nconst NOT_DIGIT = /[^0-9]/g;\n\nexport const STRIP_PREFIX = \"strip_prefix\";\n\nconst trim = (value: string): string => value.replace(WHITESPACE_EDGES, \"\");\n\nconst emailLocalPart = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? value : value.slice(0, at);\n};\n\nconst emailDomain = (value: string): string => {\n const at = value.lastIndexOf(\"@\");\n return at === -1 ? \"\" : value.slice(at + 1).toLowerCase();\n};\n\nconst stripPrefix =\n (prefix: string): Transform =>\n (value) =>\n value.startsWith(prefix) ? value.slice(prefix.length) : value;\n\nconst hex = (algorithm: \"sha1\" | \"sha256\", value: string): string =>\n createHash(algorithm).update(value, \"utf8\").digest(\"hex\");\n\nconst SIMPLE: Record<string, Transform> = {\n lower: (value) => value.toLowerCase(),\n upper: (value) => value.toUpperCase(),\n trim,\n collapse_ws: (value) => trim(value).replace(WHITESPACE_RUN, \" \"),\n nfkc: (value) => value.normalize(\"NFKC\"),\n digits: (value) => value.replace(NOT_DIGIT, \"\"),\n email_local_part: emailLocalPart,\n email_domain: emailDomain,\n // Vendor-style digests: lowercase hex of the utf-8 bytes, unsalted. This is\n // how SpyCloud accepts a hashed selector (`_digests` in its api_handlers).\n sha1: (value) => hex(\"sha1\", value),\n sha256: (value) => hex(\"sha256\", value),\n};\n\n/** The closed set, as a manifest spells it. `strip_prefix` takes its parameter\n * after a colon; the parameter may hold any character but `,`. */\nexport const TRANSFORMS: readonly string[] = [...Object.keys(SIMPLE), `${STRIP_PREFIX}:<prefix>`];\n\n/** The function a transform name denotes; throws when the name is not in the set. */\nexport function parseTransform(name: string): Transform {\n const simple = Object.prototype.hasOwnProperty.call(SIMPLE, name) ? SIMPLE[name] : undefined;\n if (simple) return simple;\n const colon = name.indexOf(\":\");\n if (colon !== -1) {\n const head = name.slice(0, colon);\n const prefix = name.slice(colon + 1);\n if (head === STRIP_PREFIX && prefix && !prefix.includes(\",\")) return stripPrefix(prefix);\n }\n throw new Error(`Unknown transform '${name}'; choose one of ${TRANSFORMS.join(\", \")}`);\n}\n\n/** `str(value)` as the Python runtime spells a number: an integral number is an\n * int, any other its float repr. */\nconst text = (value: string | number): string => {\n if (typeof value === \"string\") return value;\n return Number.isInteger(value) ? String(value) : pyFloatRepr(value);\n};\n\n/**\n * Compose `chain` left to right over `value`.\n *\n * A number is written as Python's `str()` first, the way `_digest` salts one,\n * so a number keyed on one side and a string on the other transform alike. The\n * whole chain is parsed before any step runs: a bad name at the end refuses\n * the mapping outright rather than after a partial result. An empty chain is\n * the identity.\n */\nexport function applyTransforms(value: string | number, chain: readonly string[]): string {\n const steps = chain.map(parseTransform);\n let out = text(value);\n for (const step of steps) out = step(out);\n return out;\n}\n","/**\n * Stored forms: what a world's store holds for a field given its plaintext.\n *\n * A schema world's `[redact]` table (connector.toml) rewrites named fields\n * before they reach disk — `hash` to a slug-salted sha256, `preserve` to a\n * shape-preserving digest, `round` to fewer decimals, `drop` to nothing. A\n * lookup by plaintext therefore has to compute the same form the store did.\n * This module is the TypeScript twin of the Python runtime's `_digest`,\n * `_shaped`, `redaction_of` and `stored_forms` (environment/schema/connector.py):\n * the rule is `\"sha256:\" + sha256(\"<slug>:<plaintext>\")`, no lowercasing, no\n * trimming, no other salt, and the golden vectors in redaction.test.ts pin the\n * two implementations to each other.\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { JsonNumber, pyFloatRepr, pyRound } from \"../cli/platform/worldData/json\";\nimport { applyTransforms } from \"./transforms\";\n\n/** The `[redact]` table as `describe` reports it (`connection.redact`, and\n * `redact` on `GET /api/public/worlds/{slug}`). */\nexport type RedactPolicy = {\n /** The digest salt: the connector's slug from connector.toml. It can differ\n * from the platform world slug (`spycloud` vs `spycloud-world`); `storedForms`\n * prefers it and falls back to the world slug only when it is absent. */\n slug?: string;\n hash: string[];\n drop: string[];\n preserve: string[];\n round: Record<string, number>;\n};\n\n/** The policy one field is stored under; null when it is stored in the clear. */\nexport type Redaction = \"hash\" | \"drop\" | \"preserve\" | `round:${number}`;\n\n/**\n * A value as the Python runtime would see it. JavaScript has one number\n * type, so an integral number takes Python's `int` path and any other number\n * its `float` path (`100` is `100`, never `100.0`); integers stay exact within\n * the safe range only.\n */\nexport type Plaintext = string | number;\n\nconst isInt = (value: Plaintext): value is number => typeof value === \"number\" && Number.isInteger(value);\n\n/** `str(value)` for an int or str, `repr(value)` for a float — the text the\n * Python runtime salts and shapes. */\nexport function pyText(value: Plaintext): string {\n if (typeof value === \"string\") return value;\n if (Number.isInteger(value)) return String(value);\n if (Number.isNaN(value)) return \"nan\";\n if (!Number.isFinite(value)) return value > 0 ? \"inf\" : \"-inf\";\n return pyFloatRepr(value);\n}\n\n/** The `hash` form: `\"sha256:\" + sha256(\"<slug>:<plaintext>\")` as hex. */\nexport function hashForm(slug: string, plaintext: Plaintext): string {\n return \"sha256:\" + createHash(\"sha256\").update(`${slug}:${pyText(plaintext)}`, \"utf8\").digest(\"hex\");\n}\n\n/**\n * The `preserve` form, the Python `_shaped`: the same length, every ASCII\n * digit still a digit, every ASCII letter still a letter of the same case,\n * everything else (separators, punctuation, non-ASCII) left in place. The\n * bytes come from sha256 of the seed `\"<slug>:<text>\"`, re-keyed as\n * sha256(digest + seed) once the 32 bytes are spent. A number keeps its type:\n * an int keeps its digit count (a leading zero is replaced), a float is re-read.\n */\nexport function preserveForm(slug: string, plaintext: Plaintext): Plaintext {\n const kind = typeof plaintext === \"string\" ? \"str\" : isInt(plaintext) ? \"int\" : \"float\";\n const shaped = shapeText(slug, pyText(plaintext), kind);\n return kind === \"str\" ? shaped : Number(shaped);\n}\n\n/** The shaping itself, on text: `kind` says which of Python's rules apply\n * (letters are re-lettered for a str only; an int keeps its digit count). */\nexport function shapeText(slug: string, text: string, kind: \"str\" | \"int\" | \"float\"): string {\n const seed = Buffer.from(`${slug}:${text}`, \"utf8\");\n let digest = createHash(\"sha256\").update(seed).digest();\n let cursor = 0;\n const out: string[] = [];\n for (const char of text) {\n if (cursor === digest.length) {\n digest = createHash(\"sha256\").update(Buffer.concat([digest, seed])).digest();\n cursor = 0;\n }\n const byte = digest[cursor]!;\n cursor += 1;\n if (char >= \"0\" && char <= \"9\") out.push(String(byte % 10));\n else if (kind === \"str\" && char >= \"a\" && char <= \"z\") out.push(String.fromCharCode(97 + (byte % 26)));\n else if (kind === \"str\" && char >= \"A\" && char <= \"Z\") out.push(String.fromCharCode(65 + (byte % 26)));\n else out.push(char);\n }\n // An int keeps its digit count; int() would drop a leading zero.\n if (kind === \"int\" && out.length > 1 && out[0] === \"0\") out[0] = String(1 + (digest[0]! % 9));\n return out.join(\"\");\n}\n\n/** The `round` form: Python's `round(value, decimals)` — an int unchanged, a\n * float correctly rounded with ties to even; a string is not a number and\n * passes through as the runtime leaves it. */\nexport function roundForm(plaintext: Plaintext, decimals: number): Plaintext {\n if (typeof plaintext === \"string\" || isInt(plaintext) || !Number.isFinite(plaintext)) return plaintext;\n return pyRound(new JsonNumber(pyFloatRepr(plaintext)), decimals).value;\n}\n\n/**\n * The policy a field of this name falls under, ranked as the runtime applies\n * them (drop, hash, preserve, round). Read without a path: a bare name in the\n * table counts, and so does a dotted path whose last segment is the field.\n */\nexport function redactionOf(redact: RedactPolicy | null | undefined, field: string): Redaction | null {\n if (!redact) return null;\n const named = (names: string[] | undefined) =>\n (names ?? []).some((name) => name === field || name.slice(name.lastIndexOf(\".\") + 1) === field);\n if (named(redact.drop)) return \"drop\";\n if (named(redact.hash)) return \"hash\";\n if (named(redact.preserve)) return \"preserve\";\n const decimals = redact.round?.[field];\n if (typeof decimals === \"number\") return `round:${decimals}`;\n return null;\n}\n\n/**\n * Every value the store may hold for `field` given this plaintext:\n *\n * clear field -> [plaintext]\n * hash -> [\"sha256:<hex>\"]\n * preserve -> [the shape-preserving digest]\n * round -> [round(plaintext, decimals)] for a number, [plaintext] otherwise\n * drop -> [] (the field is not on disk: a documented miss, not an error)\n *\n * `world` is what `describeWorld` / the bridge's `describe` return: the slug\n * is the salt, `redact` the table.\n *\n * `transform` — a cross-world mapping's chain (`./transforms`) — runs over the\n * plaintext FIRST, so `hash` and `preserve` salt the normalised text; omitted\n * (or empty) is today's behaviour, byte for byte.\n */\nexport function storedForms(\n world: { slug: string; redact?: RedactPolicy | null },\n field: string,\n plaintext: Plaintext,\n transform?: readonly string[],\n): Plaintext[] {\n if (transform?.length) plaintext = applyTransforms(plaintext, transform);\n const policy = redactionOf(world.redact, field);\n const salt = world.redact?.slug ?? world.slug;\n if (policy === \"drop\") return [];\n if (policy === \"hash\") return [hashForm(salt, plaintext)];\n if (policy === \"preserve\") return [preserveForm(salt, plaintext)];\n if (policy !== null) return [roundForm(plaintext, world.redact!.round[field]!)];\n return [plaintext];\n}\n","/**\n * `queryRows(slug, entity, {where, resolve, limit, offset})` — the rows of\n * one entity that match a predicate, from\n * `GET /api/public/worlds/{slug}/data?entity=&where=&limit=&offset=&resolve=`.\n * `where` is field → value, or field → list of values (any of); values match\n * the STORED form as given. With `resolve: true` the values are plaintext and\n * the runtime maps each to its stored form under the world's `[redact]`\n * policy first (a hashed `email` becomes its slug-salted digest; a dropped\n * field resolves to nothing and matches no row — the answer's `resolved`\n * says so). The CLI twin is `gateway worlds data query <slug> <entity>`.\n *\n * `across: true` runs the same plaintext in every world this one links to\n * whose `[dependencies.<alias>.entities]` mapping covers a `where` field;\n * each linked world recomputes its own stored form (after the mapping's\n * transform) at query time — no join on disk, no shared salt. The answer\n * is then {@link WorldQueryAcrossResult}: one group per world, the root\n * first, and with `compare: true` a parity report saying, per field and\n * per world, `matched`, `no match` or `unmapped`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\nimport type { Plaintext } from \"./redaction\";\n\nexport type WorldQueryWhere = Record<string, Plaintext | Plaintext[]>;\n\nexport type WorldQueryOptions = {\n where?: WorldQueryWhere;\n /** The `where` values are plaintext: resolve each to its stored form before matching. */\n resolve?: boolean;\n limit?: number;\n offset?: number;\n /** Query the linked worlds too; the answer becomes groups. */\n across?: boolean;\n /** With `across`: add the parity report. */\n compare?: boolean;\n};\n\n/** The options that make `queryRows` answer {@link WorldQueryAcrossResult}. */\nexport type WorldQueryAcrossOptions = WorldQueryOptions & { across: true };\n\nexport type WorldQueryResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n rows: Record<string, unknown>[];\n /** Rows in this page. */\n count: number;\n /** Rows matching in all; null when the store does not count them. */\n total: number | null;\n limit: number;\n offset: number;\n /** With `resolve`: the stored forms each `where` field was matched against\n * (`[]` for a dropped field, which is why such a query matches nothing). */\n resolved?: Record<string, Plaintext[]>;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\nexport type WorldQuerySnapshot = {\n snapshotId: string;\n contractHash: string;\n batchDigest: string;\n bytes: number;\n};\n\n/** One world's page inside an across answer: the root (`alias: null`, no\n * `mapping`) or a linked world with the mappings that carried the root's\n * `where` fields into its own entity. */\nexport type WorldQueryGroup = {\n world: { slug: string; alias: string | null; versionId: string };\n entity: string;\n rows: Record<string, unknown>[];\n count: number;\n total: number | null;\n limit: number;\n offset: number;\n resolved?: Record<string, Plaintext[]>;\n mapping?: { field: string; depField: string; transform: string[] }[];\n};\n\nexport type WorldQueryCompareStatus = \"matched\" | \"no match\" | \"unmapped\";\n\n/** Per `where` field, per world: whether the field reached the world and\n * whether any row matched there; `present`/`absent` list the worlds by slug. */\nexport type WorldQueryCompare = {\n present: string[];\n absent: string[];\n perField: {\n field: string;\n worlds: {\n world: string;\n alias: string | null;\n status: WorldQueryCompareStatus;\n /** `<depEntity>.<depField>` and the transform applied (mapped worlds only). */\n depField?: string;\n transform?: string[];\n }[];\n }[];\n};\n\nexport type WorldQueryAcrossResult = {\n slug: string;\n versionId: string;\n kind: string | null;\n entity: string;\n /** The root world first, then one per linked world that was queried. */\n groups: WorldQueryGroup[];\n compare?: WorldQueryCompare;\n entityCounts: Record<string, number>;\n snapshot: WorldQuerySnapshot | null;\n};\n\n/** The query string the route reads; `where` travels as URL-encoded JSON. */\nexport function queryRowsSearch(entity: string, opts: WorldQueryOptions = {}): string {\n const search = new URLSearchParams();\n search.set(\"entity\", entity);\n if (opts.where && Object.keys(opts.where).length) search.set(\"where\", JSON.stringify(opts.where));\n if (opts.limit !== undefined) search.set(\"limit\", String(opts.limit));\n if (opts.offset !== undefined) search.set(\"offset\", String(opts.offset));\n if (opts.resolve) search.set(\"resolve\", \"true\");\n if (opts.across) search.set(\"across\", \"true\");\n if (opts.compare) search.set(\"compare\", \"true\");\n return `?${search.toString()}`;\n}\n\n/** The world's head version, queried. The route reads the head only, so a\n * `slug@ref` is refused rather than silently served as the head. With\n * `across: true` the answer is the groups shape. */\nexport async function queryRows(\n slug: string,\n entity: string,\n opts: WorldQueryAcrossOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryAcrossResult>;\nexport async function queryRows(\n slug: string,\n entity: string,\n opts?: WorldQueryOptions,\n options?: WorldsClientOptions,\n): Promise<WorldQueryResult>;\nexport async function queryRows(\n slug: string,\n entity: string,\n opts: WorldQueryOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldQueryResult | WorldQueryAcrossResult> {\n if (slug.includes(\"@\"))\n throw new Error(\n `queryRows reads a world's head version: pass the slug without @ref (got ${slug})`,\n );\n if (!entity) throw new Error(\"queryRows needs an entity\");\n if (opts.compare && !opts.across) throw new Error(\"queryRows: compare needs across\");\n return apiRequest<WorldQueryResult | WorldQueryAcrossResult>(\n options,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}/data${queryRowsSearch(entity, opts)}`,\n );\n}\n","/**\n * `migrateWorld(slug)` — convert a stored world into a schema world, from\n * `POST /api/public/worlds/{slug}/migrate`; `migrateProjectWorlds()` plans\n * (or migrates) every connector world in the project from\n * `POST /api/public/worlds/migrate`. Dry run by default: the report says\n * what the version is, what the conversion does, or why it cannot; `apply`\n * commits the migrated tree as the next version (\"Migrated to a schema\n * world\"). Targets are the platform's connector worlds; a hand-built world\n * needs `force`. The CLI twin is `gateway worlds migrate`.\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport type WorldMigrationRefusal = {\n code: string;\n message: string;\n /** Paths the conversion needed and did not find. */\n missing: string[];\n};\n\nexport type WorldMigrationReport = {\n slug: string;\n containerId: string;\n versionId: string;\n /** True when the container was created from a connector template. */\n connectorWorld: boolean;\n /** schema | api-bundle | legacy-tools | harbor | verifiers */\n shape: string;\n target: \"schema\";\n /** True when the world already is a schema world. */\n unchanged: boolean;\n /** The dry-run report, one sentence each. */\n actions: string[];\n /** Files the migrated tree holds; 0 on a refusal. */\n files: number;\n refusal: WorldMigrationRefusal | null;\n /** True when this call committed the migrated tree. */\n applied: boolean;\n version: { id: string; contentHash: string } | null;\n};\n\nexport type MigrateWorldOptions = {\n /** Commit the migrated tree as the next version. Default false: dry run. */\n apply?: boolean;\n /** Migrate a world that was not created from a connector template. */\n force?: boolean;\n};\n\nexport async function migrateWorld(\n slug: string,\n input: MigrateWorldOptions = {},\n options: WorldsClientOptions = {},\n): Promise<WorldMigrationReport> {\n if (slug.includes(\"@\"))\n throw new Error(\n `migrateWorld converts a world's head version: pass the slug without @ref (got ${slug})`,\n );\n return apiRequest<WorldMigrationReport>(\n options,\n \"POST\",\n `/api/public/worlds/${encodeURIComponent(slug)}/migrate`,\n {\n ...(input.apply === undefined ? {} : { apply: input.apply }),\n ...(input.force === undefined ? {} : { force: input.force }),\n },\n );\n}\n\n/** Every connector world in the project, one report each. */\nexport async function migrateProjectWorlds(\n input: { apply?: boolean } = {},\n options: WorldsClientOptions = {},\n): Promise<{ worlds: WorldMigrationReport[]; applied: boolean }> {\n return apiRequest<{ worlds: WorldMigrationReport[]; applied: boolean }>(\n options,\n \"POST\",\n \"/api/public/worlds/migrate\",\n input.apply === undefined ? {} : { apply: input.apply },\n );\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { Credentials } from \"../config\";\nimport { CliError } from \"../router\";\nimport type { WorldQueryAcrossResult } from \"../../worlds/query\";\nimport {\n BridgeRejected,\n detailFrom,\n readWorldFiles,\n runtime,\n writeWorldFiles,\n type WorldFile,\n} from \"./client\";\nimport { localBridge, localRuntime, localRuntimeReason } from \"./local\";\n\n/**\n * Rows into, and counts out of, a world that lives in a LOCAL directory. The\n * `worlds data import|show` commands (registered by the platform track) call\n * these two for the directory case; a slug goes to the platform's world data\n * routes instead. The gate is the world's own contract, run by the platform\n * runtime: a bad row is refused with the field named and nothing is written.\n */\n\nexport type Rows = Record<string, Record<string, unknown>[]>;\nexport type ImportMode = \"append\" | \"replace\";\n\nexport type LocalImportResult = {\n kind: string;\n entity_counts: Record<string, number>;\n changed: boolean;\n};\n\nexport async function importLocalWorldData(\n dir: string,\n rows: Rows,\n opts: { mode?: ImportMode; redact?: \"off\" | \"apply\" | \"refuse\" },\n creds: Credentials | null,\n): Promise<LocalImportResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n changed?: boolean;\n files?: WorldFile[];\n }>(creds, {\n command: \"import-data\",\n files: readWorldFiles(dir),\n rows,\n mode: opts.mode ?? \"append\",\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n });\n if (res.files?.length) writeWorldFiles(dir, res.files);\n // Snapshots are build outputs, not tree files: the runtime answers without\n // them, and the ones on disk were built from the journals BEFORE this import.\n // A served world ignores a stale snapshot and replays the journals, but the\n // files would still sit there claiming an older state — drop them, and let\n // `worlds schema compile` build them again from the data that is there now.\n if (res.changed) dropBuildOutputs(dir);\n return {\n kind: res.kind ?? \"unknown\",\n entity_counts: res.entity_counts ?? {},\n changed: Boolean(res.changed),\n };\n}\n\nconst BUILD_OUTPUT = /(^|\\/)state\\.(sqlite|json)$/;\n\n/** Remove the compiled snapshots (`db/state.*`, `scenarios/<name>/state.*`)\n * that no longer match the tree's journals. */\nexport function dropBuildOutputs(dir: string): string[] {\n const dropped: string[] = [];\n for (const file of readWorldFiles(dir, { buildOutputs: true })) {\n if (!BUILD_OUTPUT.test(file.path)) continue;\n fs.rmSync(path.join(dir, file.path), { force: true });\n dropped.push(file.path);\n }\n return dropped;\n}\n\n/**\n * The same bridge import over the tree, with the answered files discarded:\n * the rows are checked through the world's contract and nothing on disk\n * changes. A refused row surfaces as a BridgeRejected, as an import would.\n */\nexport async function checkLocalWorldData(\n dir: string,\n rows: Rows,\n creds: Credentials | null,\n opts: { redact?: \"off\" | \"apply\" | \"refuse\" } = {},\n): Promise<LocalImportResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n changed?: boolean;\n }>(creds, {\n command: \"import-data\",\n files: readWorldFiles(dir),\n rows,\n mode: \"append\",\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n });\n return {\n kind: res.kind ?? \"unknown\",\n entity_counts: res.entity_counts ?? {},\n changed: Boolean(res.changed),\n };\n}\n\nexport type LocalShowResult = {\n kind: string;\n entity_counts?: Record<string, number>;\n entity?: string;\n rows?: Record<string, unknown>[];\n};\n\nexport async function showLocalWorldData(\n dir: string,\n entity: string | undefined,\n creds: Credentials | null,\n): Promise<LocalShowResult> {\n const res = await runtime<{\n kind?: string;\n entity_counts?: Record<string, number>;\n rows?: Record<string, unknown>[];\n }>(creds, {\n command: \"counts\",\n files: readWorldFiles(dir),\n ...(entity ? { entity } : {}),\n });\n const out: LocalShowResult = { kind: res.kind ?? \"unknown\" };\n if (entity) {\n out.entity = entity;\n out.rows = res.rows ?? [];\n } else out.entity_counts = res.entity_counts ?? {};\n return out;\n}\n\n/** field → stored value, or a list of them (any of). */\nexport type LocalQueryWhere = Record<string, string | string[]>;\n\nexport type LocalQueryOptions = {\n /** The `where` values are plaintext: the runtime resolves each to its stored form first. */\n resolve?: boolean;\n limit?: number;\n offset?: number;\n /** Read the rows a session opened in this scenario starts from (schema worlds). */\n scenario?: string;\n};\n\nexport type LocalQueryResult = {\n kind?: string;\n entity: string;\n scenario?: string;\n rows: Record<string, unknown>[];\n count: number;\n total: number | null;\n limit: number;\n offset: number;\n /** With `resolve`: the stored forms each field was matched against (`[]` for a dropped field). */\n resolved?: Record<string, (string | number)[]>;\n};\n\n/**\n * The bridge's `query` over the tree: one entity's rows matching `where`.\n * A refused query (unknown entity or field) surfaces as a BridgeRejected.\n */\nexport async function queryLocalWorldData(\n dir: string,\n entity: string,\n where: LocalQueryWhere,\n opts: LocalQueryOptions,\n creds: Credentials | null,\n): Promise<LocalQueryResult> {\n const res = await runtime<{\n kind?: string;\n entity?: string;\n rows?: Record<string, unknown>[];\n count?: number;\n total?: number | null;\n limit?: number;\n offset?: number;\n scenario?: string;\n resolved?: Record<string, (string | number)[]>;\n }>(creds, {\n command: \"query\",\n files: readWorldFiles(dir),\n entity,\n ...(Object.keys(where).length ? { where } : {}),\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.offset !== undefined ? { offset: opts.offset } : {}),\n ...(opts.resolve ? { resolve: true } : {}),\n ...(opts.scenario ? { scenario: opts.scenario } : {}),\n });\n const rows = res.rows ?? [];\n return {\n ...(res.kind ? { kind: res.kind } : {}),\n entity: res.entity ?? entity,\n ...(res.scenario ? { scenario: res.scenario } : {}),\n rows,\n count: res.count ?? rows.length,\n total: res.total ?? null,\n limit: res.limit ?? opts.limit ?? rows.length,\n offset: res.offset ?? opts.offset ?? 0,\n ...(res.resolved ? { resolved: res.resolved } : {}),\n };\n}\n\n/** A local across answer: the platform's groups, each world named by its\n * manifest name (the root) or its pin's slug (a dependency); no version ids,\n * since the trees are read where they sit. */\nexport type LocalQueryAcrossResult = {\n kind?: string;\n entity: string;\n groups: (Omit<WorldQueryAcrossResult[\"groups\"][number], \"world\"> & { world: { slug: string; alias: string | null } })[];\n compare?: WorldQueryAcrossResult[\"compare\"];\n};\n\n/**\n * The bridge's `query` with `across` over the tree in place: the root's rows\n * and, per `[dependencies.<alias>.entities]` mapping that carries a `where`\n * field, the linked world's, read at its `path`. Needs the bundled runtime on\n * this machine, as the paths beside the tree must resolve.\n */\nexport async function queryLocalWorldDataAcross(\n dir: string,\n entity: string,\n where: LocalQueryWhere,\n opts: LocalQueryOptions & { compare?: boolean },\n): Promise<LocalQueryAcrossResult> {\n const local = localRuntime();\n if (!local)\n throw new CliError(\n \"`--across` on a directory reads the linked worlds at their paths, so it needs the bundled runtime on this machine. \" +\n localRuntimeReason(),\n 1,\n );\n const payload = await localBridge<Record<string, unknown>>(\n {\n command: \"query\",\n world: path.resolve(dir),\n entity,\n across: true,\n ...(opts.compare ? { compare: true } : {}),\n ...(Object.keys(where).length ? { where } : {}),\n ...(opts.limit !== undefined ? { limit: opts.limit } : {}),\n ...(opts.offset !== undefined ? { offset: opts.offset } : {}),\n ...(opts.resolve ? { resolve: true } : {}),\n ...(opts.scenario ? { scenario: opts.scenario } : {}),\n },\n local,\n );\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n return payload as unknown as LocalQueryAcrossResult;\n}\n\n// ---------------------------------------------------------------- tool calls\n\nexport type LocalIngestRefusal = { index: number | null; tool: string | null; reason: string; pointer?: string };\n\n/** One `[[sources]]` of a mapping in the report: what it saw and what it did not touch. */\nexport type LocalIngestSource = {\n name: string;\n kind: string;\n select: string;\n entity: string;\n records: number;\n items: number;\n rows: Record<string, number>;\n /** Source fields no line of the source reads, with a sample value. */\n unmapped_fields: Record<string, string>;\n /** Entity fields the source never sets, per entity it lands in. */\n unset_fields: Record<string, string[]>;\n};\n\n/** The bridge's `ingest-calls` report (the Python `ingest.ingest_records`). */\nexport type LocalIngestResult = {\n /** How the rows were produced: a declared mapping, the operations' projection, or rows as given. */\n via?: \"map\" | \"operations\" | \"rows\" | \"transform\";\n records: number;\n ingested: number;\n skipped: Record<string, number>;\n refusals: LocalIngestRefusal[];\n rows: Record<string, number>;\n /** The projected rows themselves, as the tools returned them (before any redaction). */\n projected?: Rows;\n /** `via: \"map\"`: each source's accounting. */\n sources?: LocalIngestSource[];\n /** `via: \"map\"` with `unmatched = \"skip\"`: records no source claimed, by tool name. */\n unmatched?: Record<string, number>;\n /** `via: \"operations\"`: that the rows came through the operation projection, not a mapping. */\n note?: string;\n dry_run: boolean;\n redact: \"off\" | \"apply\" | \"refuse\";\n changed: boolean;\n kind?: string;\n entity_counts?: Record<string, number>;\n batch?: string | null;\n};\n\n/**\n * Tool-call records into a world in a LOCAL directory, through the runtime's\n * `ingest-calls`: each record's tool resolves to an operation of the world's\n * `connector.toml`, its result goes through that operation's projection the\n * way a capture does, and the rows through the world's contract. An unknown\n * tool is a refusal in the report (nothing written); a row the contract\n * refuses surfaces as a BridgeRejected, as an import would. Redaction is\n * optional and off by default. With `dryRun` the tree is untouched.\n */\nexport async function ingestLocalToolCalls(\n dir: string,\n records: unknown[],\n opts: { redact?: \"off\" | \"apply\" | \"refuse\"; dryRun?: boolean; mode?: ImportMode; map?: string | Record<string, unknown> },\n creds: Credentials | null,\n): Promise<LocalIngestResult> {\n const res = await runtime<Partial<LocalIngestResult> & { files?: WorldFile[] }>(creds, {\n command: \"ingest-calls\",\n files: readWorldFiles(dir),\n records,\n mode: opts.mode ?? \"append\",\n ...(opts.dryRun ? { dry_run: true } : {}),\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n ...(opts.map !== undefined ? { map: opts.map } : {}),\n });\n if (!opts.dryRun && res.files?.length) writeWorldFiles(dir, res.files);\n if (res.changed) dropBuildOutputs(dir);\n return {\n ...(res.via ? { via: res.via } : {}),\n ...(res.sources ? { sources: res.sources } : {}),\n ...(res.unmatched ? { unmatched: res.unmatched } : {}),\n ...(res.note ? { note: res.note } : {}),\n records: res.records ?? records.length,\n ingested: res.ingested ?? 0,\n skipped: res.skipped ?? {},\n refusals: res.refusals ?? [],\n rows: res.rows ?? {},\n ...(res.projected ? { projected: res.projected } : {}),\n dry_run: Boolean(res.dry_run ?? opts.dryRun),\n redact: res.redact ?? opts.redact ?? \"off\",\n changed: Boolean(res.changed),\n ...(res.kind ? { kind: res.kind } : {}),\n ...(res.entity_counts ? { entity_counts: res.entity_counts } : {}),\n ...(res.batch !== undefined ? { batch: res.batch } : {}),\n };\n}\n","import { spawn } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { createRequire } from \"node:module\";\n\nimport { CliError } from \"../../router\";\nimport type { Rows } from \"../rows\";\n\n/**\n * `--transform`: the agent's own code turns records into rows (the Python\n * `schema.transform`, wrapper for wrapper). A script — `.py`, or `.ts` /\n * `.mjs` / `.js` / `.cjs` for node — either exports `transform(records) ->\n * {entity: [rows]}` (node: `transform` or the default export) or reads the\n * records as JSONL on stdin and prints the rows document on stdout.\n *\n * The script runs in a subprocess with a time limit, its stderr passed\n * through. The wrapper disables sockets (Python) and `net`/`tls`/`http`/\n * `dgram`/`fetch` (node) before the script loads, and the child gets no\n * `GATEWAY_*` or proxy variables. That is a guard, not a sandbox: a\n * transform is the agent's own code, run on the agent's own machine.\n */\n\nexport const DEFAULT_TRANSFORM_TIMEOUT_MS = 120_000;\nexport const NODE_SUFFIXES = [\".ts\", \".mts\", \".mjs\", \".js\", \".cjs\"];\nexport const PYTHON_SUFFIXES = [\".py\"];\nconst SCRUBBED = /^(GATEWAY_|HTTPS?_PROXY$|ALL_PROXY$|https?_proxy$|all_proxy$)/;\n\nexport const PY_WRAPPER = `\nimport io, json, runpy, socket, sys\n\ndef _deny(*args, **kwargs):\n raise RuntimeError(\"network is disabled in a transform\")\n\nclass _Denied(socket.socket):\n def __init__(self, *args, **kwargs):\n _deny()\n\nsocket.socket = _Denied\nsocket.SocketType = _Denied\nsocket.create_connection = _deny\nsocket.getaddrinfo = _deny\n\ntext = sys.stdin.read()\nrecords = [json.loads(line) for line in text.splitlines() if line.strip()]\nsys.stdin = io.StringIO(text)\ncaptured = io.StringIO()\nreal = sys.stdout\nsys.stdout = captured\ntry:\n namespace = runpy.run_path(sys.argv[1], run_name=\"__main__\")\nfinally:\n sys.stdout = real\nfn = namespace.get(\"transform\")\nif callable(fn):\n out = fn(records)\nelse:\n printed = captured.getvalue().strip()\n if not printed:\n sys.stderr.write(\"the transform defines no transform(records) and printed nothing\\\\n\")\n sys.exit(3)\n out = json.loads(printed)\nreal.write(json.dumps(out))\n`;\n\nexport const NODE_WRAPPER = `\nimport { pathToFileURL } from \"node:url\";\nimport net from \"node:net\";\nimport tls from \"node:tls\";\nimport http from \"node:http\";\nimport https from \"node:https\";\nimport dgram from \"node:dgram\";\n\nconst deny = () => { throw new Error(\"network is disabled in a transform\"); };\nnet.Socket.prototype.connect = deny;\nnet.connect = deny;\nnet.createConnection = deny;\ntls.connect = deny;\nhttp.request = deny;\nhttp.get = deny;\nhttps.request = deny;\nhttps.get = deny;\ndgram.createSocket = deny;\nglobalThis.fetch = deny;\n\nconst module = await import(pathToFileURL(process.argv[2]).href);\nconst fn = typeof module.transform === \"function\" ? module.transform : typeof module.default === \"function\" ? module.default : null;\nif (fn) {\n const chunks = [];\n for await (const chunk of process.stdin) chunks.push(chunk);\n const text = Buffer.concat(chunks).toString(\"utf8\");\n const records = text.split(\"\\\\n\").filter((line) => line.trim()).map((line) => JSON.parse(line));\n const out = await fn(records);\n process.stdout.write(JSON.stringify(out));\n}\n`;\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** `value` as the rows document `{entity: [rows]}`, or a CliError saying what shape it has instead. */\nexport function checkRows(value: unknown, where: string): Rows {\n if (!isObject(value)) throw new CliError(`${where} must return {entity: [rows]}; got ${value === null ? \"null\" : Array.isArray(value) ? \"an array\" : typeof value}`, 1);\n for (const [entity, listed] of Object.entries(value)) {\n if (!Array.isArray(listed)) throw new CliError(`${where}: ${entity} must be a list of rows; got ${listed === null ? \"null\" : typeof listed}`, 1);\n listed.forEach((row, index) => {\n if (!isObject(row)) throw new CliError(`${where}: ${entity}[${index}] is not an object`, 1);\n });\n }\n return value as Rows;\n}\n\n/**\n * How this node runs a `.ts` transform: built-in type stripping from Node\n * 22.6 on; before that, the `tsx` command-line entry when tsx is installed\n * beside the CLI (a dev dependency here, present on CI's Node 20); otherwise\n * a refusal that names both options instead of a stack trace from node.\n * Returns the argv prefix that goes in front of the wrapper.\n */\nfunction typescriptPrefix(): string[] {\n const [major, minor] = process.versions.node.split(\".\").map(Number);\n if (!process.env.GATEWAY_NODE && (major > 22 || (major === 22 && minor >= 6))) return [\"--experimental-strip-types\", \"--no-warnings\"];\n try {\n return [createRequire(import.meta.url).resolve(\"tsx/cli\")];\n } catch {\n throw new CliError(\n `a .ts transform needs Node 22.6 or newer (built-in type stripping; this is ${process.versions.node}) or the tsx package installed beside the CLI; write the transform as .mjs or .py, or set GATEWAY_NODE to a newer node`,\n 1,\n );\n }\n}\n\nfunction command(script: string, wrapperDir: string): { file: string; args: string[] } {\n const suffix = path.extname(script).toLowerCase();\n if (PYTHON_SUFFIXES.includes(suffix)) return { file: process.env.GATEWAY_PYTHON || \"python3\", args: [\"-c\", PY_WRAPPER, script] };\n if (NODE_SUFFIXES.includes(suffix)) {\n const wrapper = path.join(wrapperDir, \"transform-wrapper.mjs\");\n fs.writeFileSync(wrapper, NODE_WRAPPER);\n const flags = suffix === \".ts\" || suffix === \".mts\" ? typescriptPrefix() : [];\n return { file: process.env.GATEWAY_NODE || process.execPath, args: [...flags, wrapper, script] };\n }\n throw new CliError(`${path.basename(script)}: a transform script is .py, .ts, .mjs, .js or .cjs`, 1);\n}\n\nconst tail = (stderr: string, lines = 12): string => {\n const kept = stderr\n .split(\"\\n\")\n .filter((line) => line.trim())\n .slice(-lines);\n return kept.length ? \"\\n\" + kept.join(\"\\n\") : \"\";\n};\n\n/**\n * Run `script` over `records`: the rows document it returns and its stderr.\n * A non-zero exit, a timeout, or output that is not the rows document is a\n * CliError (exit 1) carrying the tail of the script's stderr.\n */\nexport async function runTransform(script: string, records: unknown[], opts: { timeoutMs?: number } = {}): Promise<{ rows: Rows; stderr: string }> {\n if (!fs.existsSync(script) || !fs.statSync(script).isFile()) throw new CliError(`no transform script at ${script}`, 1);\n const resolved = path.resolve(script);\n const name = path.basename(script);\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TRANSFORM_TIMEOUT_MS;\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-transform-\"));\n try {\n const { file, args } = command(resolved, scratch);\n const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !SCRUBBED.test(key)));\n const done = await new Promise<{ code: number | null; stdout: string; stderr: string; timedOut: boolean }>((resolve, reject) => {\n const child = spawn(file, args, { cwd: path.dirname(resolved), env, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGKILL\");\n }, timeoutMs);\n child.stdout.setEncoding(\"utf8\").on(\"data\", (chunk: string) => (stdout += chunk));\n child.stderr.setEncoding(\"utf8\").on(\"data\", (chunk: string) => (stderr += chunk));\n child.on(\"error\", (error) => {\n clearTimeout(timer);\n reject(new CliError(`${name}: cannot run ${file}: ${error.message}`, 1));\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n resolve({ code, stdout, stderr, timedOut });\n });\n child.stdin.on(\"error\", () => undefined);\n child.stdin.end(records.map((record) => JSON.stringify(record) + \"\\n\").join(\"\"));\n });\n if (done.timedOut) throw new CliError(`${name} timed out after ${timeoutMs / 1000}s${tail(done.stderr)}`, 1);\n if (done.code !== 0) throw new CliError(`${name} exited ${done.code ?? \"?\"}${tail(done.stderr)}`, 1);\n let value: unknown;\n try {\n value = done.stdout.trim() ? JSON.parse(done.stdout) : null;\n } catch {\n throw new CliError(`${name} printed something other than the rows document${tail(done.stderr)}`, 1);\n }\n return { rows: checkRows(value, name), stderr: done.stderr };\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\n/** A transform given to the SDK: a function, or a script path run as above. */\nexport type TransformLike = string | ((records: unknown[]) => Rows | Promise<Rows>);\n\nexport async function transformRecords(transform: TransformLike, records: unknown[], opts: { timeoutMs?: number } = {}): Promise<{ rows: Rows; stderr: string }> {\n if (typeof transform === \"function\") return { rows: checkRows(await transform(records), \"transform(records)\"), stderr: \"\" };\n return runTransform(transform, records, opts);\n}\n","import { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\n\nimport { api, type Credentials } from \"../../config\";\nimport { CliError } from \"../../router\";\nimport type { BuiltChunk } from \"./chunker\";\nimport type { ManifestChunk } from \"./manifest\";\n\n/**\n * The batch protocol of `/api/public/worlds/{slug}/data` (contract §7): open\n * a batch, register each chunk by digest (the server hands back a presigned\n * PUT, or says it already holds that content), confirm the upload, complete,\n * then poll. Thin on purpose: the server owns validation and the ledger.\n */\n\nexport type Refusal = {\n chunk: number;\n index: number;\n entity: string | null;\n primaryKey: Record<string, unknown> | null;\n field: string | null;\n pointer: string;\n detail: string;\n};\n\nexport type BatchStatus = {\n batchId: string;\n state: string;\n mode?: string;\n merge?: string;\n atomic?: boolean;\n dryRun?: boolean;\n publish?: string;\n chunks?: number;\n uploadedChunks?: number;\n rows?: number;\n refusalCount?: number;\n refusals?: Refusal[];\n reportUrl?: string;\n progress?: { phase?: string; validatedChunks?: number; appliedRows?: number };\n entityCounts?: Record<string, number>;\n snapshotId?: string | null;\n batchDigest?: string | null;\n versionId?: string | null;\n error?: string | null;\n createdAt?: string;\n updatedAt?: string;\n};\n\nexport type OpenBatchBody = {\n mode: \"append\" | \"replace\";\n merge: \"upsert\" | \"fill\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n atomic: boolean;\n dryRun: boolean;\n publish: \"now\" | \"later\";\n message?: string;\n expectedChunks?: number;\n entities?: string[];\n};\n\nexport type OpenedBatch = { batchId: string; state: string; limits?: { chunkBytes?: number; batchBytes?: number; inlineBytes?: number } };\n\nexport type RegisteredChunk = {\n chunkId: string;\n uploaded: boolean;\n uploadUrl?: string;\n /** Headers the presigned PUT was signed for (content-type, content-length, x-amz-checksum-sha256); sent exactly. */\n uploadHeaders?: Record<string, string>;\n expiresAt?: string;\n};\n\nexport const TERMINAL_STATES = new Set([\"applied\", \"refused\", \"published\", \"failed\"]);\n\nexport const sleepMs = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\nexport class WorldDataApi {\n readonly base: string;\n constructor(\n readonly creds: Credentials,\n readonly slug: string,\n /** Injectable for tests: the pause between retries and polls. */\n readonly sleep: (ms: number) => Promise<void> = sleepMs,\n ) {\n this.base = `/api/public/worlds/${encodeURIComponent(slug)}/data`;\n }\n\n open(body: OpenBatchBody): Promise<OpenedBatch> {\n return api<OpenedBatch>(this.creds, \"POST\", `${this.base}/batches`, body);\n }\n\n register(batchId: string, chunk: { ordinal: number; digest: string; bytes: number; rows: number; entity: string | null }): Promise<RegisteredChunk> {\n return api<RegisteredChunk>(this.creds, \"POST\", `${this.base}/batches/${batchId}/chunks`, {\n ordinal: chunk.ordinal,\n digest: chunk.digest,\n bytes: chunk.bytes,\n rows: chunk.rows,\n ...(chunk.entity ? { entity: chunk.entity } : {}),\n });\n }\n\n markUploaded(batchId: string, chunkId: string): Promise<{ chunkId: string; uploaded: boolean; bytes: number }> {\n return api(this.creds, \"POST\", `${this.base}/batches/${batchId}/chunks/${chunkId}/uploaded`);\n }\n\n complete(batchId: string): Promise<{ batchId: string; state: string }> {\n return api(this.creds, \"POST\", `${this.base}/batches/${batchId}/complete`);\n }\n\n get(batchId: string): Promise<BatchStatus> {\n return api<BatchStatus>(this.creds, \"GET\", `${this.base}/batches/${batchId}`);\n }\n\n list(limit?: number, cursor?: string): Promise<{ batches: BatchStatus[]; nextCursor?: string }> {\n const params = new URLSearchParams();\n if (limit !== undefined) params.set(\"limit\", String(limit));\n if (cursor) params.set(\"cursor\", cursor);\n const q = params.toString();\n return api(this.creds, \"GET\", `${this.base}/batches${q ? `?${q}` : \"\"}`);\n }\n\n publish(message?: string): Promise<{ versionId: string; snapshotId: string; batchIds: string[] }> {\n return api(this.creds, \"POST\", `${this.base}/publish`, message ? { message } : {});\n }\n\n /**\n * PUT the gzipped chunk to its presigned URL with exactly the headers the\n * URL was signed for (the platform's `uploadHeaders`; the same three when it\n * sends none), with backoff on a dropped connection or a 5xx.\n */\n async put(uploadUrl: string, gz: Buffer, signed?: Record<string, string>): Promise<void> {\n const headers = signed ?? uploadHeadersFor(gz);\n const delays = [500, 1500, 4000];\n for (let attempt = 0; ; attempt++) {\n try {\n const res = await fetch(uploadUrl, { method: \"PUT\", body: new Uint8Array(gz), headers });\n if (res.ok) return;\n if (res.status < 500 || attempt >= delays.length) throw new CliError(`chunk upload -> ${res.status}: ${(await res.text()).slice(0, 300)}`, 1);\n } catch (error) {\n if (error instanceof CliError || attempt >= delays.length) throw error instanceof CliError ? error : new CliError(`chunk upload failed: ${(error as Error).message}`, 1);\n }\n await this.sleep(delays[attempt]!);\n }\n }\n\n /** Register, upload unless the server already holds the content, confirm. */\n async upload(batchId: string, chunk: BuiltChunk): Promise<ManifestChunk> {\n const registered = await this.register(batchId, chunk);\n if (!registered.uploaded) {\n if (!registered.uploadUrl) throw new CliError(`the server registered chunk ${chunk.ordinal} without an upload URL`, 1);\n await this.put(registered.uploadUrl, chunk.gz, registered.uploadHeaders);\n await this.markUploaded(batchId, registered.chunkId);\n }\n return { ordinal: chunk.ordinal, digest: chunk.digest, bytes: chunk.bytes, rows: chunk.rows, entity: chunk.entity, chunkId: registered.chunkId, uploaded: true };\n }\n}\n\n/** What a chunk's presigned PUT is signed for: its type, size and sha256 (base64, S3's spelling). */\nexport function uploadHeadersFor(gz: Buffer): Record<string, string> {\n return {\n \"content-type\": \"application/gzip\",\n \"content-length\": String(gz.length),\n \"x-amz-checksum-sha256\": createHash(\"sha256\").update(gz).digest(\"base64\"),\n };\n}\n\n/** Run `fn` over an async stream with at most `limit` in flight; results in input order. */\nexport async function forEachLimited<T>(items: AsyncIterable<T>, limit: number, fn: (item: T) => Promise<void>): Promise<void> {\n const inFlight = new Set<Promise<void>>();\n let failure: unknown = null;\n const track = (p: Promise<void>) => {\n const wrapped: Promise<void> = p.then(\n () => {\n inFlight.delete(wrapped);\n },\n (error) => {\n failure ??= error;\n inFlight.delete(wrapped);\n },\n );\n inFlight.add(wrapped);\n };\n for await (const item of items) {\n if (failure) break;\n track(fn(item));\n if (inFlight.size >= limit) await Promise.race(inFlight);\n }\n await Promise.all(inFlight);\n if (failure) throw failure;\n}\n\nexport type WaitOptions = {\n /** Called once per phase change with a printable line. */\n onPhase?: (line: string) => void;\n sleep?: (ms: number) => Promise<void>;\n /** The first pause between polls (default 1 s; GATEWAY_WORLD_DATA_POLL_MS in the CLI). */\n initialDelayMs?: number;\n};\n\n/** Poll until the batch settles; 1 s growing to 10 s between polls. */\nexport async function waitForBatch(client: WorldDataApi, batchId: string, opts: WaitOptions = {}): Promise<BatchStatus> {\n const sleep = opts.sleep ?? client.sleep;\n let delay = opts.initialDelayMs ?? 1000;\n let last = \"\";\n for (;;) {\n const status = await client.get(batchId);\n const phase = phaseLine(status);\n if (phase !== last) {\n opts.onPhase?.(phase);\n last = phase;\n }\n if (TERMINAL_STATES.has(status.state)) return status;\n await sleep(delay);\n delay = Math.min(10_000, Math.round(delay * 1.5));\n }\n}\n\n/** The Python CLI's progress line: `state`, with the job's phase in parentheses when it has one. */\nexport function phaseLine(status: BatchStatus): string {\n const phase = status.progress?.phase;\n return phase ? `${status.state} (${phase})` : status.state;\n}\n\n/**\n * The refusal report as JSONL: the server's full report when it has one\n * (`reportUrl`), else the records the status carries inline. Returns the\n * number of lines written.\n */\nexport async function writeRefusalReport(status: BatchStatus, file: string): Promise<number> {\n let text: string;\n if (status.reportUrl) {\n const res = await fetch(status.reportUrl);\n if (!res.ok) throw new CliError(`refusal report -> ${res.status}`, 1);\n text = await res.text();\n if (text && !text.endsWith(\"\\n\")) text += \"\\n\";\n } else text = (status.refusals ?? []).map((r) => JSON.stringify(r) + \"\\n\").join(\"\");\n fs.writeFileSync(file, text);\n return text ? text.split(\"\\n\").filter(Boolean).length : 0;\n}\n","import { createHash } from \"node:crypto\";\nimport { deflateRawSync } from \"node:zlib\";\n\nimport { dumps, type JsonObject } from \"./json\";\nimport type { TaggedRow } from \"./rowSource\";\n\n/**\n * Rows into chunks: gzip over JSONL, cut on row boundaries at `--chunk-rows`\n * or `--chunk-bytes` (uncompressed), content-addressed by the sha256 of the\n * gzipped bytes. The same rows with the same flags give the same content\n * digests (over the JSONL) in both CLIs and on every platform, and the same\n * gzip digests wherever the two zlibs deflate alike: lines are the Python\n * serialisation (`dumps`), the deflate stream is zlib's at level 9, and the\n * gzip header is written here rather than by zlib, as CPython's\n * `gzip.compress(…, mtime=0)` writes it — zlib would stamp the platform's OS\n * byte instead. Node 20 and 24 bundle Chromium's zlib, which deflates\n * differently from CPython's stock zlib, so a chunk's gzip digest can differ\n * between CLIs while its content digest agrees; `--resume` keys on the digest\n * of what this CLI wrote, so it is unaffected. See `zlibDeflatesLikeCPython`.\n */\n\nexport const DEFAULT_CHUNK_BYTES = 64 * 1024 * 1024;\nexport const GZIP_LEVEL = 9;\n\nexport type ChunkPlan = {\n /** Always bound: the Python CLI keeps 64 MiB even with --chunk-rows. */\n chunkBytes: number;\n chunkRows: number | null;\n /** When set, chunks are declared with this entity and lines are bare rows. */\n entity: string | null;\n};\n\nexport type BuiltChunk = {\n ordinal: number;\n /** sha256 of the gzipped bytes, hex. */\n digest: string;\n /** Gzipped size. */\n bytes: number;\n rows: number;\n entity: string | null;\n /** Uncompressed JSONL size (`contentBytes` in the shared manifest). */\n rawBytes: number;\n /** sha256 of the uncompressed JSONL: the cross-zlib parity check. */\n contentSha256: string;\n /** Index of the chunk's first row in the input stream. */\n firstRow: number;\n gz: Buffer;\n};\n\n/** One row as the line a chunk carries: tagged, or bare when the chunk declares its entity. */\nexport function chunkLine(row: TaggedRow, declared: string | null): string {\n if (declared !== null) return dumps(row.row) + \"\\n\";\n const tagged: JsonObject = new Map();\n tagged.set(\"entity\", row.entity);\n tagged.set(\"row\", row.row);\n return dumps(tagged) + \"\\n\";\n}\n\nexport async function* buildChunks(rows: AsyncIterable<TaggedRow>, plan: ChunkPlan): AsyncGenerator<BuiltChunk> {\n let lines: Buffer[] = [];\n let rawBytes = 0;\n let ordinal = 0;\n let seen = 0;\n const flush = (): BuiltChunk => {\n const raw = Buffer.concat(lines);\n const built = finishChunk(ordinal++, raw, lines.length, plan.entity, seen - lines.length);\n lines = [];\n rawBytes = 0;\n return built;\n };\n for await (const row of rows) {\n const line = Buffer.from(chunkLine(row, plan.entity), \"utf8\");\n const full =\n lines.length > 0 &&\n ((plan.chunkRows !== null && lines.length >= plan.chunkRows) ||\n rawBytes + line.length > plan.chunkBytes);\n if (full) yield flush();\n lines.push(line);\n rawBytes += line.length;\n seen++;\n }\n if (lines.length) yield flush();\n}\n\nexport function finishChunk(ordinal: number, raw: Buffer, rows: number, entity: string | null, firstRow = 0): BuiltChunk {\n const gz = gzipDeterministic(raw, { name: chunkName(ordinal) });\n return {\n ordinal,\n digest: createHash(\"sha256\").update(gz).digest(\"hex\"),\n bytes: gz.length,\n rows,\n entity,\n rawBytes: raw.length,\n contentSha256: createHash(\"sha256\").update(raw).digest(\"hex\"),\n firstRow,\n gz,\n };\n}\n\n/**\n * Whether this Node's zlib deflates as the CPython that wrote the fixtures\n * did. Deflate output is a property of the zlib build, not of the format:\n * the same input inflates everywhere, but a zlib-ng or a future Chromium\n * zlib may pick different matches, and then gzip digests differ across\n * CLIs while content digests (over the JSONL) still agree. The manifest\n * parity check is on the content; the gzip digest is informative.\n */\nexport function zlibDeflatesLikeCPython(): boolean {\n return deflateRawSync(Buffer.from(CPYTHON_PROBE_TEXT), { level: GZIP_LEVEL }).toString(\"hex\") === CPYTHON_PROBE_DEFLATE;\n}\n/**\n * Two tagged rows, as the chunker writes them, and CPython's deflate of them (zlib\n * 1.2.12, which also wrote the fixtures). The probe has to be this long: \"hello\\n\"\n * deflates identically on every zlib, so it proved nothing, while on this text\n * Node 20 and 24 (Chromium's zlib 1.3.1) pick different matches and land two\n * bytes shorter than Node 25 and CPython (stock zlib).\n */\nconst CPYTHON_PROBE_TEXT = '{\"entity\":\"customers\",\"row\":{\"id\":0,\"name\":\"n0\",\"score\":0.0,\"tags\":[\"a\"]}}\\n{\"entity\":\"customers\",\"row\":{\"id\":1,\"name\":\"n1\",\"score\":1.0,\"tags\":[\"a\"]}}\\n';\nconst CPYTHON_PROBE_DEFLATE = \"ab564acd2bc92ca954b2524a2e2d2ec9cf4d2d2a56d2512aca2f57b2aa56ca4c51b232d051ca4bcc4d052ac83300ca1427e7170139067a40f192c4f46225ab68a544a5d8da5aae6a824619228c3244186588691400\";\n\n/** The file name the Python CLI gives chunk N (`chunk-00007.jsonl.gz`), which\n * its `GzipFile` records in the gzip header, so it is part of the digest. */\nexport const chunkName = (ordinal: number): string => `chunk-${String(ordinal).padStart(5, \"0\")}.jsonl`;\n\n/**\n * Gzip as CPython's `gzip.GzipFile(fileobj, \"wb\", mtime=0)` writes it: mtime\n * 0, XFL for the level, OS \"unknown\" (0xff), and — when a name is given — the\n * FNAME field, exactly as GzipFile records the basename of the file it writes.\n */\nexport function gzipDeterministic(raw: Buffer, opts: { level?: number; name?: string } = {}): Buffer {\n const level = opts.level ?? GZIP_LEVEL;\n const name = opts.name ? Buffer.concat([Buffer.from(opts.name, \"latin1\"), Buffer.from([0])]) : Buffer.alloc(0);\n const header = Buffer.from([0x1f, 0x8b, 0x08, opts.name ? 0x08 : 0x00, 0, 0, 0, 0, level === 9 ? 0x02 : level === 1 ? 0x04 : 0x00, 0xff]);\n const body = deflateRawSync(raw, { level });\n const trailer = Buffer.alloc(8);\n trailer.writeUInt32LE(crc32(raw), 0);\n trailer.writeUInt32LE(raw.length >>> 0, 4);\n return Buffer.concat([header, name, body, trailer]);\n}\n\nlet table: Uint32Array | null = null;\n\n/** CRC-32 (IEEE), the gzip trailer's checksum. A table here keeps the CLI on Node 18. */\nexport function crc32(data: Buffer): number {\n if (!table) {\n table = new Uint32Array(256);\n for (let n = 0; n < 256; n++) {\n let c = n;\n for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;\n table[n] = c >>> 0;\n }\n }\n let crc = 0xffffffff;\n for (let i = 0; i < data.length; i++) crc = table[(crc ^ data[i]!) & 0xff]! ^ (crc >>> 8);\n return (crc ^ 0xffffffff) >>> 0;\n}\n\n/** The Python CLI's `_parse_size`: an integer and a unit — none, b, k, kib, kb, m, mib, mb, g, gib, gb. */\nexport function parseSize(text: string): number {\n const units: Record<string, number> = { \"\": 1, b: 1, k: 1024, kib: 1024, kb: 1000, m: 1024 ** 2, mib: 1024 ** 2, mb: 1000 ** 2, g: 1024 ** 3, gib: 1024 ** 3, gb: 1000 ** 3 };\n const raw = text.trim().toLowerCase().replace(/ /g, \"\");\n const m = /^(\\d+)([a-z]*)$/.exec(raw);\n if (!m || !(m[2]! in units)) throw new Error(`--chunk-bytes takes a size like 64MiB or 1000000, not '${text}'`);\n return Number(m[1]) * units[m[2]!]!;\n}\n","import type { Credentials } from \"../../config\";\nimport type { Rows } from \"../rows\";\nimport { forEachLimited, waitForBatch, WorldDataApi, type BatchStatus } from \"./batches\";\nimport { buildChunks, DEFAULT_CHUNK_BYTES } from \"./chunker\";\nimport { parseJson, type JsonObject } from \"./json\";\nimport type { TaggedRow } from \"./rowSource\";\n\n/**\n * Rows already in memory into a platform world through the batch lane —\n * open, chunk, upload, complete, wait — with none of the CLI's file, manifest\n * or resume machinery. What `ingestToolCalls` (the SDK) pushes after the\n * runtime projected a slug's records; the CLI keeps `data import`'s lane.\n * `redact` is optional and defaults to off: the platform stores the rows as\n * given unless asked to apply its `[redact]` policy.\n */\nexport async function pushRows(\n creds: Credentials,\n slug: string,\n rows: Rows,\n opts: {\n mode?: \"append\" | \"replace\";\n redact?: \"off\" | \"apply\" | \"refuse\";\n message?: string;\n publish?: \"now\" | \"later\";\n chunkBytes?: number;\n parallel?: number;\n dryRun?: boolean;\n sleep?: (ms: number) => Promise<void>;\n } = {},\n): Promise<BatchStatus> {\n const client = opts.sleep ? new WorldDataApi(creds, slug, opts.sleep) : new WorldDataApi(creds, slug);\n const opened = await client.open({\n mode: opts.mode ?? \"append\",\n merge: \"upsert\",\n ...(opts.redact && opts.redact !== \"off\" ? { redact: opts.redact } : {}),\n atomic: true,\n dryRun: Boolean(opts.dryRun),\n publish: opts.publish ?? \"now\",\n ...(opts.message ? { message: opts.message } : {}),\n });\n if (!opened.batchId) throw new Error(\"the platform opened no batch (no batchId in the answer)\");\n // The chunker speaks the file lane's JSON model (CPython-faithful numbers and\n // key order), so each row takes the same road a JSONL line does: serialized, parsed.\n const tagged = (async function* (): AsyncGenerator<TaggedRow> {\n for (const [entity, listed] of Object.entries(rows))\n for (let index = 0; index < listed.length; index++)\n yield { entity, row: parseJson(JSON.stringify(listed[index]!)) as JsonObject, where: `${entity}[${index}]` };\n })();\n const chunks = buildChunks(tagged, { chunkBytes: opts.chunkBytes ?? DEFAULT_CHUNK_BYTES, chunkRows: null, entity: null });\n await forEachLimited(chunks, Math.max(1, opts.parallel ?? 4), async (chunk) => {\n await client.upload(opened.batchId, chunk);\n });\n await client.complete(opened.batchId);\n return waitForBatch(client, opened.batchId, { initialDelayMs: pollMs() });\n}\n\nfunction pollMs(): number {\n const raw = Number(process.env.GATEWAY_WORLD_DATA_POLL_MS ?? 1000);\n return Number.isFinite(raw) && raw >= 0 ? raw : 1000;\n}\n","/**\n * Records into a world's rows — the record contract, an interceptor that\n * writes it, the conversion from TOOL observations, and the door in.\n *\n * A tool's response is not the entity's shape, and nothing here assumes it\n * is. The workflow with real data is: pull the raw tool calls, look at them,\n * then ingest them through the route you declare — {@link ingest} with a\n * `transform` (your own `transform(records) -> {entity: [rows]}`, a function\n * or a script), with a `map` (an `ingest.toml` mapping for shapes that need\n * no code), or with neither, when the world's own `ingest.toml` applies or\n * each record's tool is a connector operation whose result *is* the\n * operation's response body (its `[ingest]` projection in `connector.toml`).\n * Mappings and projections run in the schema runtime (Python, bundled with\n * the CLI or on the platform), never re-implemented here; a transform runs\n * where you are.\n *\n * The record, one JSON object per line:\n *\n * {\"tool\": \"list_users\", \"args\": {\"team\": \"t1\"}, \"result\": {\"users\": [...]},\n * \"at\": \"2026-09-15T10:00:00Z\", \"session\": \"optional\", \"source\": \"optional free text\"}\n *\n * A `gateway worlds session export` line (`{seq, kind, tool, args, result,\n * error, completedAt}`) is accepted as it is. Redaction is optional and OFF\n * by default everywhere here: rows land as the tools returned them unless\n * `redact: \"apply\"` (the world's `[redact]` policy) or `\"refuse\"` is asked for.\n *\n * - {@link captureToolCalls} wraps an agent's tool functions so every real\n * call is recorded — the agent changes nothing.\n * - {@link toolCallsFromObservations} turns a trace's TOOL observations into\n * records (the `--from traces` path of `gateway worlds data ingest`).\n * - {@link ingest} puts records into a world through a transform, a mapping\n * or the operations: a local directory through the bundled runtime, a\n * platform slug through the batch lane. {@link ingestToolCalls} is the same\n * door with neither transform nor mapping of your own.\n */\n\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { apiRequest, type WorldsClientOptions } from \"./index\";\n\nexport type ToolCallRecord = {\n /** The operation name in the world's `connector.toml`. */\n tool: string;\n /** The call's arguments, by name: what `carry_args` reads. */\n args: Record<string, unknown>;\n /** The operation's response body, as the tool returned it. */\n result?: unknown;\n /** ISO time of the call. */\n at?: string;\n /** The session the call belongs to, when there is one. */\n session?: string;\n /** Free text: where the record came from. */\n source?: string;\n /** Set instead of `result` when the call threw; ingest skips it, counted. */\n error?: string;\n};\n\nexport type RedactMode = \"off\" | \"apply\" | \"refuse\";\nexport type IngestMode = \"append\" | \"replace\";\n\n// ---------------------------------------------------------------- the mapping\n\n/** How one entity field is set: an item path, or a table naming exactly one of `from`, `literal`, `template`, `hash`. */\nexport type IngestFieldSpec =\n | string\n | {\n /** Item path (`name`, `customer.id`, `emails[0]`); `$`-paths reach the record: `$tool`, `$at`, `$index`, `$session`, `$source`, `$source.id`, `$source.trace`, `$record.<path>`, `$parent.<path>`. */\n from?: string;\n literal?: string | number | boolean;\n /** `{path}` holes are filled from the item or the record; a hole with no value refuses the record. */\n template?: string;\n /** sha256 of the JSON array of these paths' values; unset when any is missing. */\n hash?: string[];\n /** A chain from the closed transform set, applied to `from` or `template`. */\n transform?: string[];\n /** Used when `from` is missing or null. */\n default?: string | number | boolean;\n /** Coerce the value; a CSV cell is text until this says otherwise. */\n type?: \"string\" | \"integer\" | \"number\" | \"boolean\";\n };\n\nexport type IngestExplode = {\n /** Item path to a list (or one object) of children. */\n path: string;\n entity: string;\n /** child field <- parent ENTITY field (after the parent's mapping). */\n carry?: Record<string, string>;\n fields?: Record<string, IngestFieldSpec>;\n};\n\nexport type IngestSource = {\n /** The tool name (or several), or `\"*\"` for rows and csv records. */\n name: string | string[];\n kind?: \"tool-call\" | \"rows\" | \"csv\";\n /** Path into the record: `result`, `result.data[*]`, `args`, `$record`. */\n select: string;\n /** All must hold on the selected item: a literal, or `{ present: true | false }`. */\n when?: Record<string, string | number | boolean | { present: boolean }>;\n entity: string;\n /** Item path that dates the row for `on_conflict`; default the record's `at`. */\n at?: string;\n fields?: Record<string, IngestFieldSpec>;\n explode?: IngestExplode[];\n};\n\n/** `ingest.toml`, parsed: the grammar the schema runtime's `mapping.py` checks and applies. */\nexport type IngestMapping = {\n ingest?: { on_conflict?: \"latest\" | \"first\"; unmatched?: \"refuse\" | \"skip\" };\n sources: IngestSource[];\n};\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n// ---------------------------------------------------------------- records\n\nexport type ParsedToolCall = {\n /** The record in the contract's shape, when it is a tool call with a result. */\n record: ToolCallRecord | null;\n /** Why a well-formed record carries no rows by design (a `seed` line, a failed call). */\n skip: string | null;\n /** What is wrong with the record. */\n refusal: string | null;\n};\n\n/**\n * One raw record — the contract's shape or a session-export line — judged the\n * way the runtime judges it (`ingest.normalize_record`): the same skips, the\n * same refusals, so a file checked here is what the runtime will accept.\n */\nexport function parseToolCallRecord(raw: unknown): ParsedToolCall {\n const none = { record: null, skip: null };\n if (!isObject(raw)) return { ...none, refusal: \"record is not an object\" };\n const kind = raw.kind;\n if (kind !== undefined && kind !== null && kind !== \"call\") return { record: null, skip: `kind ${String(kind)}`, refusal: null };\n const tool = raw.tool;\n if (typeof tool !== \"string\" || !tool) return { ...none, refusal: \"record has no tool name\" };\n if (raw.error !== undefined && raw.error !== null && raw.error !== \"\") return { record: null, skip: \"call failed\", refusal: null };\n const args = raw.args ?? {};\n if (!isObject(args)) return { ...none, refusal: `args of ${tool} is not an object` };\n if (!(\"result\" in raw)) return { ...none, refusal: `record of ${tool} has no result` };\n const at = raw.at ?? raw.completedAt;\n const record: ToolCallRecord = { tool, args, result: raw.result };\n if (typeof at === \"string\") record.at = at;\n if (typeof raw.session === \"string\") record.session = raw.session;\n if (typeof raw.source === \"string\") record.source = raw.source;\n return { record, skip: null, refusal: null };\n}\n\n/**\n * Raw records from files: JSONL (one object per line) or one JSON array, several\n * files concatenated in order. A line that is not JSON, or not an object, throws\n * naming the file and line. Each record's shape is judged later, per record, so\n * the report can point at the index.\n */\nexport function readToolCallRecords(paths: string[]): unknown[] {\n const records: unknown[] = [];\n for (const file of paths) records.push(...toolCallRecordsIn(fs.readFileSync(file, \"utf8\"), file));\n return records;\n}\n\n/** The records in one text, named `where` in a refusal. */\nexport function toolCallRecordsIn(text: string, where: string): unknown[] {\n const stripped = text.trim();\n if (!stripped) return [];\n if (stripped.startsWith(\"[\")) {\n const listed = JSON.parse(stripped) as unknown;\n if (!Array.isArray(listed)) throw new Error(`${where} is neither a JSON array nor JSON Lines`);\n listed.forEach((item, index) => {\n if (!isObject(item)) throw new Error(`${where}[${index}] is not an object`);\n });\n return listed;\n }\n const records: unknown[] = [];\n const lines = text.split(/\\r?\\n/);\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index]!;\n if (!line.trim()) continue;\n let item: unknown;\n try {\n item = JSON.parse(line);\n } catch {\n throw new Error(`${where}:${index + 1} is not JSON`);\n }\n if (!isObject(item)) throw new Error(`${where}:${index + 1} is not an object`);\n records.push(item);\n }\n return records;\n}\n\n// ---------------------------------------------------------------- capture\n\n/**\n * Where {@link captureToolCalls} writes each record: an array (pushed), a file\n * path (JSONL, one record per line, appended), or a callback (awaited).\n */\nexport type ToolCallSink = ToolCallRecord[] | string | ((record: ToolCallRecord) => unknown | Promise<unknown>);\n\nexport type ToolFunctions = Record<string, (args: Record<string, unknown>) => Promise<unknown>>;\n\nasync function emit(sink: ToolCallSink, record: ToolCallRecord): Promise<void> {\n if (Array.isArray(sink)) {\n sink.push(record);\n return;\n }\n if (typeof sink === \"string\") {\n fs.appendFileSync(sink, JSON.stringify(record) + \"\\n\");\n return;\n }\n if (typeof sink === \"function\") {\n await sink(record);\n return;\n }\n throw new TypeError(\"sink must be an array, a file path, or a function\");\n}\n\n/**\n * Wrap a name → async function map — the shape the Vercel AI SDK's tools and a\n * `WorldToolkit`'s `impls` share — so every call is recorded as a tool-call\n * record into `sink`, and hand back the same map. The agent changes nothing:\n * each wrapped function returns what the original returned, and an error is\n * thrown through untouched (recorded with `error` and no `result`, which\n * ingest skips and counts). Nothing is redacted here; redaction is optional\n * and off by default on the ingest side.\n *\n * const tools = captureToolCalls({ list_users: realVendor.listUsers }, \"calls.jsonl\");\n * await runMyAgent(tools); // real vendor, every call recorded\n * await ingestToolCalls(\"acme-crm\", readToolCallRecords([\"calls.jsonl\"]));\n */\nexport function captureToolCalls<T extends ToolFunctions>(\n tools: T,\n sink: ToolCallSink,\n opts: { session?: string; source?: string } = {},\n): T {\n const wrapped: ToolFunctions = Object.create(null);\n for (const [name, fn] of Object.entries(tools)) {\n wrapped[name] = async (args: Record<string, unknown> = {}) => {\n const record: ToolCallRecord = { tool: name, args, at: new Date().toISOString() };\n if (opts.session) record.session = opts.session;\n if (opts.source) record.source = opts.source;\n let result: unknown;\n try {\n result = await fn(args);\n } catch (error) {\n record.error = error instanceof Error ? error.message || error.name : String(error);\n await emit(sink, record);\n throw error;\n }\n record.result = result;\n await emit(sink, record);\n return result;\n };\n }\n return wrapped as T;\n}\n\n// ---------------------------------------------------------------- observations\n\n/** What a TOOL observation carries, as `GET /api/public/observations` and\n * `GET /api/public/sessions/{id}?includeIO=true` return it. */\nexport type ObservationLike = {\n id?: string;\n traceId?: string | null;\n type?: string;\n name?: string | null;\n input?: unknown;\n output?: unknown;\n startTime?: string | Date;\n level?: string;\n statusMessage?: string | null;\n};\n\nexport type ObservationConversion = {\n records: ToolCallRecord[];\n /** TOOL observations whose name is not one of the world's operations, by name. */\n unknownTools: Record<string, number>;\n /** Observations that were not converted, by reason. */\n skipped: Record<string, number>;\n};\n\n/** A serialized value back to JSON when it parses; otherwise as it is. */\nfunction jsonish(value: unknown): unknown {\n if (typeof value !== \"string\") return value;\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n\nconst isoOf = (value: string | Date | undefined): string | undefined =>\n value instanceof Date ? value.toISOString() : typeof value === \"string\" ? value : undefined;\n\n/**\n * TOOL observations → tool-call records: `name` is the tool, `input` the args,\n * `output` the result, `startTime` the time, `trace:<traceId>/<id>` the source.\n * A serialized `input`/`output` (the SDK stores JSON text) is parsed back;\n * an `input` that is not an object leaves `args` empty rather than guessed.\n * Only `type: \"TOOL\"` converts. With `tools` (the world's operation names) an\n * observation for any other tool is counted in `unknownTools`, not converted.\n * An `ERROR`-level observation converts with `error` set, so ingest counts it\n * as a failed call instead of projecting its output.\n */\nexport function toolCallsFromObservations(\n observations: ObservationLike[],\n opts: { tools?: Iterable<string> | null; session?: string; since?: string } = {},\n): ObservationConversion {\n const known = opts.tools ? new Set(opts.tools) : null;\n const sinceMs = opts.since ? Date.parse(opts.since) : NaN;\n const out: ObservationConversion = { records: [], unknownTools: {}, skipped: {} };\n const skip = (reason: string) => {\n out.skipped[reason] = (out.skipped[reason] ?? 0) + 1;\n };\n for (const observation of observations) {\n if (observation.type !== \"TOOL\") {\n skip(`type ${observation.type ?? \"unknown\"}`);\n continue;\n }\n const tool = observation.name;\n if (typeof tool !== \"string\" || !tool) {\n skip(\"no name\");\n continue;\n }\n const at = isoOf(observation.startTime);\n if (!Number.isNaN(sinceMs) && at !== undefined && Date.parse(at) < sinceMs) {\n skip(\"before since\");\n continue;\n }\n if (known && !known.has(tool)) {\n out.unknownTools[tool] = (out.unknownTools[tool] ?? 0) + 1;\n continue;\n }\n const input = jsonish(observation.input);\n const record: ToolCallRecord = { tool, args: isObject(input) ? input : {} };\n if (observation.level === \"ERROR\") record.error = observation.statusMessage || \"ERROR\";\n else record.result = jsonish(observation.output);\n if (at !== undefined) record.at = at;\n if (opts.session) record.session = opts.session;\n record.source = `trace:${observation.traceId ?? \"?\"}/${observation.id ?? \"?\"}`;\n out.records.push(record);\n }\n return out;\n}\n\n// ---------------------------------------------------------------- the door\n\nexport type IngestRefusal = { index: number | null; tool: string | null; reason: string; pointer?: string };\n\n/** One `[[sources]]` of a mapping in the report. */\nexport type IngestSourceReport = {\n name: string;\n kind: string;\n select: string;\n entity: string;\n records: number;\n items: number;\n rows: Record<string, number>;\n /** Source fields no line of the source reads, with a sample value. */\n unmappedFields: Record<string, string>;\n /** Entity fields the source never sets, per entity. */\n unsetFields: Record<string, string[]>;\n};\n\nexport type IngestToolCallsReport = {\n world: string;\n /** How the rows were produced. */\n via?: \"transform\" | \"map\" | \"operations\" | \"rows\";\n /** `via: \"map\"`: each source's accounting. */\n sources?: IngestSourceReport[];\n /** `via: \"map\"` with `unmatched = \"skip\"`: records no source claimed, by tool name. */\n unmatched?: Record<string, number>;\n /** `via: \"operations\"`: that this was the operation projection, not a mapping. */\n note?: string;\n /** `via: \"transform\"`: what the script wrote to stderr. */\n stderr?: string;\n /** Records given. */\n records: number;\n /** Records that yielded rows. */\n ingested: number;\n /** Records that carried no rows by design, by reason. */\n skipped: Record<string, number>;\n /** What was wrong, per record; with any, nothing was written. */\n refusals: IngestRefusal[];\n /** Rows projected, per entity. */\n rows: Record<string, number>;\n dryRun: boolean;\n redact: RedactMode;\n changed: boolean;\n kind?: string;\n entityCounts?: Record<string, number>;\n /** A slug that was pushed: the batch's final status (`state`, `versionId`, …). */\n batch?: Record<string, unknown>;\n};\n\nexport type IngestToolCallsOptions = WorldsClientOptions & {\n /** Optional, default `\"off\"`: rows land as the tools returned them. */\n redact?: RedactMode;\n /** Project and prove the rows; write and upload nothing. */\n dryRun?: boolean;\n mode?: IngestMode;\n /** Change reason for the version a slug cuts. */\n message?: string;\n};\n\nexport type IngestReport = IngestToolCallsReport;\n\nexport type IngestOptions = IngestToolCallsOptions & {\n /** Your own `transform(records) -> {entity: [rows]}`: a function (run here) or a script path (`.py`, `.ts`, `.mjs`; a subprocess with a time limit and sockets disabled). */\n transform?: string | ((records: unknown[]) => Rows | Promise<Rows>);\n /** An `ingest.toml` mapping: its text, or the parsed table. Exclusive with `transform`. */\n map?: string | IngestMapping;\n /** For a script transform; default 120 000. */\n timeoutMs?: number;\n};\n\ntype Rows = Record<string, Record<string, unknown>[]>;\n\nfunction credentialsOf(options: WorldsClientOptions): { host: string; publicKey: string; secretKey: string } | null {\n const host = (options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\").replace(/\\/+$/, \"\");\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n return publicKey && secretKey ? { host, publicKey, secretKey } : null;\n}\n\n/**\n * Records into a world through the route you declare. `world` is a local\n * directory (written in place through the bundled schema runtime) or a\n * platform slug (pulled to a temporary directory, the rows produced and\n * proven there, then pushed through the chunked batch lane as a new version).\n *\n * With `transform` the rows are what your code returns; with `map` (or the\n * world's own `ingest.toml`) what the mapping declares; with neither, each\n * tool-call record's tool resolves to an operation of `connector.toml` and\n * its result goes through that operation's `[ingest]` projection (the report\n * says `via: \"operations\"`). A transform that fails or returns the wrong\n * shape throws. `redact` is optional and defaults to `\"off\"`.\n */\nexport async function ingest(world: string, records: unknown[], options: IngestOptions = {}): Promise<IngestReport> {\n const { ingestLocalToolCalls, importLocalWorldData, checkLocalWorldData } = await import(\"../cli/runtime/data\");\n if (options.transform !== undefined && options.map !== undefined) throw new Error(\"records go through one of transform, map\");\n const redact = options.redact ?? \"off\";\n const mode = options.mode ?? \"append\";\n const dryRun = Boolean(options.dryRun);\n const creds = credentialsOf(options);\n const local = fs.existsSync(world) && fs.statSync(world).isDirectory();\n const map = options.map === undefined ? undefined : options.map;\n\n let rows: Rows | null = null;\n let stderr = \"\";\n if (options.transform !== undefined) {\n const { transformRecords } = await import(\"../cli/platform/worldData/transform\");\n ({ rows, stderr } = await transformRecords(options.transform, records, { timeoutMs: options.timeoutMs }));\n }\n\n if (local) {\n if (rows === null) return reportOf(world, await ingestLocalToolCalls(world, records, { redact, dryRun, mode, map }, creds), redact);\n const landed = dryRun ? await checkLocalWorldData(world, rows, creds, { redact }) : await importLocalWorldData(world, rows, { mode, redact }, creds);\n return transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: !dryRun && landed.changed, kind: landed.kind, entityCounts: landed.entity_counts });\n }\n if (!creds) throw new Error(\"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY (or pass publicKey/secretKey).\");\n const { pull } = await import(\"./hub\");\n const slug = world.split(\"@\", 1)[0]!;\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-ingest-\"));\n try {\n const pulled = await pull(world, path.join(scratch, slug), options);\n // Produced and proven against the pulled contract; the platform's batch\n // lane checks every row again and redacts there, so this pass runs with\n // redaction off and hands the rows on as they were produced.\n let report: IngestReport;\n let projected: Rows;\n if (rows === null) {\n const proven = await ingestLocalToolCalls(pulled.dir, records, { redact: \"off\", dryRun: true, mode, map }, creds);\n report = reportOf(world, proven, redact);\n projected = proven.projected ?? {};\n } else {\n const proven = await checkLocalWorldData(pulled.dir, rows, creds);\n report = transformReport(world, records.length, rows, stderr, { dryRun, redact, changed: false, kind: proven.kind, entityCounts: proven.entity_counts });\n projected = rows;\n }\n report.dryRun = dryRun;\n if (dryRun || report.refusals.length || !Object.keys(projected).length) return report;\n const { pushRows } = await import(\"../cli/platform/worldData/push\");\n const status = await pushRows(creds, slug, projected, { mode, redact, message: options.message });\n report.batch = status;\n report.changed = status.state === \"applied\" || status.state === \"published\";\n if (status.entityCounts) report.entityCounts = status.entityCounts;\n return report;\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\n/**\n * Tool-call records into a world with neither a transform nor a mapping of\n * your own: the world's `ingest.toml` when it has one, else each record's\n * tool through its operation's `[ingest]` projection (an unknown tool is a\n * refusal naming it and nothing is written). {@link ingest} with the same\n * options.\n */\nexport async function ingestToolCalls(world: string, records: unknown[], options: IngestToolCallsOptions = {}): Promise<IngestToolCallsReport> {\n return ingest(world, records, options);\n}\n\nfunction transformReport(\n world: string,\n records: number,\n rows: Rows,\n stderr: string,\n outcome: { dryRun: boolean; redact: RedactMode; changed: boolean; kind?: string; entityCounts?: Record<string, number> },\n): IngestReport {\n return {\n world,\n via: \"transform\",\n ...(stderr ? { stderr } : {}),\n records,\n ingested: records,\n skipped: {},\n refusals: [],\n rows: Object.fromEntries(Object.entries(rows).map(([entity, listed]) => [entity, listed.length])),\n dryRun: outcome.dryRun,\n redact: outcome.redact,\n changed: outcome.changed,\n ...(outcome.kind ? { kind: outcome.kind } : {}),\n ...(outcome.entityCounts ? { entityCounts: outcome.entityCounts } : {}),\n };\n}\n\nfunction reportOf(\n world: string,\n local: {\n via?: IngestReport[\"via\"];\n sources?: { name: string; kind: string; select: string; entity: string; records: number; items: number; rows: Record<string, number>; unmapped_fields: Record<string, string>; unset_fields: Record<string, string[]> }[];\n unmatched?: Record<string, number>;\n note?: string;\n records: number;\n ingested: number;\n skipped: Record<string, number>;\n refusals: IngestRefusal[];\n rows: Record<string, number>;\n dry_run: boolean;\n changed: boolean;\n kind?: string;\n entity_counts?: Record<string, number>;\n },\n redact: RedactMode,\n): IngestToolCallsReport {\n return {\n world,\n ...(local.via ? { via: local.via } : {}),\n ...(local.sources ? { sources: local.sources.map(({ unmapped_fields, unset_fields, ...rest }) => ({ ...rest, unmappedFields: unmapped_fields, unsetFields: unset_fields })) } : {}),\n ...(local.unmatched ? { unmatched: local.unmatched } : {}),\n ...(local.note ? { note: local.note } : {}),\n records: local.records,\n ingested: local.ingested,\n skipped: local.skipped,\n refusals: local.refusals,\n rows: local.rows,\n dryRun: local.dry_run,\n redact,\n changed: local.changed,\n ...(local.kind ? { kind: local.kind } : {}),\n ...(local.entity_counts ? { entityCounts: local.entity_counts } : {}),\n };\n}\n\n/** The TOOL observations of one session, every trace's, from `GET /api/public/sessions/{id}?includeIO=true`. */\nexport async function sessionToolObservations(sessionId: string, options: WorldsClientOptions = {}): Promise<ObservationLike[]> {\n const session = await apiRequest<{ traces?: { id?: string; observations?: ObservationLike[] }[] }>(\n options,\n \"GET\",\n `/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`,\n );\n const out: ObservationLike[] = [];\n for (const trace of session.traces ?? [])\n for (const observation of trace.observations ?? []) out.push({ traceId: trace.id ?? null, ...observation });\n return out;\n}\n","/**\n * Worlds from TypeScript: identity, tasks, and HOSTED execution.\n *\n * The same three-level model as the Python SDK — WorldSet → Task — with one\n * deliberate difference: a world's tools are Python modules, so TypeScript\n * does not materialize task environments in-process. What a TS agent\n * codebase needs is exactly what this module provides: resolve a world ref\n * to its pinned version, read its task list, and dispatch HOSTED runs\n * (parallelism included) that execute the world server-side and file graded,\n * version-pinned rollouts. Local in-process execution stays a Python\n * capability by design, not by omission.\n */\n\nimport type { WorldTaskIdRef } from \"./session\";\n\nexport type WorldsClientOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n};\n\nexport type ResolvedWorldVersion = {\n versionId: string;\n semanticVersion: string | null;\n contentHash: string;\n state?: string;\n};\n\nexport type WorldTaskInfo = {\n name: string;\n variant: string | null;\n};\n\nexport type DispatchedRun = {\n model: string;\n runId: string;\n ok: boolean;\n error?: string;\n};\n\nfunction resolveEnv(options: WorldsClientOptions) {\n const host =\n options.host ?? process.env.GATEWAY_HOST ?? \"https://withgateway.ai\";\n const publicKey = options.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = options.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n if (!publicKey || !secretKey) {\n throw new Error(\n \"Gateway keys missing: set GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY \" +\n \"(or pass publicKey/secretKey).\",\n );\n }\n return { host: host.replace(/\\/+$/, \"\"), publicKey, secretKey };\n}\n\n/** Authenticated JSON request against the platform API — the primitive the\n * worlds helpers and the TS CLI share. */\nexport async function apiRequest<T>(\n options: WorldsClientOptions,\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\",\n path: string,\n body?: unknown,\n): Promise<T> {\n const { host, publicKey, secretKey } = resolveEnv(options);\n const res = await fetch(`${host}${path}`, {\n method,\n headers: {\n \"content-type\": \"application/json\",\n authorization:\n \"Basic \" + Buffer.from(`${publicKey}:${secretKey}`).toString(\"base64\"),\n },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n const text = await res.text();\n if (!res.ok) {\n throw new Error(\n `${method} ${path} -> ${res.status}: ${text.slice(0, 400)}`,\n );\n }\n return JSON.parse(text) as T;\n}\n\n/** Set (or rotate) one environment secret — write-only: no API returns it. */\nexport async function setEnvSecret(\n slug: string,\n key: string,\n value: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; created: boolean }> {\n return apiRequest(\n options,\n \"PUT\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n value,\n },\n );\n}\n\n/** Keys and rotation timestamps only — never values. */\nexport async function listEnvSecretKeys(\n slug: string,\n options: WorldsClientOptions = {},\n): Promise<{ key: string; updatedAt: string }[]> {\n const res = await apiRequest<{\n secrets: { key: string; updatedAt: string }[];\n }>(\n options,\n \"GET\",\n `/api/public/benchmark-containers/secrets?slug=${encodeURIComponent(slug)}`,\n );\n return res.secrets;\n}\n\nexport async function deleteEnvSecret(\n slug: string,\n key: string,\n options: WorldsClientOptions = {},\n): Promise<void> {\n await apiRequest(\n options,\n \"DELETE\",\n \"/api/public/benchmark-containers/secrets\",\n {\n slug,\n key,\n },\n );\n}\n\nexport type RunConfigSummary = {\n id: string;\n name: string;\n runType: string;\n createdAt: string;\n models: string[];\n parallelism: number;\n autoRunOnPush: boolean;\n agent: string | null;\n};\n\n/** Run configs in the project. CI resolves by NAME and dispatches by id. */\nexport async function listRunConfigs(\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary[]> {\n const res = await apiRequest<{ runConfigs: RunConfigSummary[] }>(\n options,\n \"GET\",\n \"/api/public/benchmark-containers/run-configs\",\n );\n return res.runConfigs;\n}\n\n/** What a run config selects for the runner to work through. A config runs\n * EITHER the bundle's own scenarios (`taskNames`, `taskSetDatasetId`) OR the\n * project's stored tasks (`worldTasks`, api worlds only) — never both. A\n * stored task ref without `version` runs the task's current version at\n * dispatch time; with it, that version forever. */\nexport type RunConfigInput = {\n id?: string;\n name: string;\n models: string[];\n parallelism?: number;\n numExamples?: number;\n rolloutsPerExample?: number;\n timeoutMinutes?: number;\n agent?: string;\n taskSetDatasetId?: string | null;\n taskNames?: string[];\n worldTasks?: WorldTaskIdRef[];\n autoRunOnPush?: boolean;\n};\n\n/** Create a run config, or update the one named by `id`. */\nexport async function upsertRunConfig(\n input: RunConfigInput,\n options: WorldsClientOptions = {},\n): Promise<RunConfigSummary> {\n return apiRequest<RunConfigSummary>(\n options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs\",\n input,\n );\n}\n\n/** `id[@version]` items (comma-separated or an array) → stored task refs;\n * the spelling `bench run-configs create --world-tasks` takes. */\nexport function parseWorldTaskRefs(spec: string | string[]): WorldTaskIdRef[] {\n const items = (Array.isArray(spec) ? spec : spec.split(\",\"))\n .map((s) => s.trim())\n .filter(Boolean);\n return items.map((item) => {\n const at = item.lastIndexOf(\"@\");\n if (at < 0) return { id: item };\n const id = item.slice(0, at);\n const version = Number(item.slice(at + 1));\n if (!id || !Number.isInteger(version) || version < 1)\n throw new Error(\n `stored task ref '${item}' is not <id> or <id>@<version> (version a positive integer)`,\n );\n return { id, version };\n });\n}\n\nexport type RunReport = {\n id: string;\n status: string;\n terminal: boolean;\n score: number | null;\n summary: string | null;\n model: string | null;\n versionLabel: string | null;\n parallelism: number;\n shardsCompleted: number | null;\n /** The run's page on the platform — what a PR comment should link. */\n url: string | null;\n evaluations: {\n id: string;\n status: string;\n avgReward: number | null;\n url: string | null;\n }[];\n samples: {\n task: string | null;\n reward: number | null;\n rewards: Record<string, unknown>;\n sessionId: string | null;\n }[];\n};\n\n/** The read half of dispatch: status, score, per-shard evaluations, and\n * per-task rewards — everything a CI gate needs. */\nexport async function getRun(\n runId: string,\n options: WorldsClientOptions = {},\n): Promise<RunReport> {\n return apiRequest(\n options,\n \"GET\",\n `/api/public/benchmark-containers/runs/${encodeURIComponent(runId)}`,\n );\n}\n\n/** Poll a run to terminal (default every 20s, up to `timeoutMinutes`). */\nexport async function waitForRun(\n runId: string,\n opts: {\n timeoutMinutes?: number;\n intervalSeconds?: number;\n onTick?: (run: RunReport) => void;\n options?: WorldsClientOptions;\n } = {},\n): Promise<RunReport> {\n const deadline = Date.now() + (opts.timeoutMinutes ?? 45) * 60_000;\n for (;;) {\n const run = await getRun(runId, opts.options ?? {});\n if (run.terminal) return run;\n if (Date.now() > deadline)\n throw new Error(\n `Run ${runId} still ${run.status} after the wait timeout.`,\n );\n opts.onTick?.(run);\n await new Promise((resolve) =>\n setTimeout(resolve, (opts.intervalSeconds ?? 20) * 1000),\n );\n }\n}\n\nexport type RunProvenance = {\n branch?: string;\n commit?: string;\n repoUrl?: string;\n actor?: { id?: string; name?: string; imageUrl?: string; kind?: string };\n};\n\n/**\n * Where a dispatch comes from, DETECTED rather than configured: the CI\n * checkout's branch/commit/actor under GitHub Actions, else the developer's\n * own git checkout. A run nobody can trace to a branch is a score with no\n * code attached, so every dispatch carries this unless overridden.\n */\nexport function detectProvenance(): RunProvenance {\n const env =\n (globalThis as { process?: { env?: Record<string, string | undefined> } })\n .process?.env ?? {};\n const out: RunProvenance = {};\n const ref = env.GITHUB_HEAD_REF || env.GITHUB_REF_NAME;\n if (ref) out.branch = ref;\n if (env.GITHUB_SHA) out.commit = env.GITHUB_SHA;\n const server = env.GITHUB_SERVER_URL ?? \"https://github.com\";\n if (env.GITHUB_REPOSITORY) out.repoUrl = `${server}/${env.GITHUB_REPOSITORY}`;\n if (env.GITHUB_ACTOR) {\n out.actor = {\n kind: \"ci\",\n id: env.GITHUB_ACTOR,\n name: env.GITHUB_ACTOR,\n // GitHub serves every account's avatar at /<login>.png.\n imageUrl: `${server}/${env.GITHUB_ACTOR}.png`,\n };\n }\n if (!out.branch || !out.commit) {\n try {\n const { execFileSync } =\n require(\"node:child_process\") as typeof import(\"node:child_process\");\n const git = (args: string[]) =>\n execFileSync(\"git\", args, {\n encoding: \"utf-8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n })\n .toString()\n .trim();\n out.branch = out.branch ?? git([\"rev-parse\", \"--abbrev-ref\", \"HEAD\"]);\n out.commit = out.commit ?? git([\"rev-parse\", \"HEAD\"]);\n if (!out.repoUrl) {\n const remote = git([\"config\", \"--get\", \"remote.origin.url\"]);\n if (remote) out.repoUrl = remote.replace(/\\.git$/, \"\");\n }\n if (!out.actor) {\n const name = git([\"config\", \"--get\", \"user.name\"]);\n if (name) out.actor = { kind: \"user\", name };\n }\n } catch {\n // No git here — dispatch without provenance rather than failing.\n }\n }\n return out;\n}\n\n/** One scenario of a world, as data. */\nexport class WorldTask {\n constructor(\n readonly world: WorldSet,\n readonly name: string,\n readonly variant: string | null,\n ) {}\n}\n\n/**\n * THE world, from a TS process: pinned identity + its tasks + hosted runs.\n *\n * const world = await openWorld(\"google-drive-sim@main\");\n * console.log(world.version.semanticVersion, world.tasks.length);\n * const runs = await world.dispatch(runConfigId);\n */\nexport class WorldSet {\n constructor(\n readonly slugRef: string,\n readonly slug: string,\n readonly ref: string | null,\n readonly version: ResolvedWorldVersion,\n public tasks: WorldTask[],\n private readonly options: WorldsClientOptions,\n ) {}\n\n task(variant: string): WorldTask {\n const hit = this.tasks.find(\n (t) => t.variant === variant || t.name.includes(variant),\n );\n if (!hit) {\n const known = this.tasks.map((t) => t.variant ?? t.name).join(\", \");\n throw new Error(`no task matches ${variant}; have: ${known}`);\n }\n return hit;\n }\n\n /**\n * Open a LIVE session against one of this world's tasks — a bundled task's\n * name or an inline `WorldTaskSpec`: the platform boots (or reuses) a warm\n * container, and your agent calls its tools through the platform. See\n * worlds/session.ts.\n */\n async open(\n task: import(\"./session\").WorldTaskRef,\n opts: {\n reuseWarm?: boolean;\n surfaces?: import(\"./browser\").WorldSurfaceKind[];\n } = {},\n ): Promise<import(\"./session\").WorldSession> {\n const { openSession } = await import(\"./session\");\n return openSession(this.slug, {\n task,\n versionId: this.version.versionId,\n reuseWarm: opts.reuseWarm,\n surfaces: opts.surfaces,\n options: this.options,\n });\n }\n\n /**\n * Start a HOSTED run of a run config against this world — the platform\n * executes the (Python) world in parallel containers per the config's\n * `parallelism` and files one graded run per model. Returns those runs.\n */\n async dispatch(\n runConfigId: string,\n opts: {\n containerId?: string;\n versionId?: string;\n /** Override the auto-detected branch/commit/actor. */\n provenance?: RunProvenance;\n } = {},\n ): Promise<{ versionLabel: string; runs: DispatchedRun[] }> {\n const provenance = opts.provenance ?? detectProvenance();\n return apiRequest(\n this.options,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n {\n runConfigId,\n ...(opts.containerId ? { containerId: opts.containerId } : {}),\n versionId: opts.versionId ?? this.version.versionId,\n ...provenance,\n },\n );\n }\n}\n\n/**\n * Resolve `slug` / `slug@branch|tag|semver|hash` to its pinned version and\n * task list. The task list comes from the version's file manifest\n * (`tasks/<name>/task.toml`), so it needs no bundle download.\n */\nexport async function openWorld(\n slugRef: string,\n options: WorldsClientOptions = {},\n): Promise<WorldSet> {\n const at = slugRef.indexOf(\"@\");\n const slug = at === -1 ? slugRef : slugRef.slice(0, at);\n const ref = at === -1 ? null : slugRef.slice(at + 1);\n\n const version = await apiRequest<\n ResolvedWorldVersion & { taskNames?: string[] }\n >(options, \"POST\", \"/api/public/benchmark-containers/resolve-version\", {\n slug,\n ...(ref ? { ref } : {}),\n });\n\n const world = new WorldSet(\n slugRef,\n slug,\n ref,\n {\n versionId: version.versionId,\n semanticVersion: version.semanticVersion ?? null,\n contentHash: version.contentHash,\n state: version.state,\n },\n [],\n options,\n );\n for (const name of version.taskNames ?? []) {\n const variant = /^[a-z0-9]+-([a-z0-9]+)-/.exec(name)?.[1] ?? null;\n world.tasks.push(new WorldTask(world, name, variant));\n }\n return world;\n}\n\n// The session surface completes the worlds module, so `@withgateway/sdk/worlds`\n// carries both halves: running a world locally, and driving one the platform\n// hosts. (session.ts imports apiRequest from here; the cycle is function-level\n// only, and the build below is what proves it resolves.)\nexport * from \"./session\";\n\n// Stored tasks: the task spec as a named, versioned project resource that\n// `openSession(world, { task: { id } })` opens on.\nexport * from \"./tasks\";\n\n// The computer-use half: surfaces, a Playwright browser on the world's UI,\n// and browser actions as model tools.\nexport * from \"./browser\";\n\n// The hub half: push, pull, propose and the content-hash primitives the CLI\n// runs on. These were reachable only from inside the package, so a consumer\n// could drive a world but never publish one.\nexport * from \"./hub\";\n\n// PR validation: push-dispatch-wait-gate as one composed call, for CI.\nexport * from \"./validate\";\n\n// Discovery: what a world holds and how each field is stored (`describeWorld`),\n// and the stored forms of a plaintext under the world's [redact] table\n// (`storedForms`, `redactionOf`) — the same digest rule as the Python runtime.\nexport * from \"./describe\";\nexport * from \"./redaction\";\nexport * from \"./transforms\";\n\n// Lookup: the rows of one entity matching a predicate (`queryRows`), by\n// stored value or — with `resolve` — by plaintext the runtime maps through\n// the same [redact] table.\nexport * from \"./query\";\n\n// Migration: a stored world into a schema world (`migrateWorld`), dry run by\n// default; the project's connector worlds at once (`migrateProjectWorlds`).\nexport * from \"./migrate\";\n\n// Tool calls into rows: the record contract, `captureToolCalls` (record an\n// agent's real calls), `toolCallsFromObservations` (from a trace) and\n// `ingestToolCalls` (into a directory or a slug). Redaction optional, off by default.\nexport * from \"./ingest\";\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { arg, CliError, type CommandContext, type CommandGroup } from \"../router\";\n\n/**\n * The skills shipped with the SDK, so any agent can pick them up.\n *\n * `gateway worlds skill NAME` prints one; `--install DIR` lands it in a\n * repository's `.claude/` (the skill's files, plus any agent it ships) — the\n * layout Claude Code, Cursor and Codex read. The files are copied from the\n * Python package (`gatewaysdk/environment/schema/skills/`) into `skills/` at\n * build time (scripts/copy-skills.mjs) and shipped with the npm package.\n */\n\nexport const SKILL_NAME = \"connector-schema-authoring\";\nconst AGENT_FILE = \"connector-template-author.md\";\n/** Agents a skill installs beside itself, under `.claude/agents/`. */\nconst SKILL_AGENTS: Record<string, string[]> = { [SKILL_NAME]: [AGENT_FILE] };\nconst NEXT_STEPS: Record<string, string> = {\n [SKILL_NAME]: \"gateway worlds schema init ./<vendor>-world --connector custom\",\n \"world-data-ingestion\": \"gateway worlds data import <world> rows.json\",\n \"worlds-getting-started\": \"gateway worlds schema init ./my-world --connector custom\",\n \"benchmarks-getting-started\": \"gateway benchmarks init ./my-benchmark --connector custom\",\n};\n\n/**\n * Where the packaged skills live: `GATEWAY_SKILLS_DIR` when set, else\n * `<package>/skills` next to the built cli.js, else (running from the repo)\n * the Python package's skills directory.\n */\nexport function skillsRoot(): string {\n const candidates: string[] = [];\n if (process.env.GATEWAY_SKILLS_DIR) candidates.push(process.env.GATEWAY_SKILLS_DIR);\n const entry = process.argv[1];\n if (entry) {\n let packageRoot: string;\n try {\n packageRoot = path.dirname(path.dirname(fs.realpathSync(entry)));\n } catch {\n packageRoot = path.dirname(path.dirname(path.resolve(entry)));\n }\n candidates.push(path.join(packageRoot, \"skills\"));\n candidates.push(path.join(packageRoot, \"..\", \"sdk\", \"src\", \"gatewaysdk\", \"environment\", \"schema\", \"skills\"));\n }\n candidates.push(path.join(process.cwd(), \"skills\"));\n for (const candidate of candidates) {\n if (fs.existsSync(path.join(candidate)) && fs.statSync(candidate).isDirectory()) return candidate;\n }\n throw new CliError(\n \"No packaged skills found: this build shipped without skills/ (run `npm run build`, which copies them) \" +\n \"or set GATEWAY_SKILLS_DIR.\",\n 1,\n );\n}\n\n/** Every skill the package ships: a directory under skills/ holding a SKILL.md. */\nexport function packagedSkills(): string[] {\n const root = skillsRoot();\n return fs\n .readdirSync(root, { withFileTypes: true })\n .filter((entry) => entry.isDirectory() && fs.existsSync(path.join(root, entry.name, \"SKILL.md\")))\n .map((entry) => entry.name)\n .sort();\n}\n\nfunction skillDir(name: string): string {\n const directory = path.join(skillsRoot(), name);\n if (name.includes(\"/\") || name.includes(\"\\\\\") || !fs.existsSync(path.join(directory, \"SKILL.md\")))\n throw new CliError(`No packaged skill '${name}'; the package ships: ${packagedSkills().join(\", \")}`, 1);\n return directory;\n}\n\nexport function skillText(name: string): string {\n return fs.readFileSync(path.join(skillDir(name), \"SKILL.md\"), \"utf8\");\n}\n\nexport type SkillMatch = {\n name: string;\n description: string;\n /** Section headings holding a query word. */\n headings: string[];\n /** Query words found in the description or a heading. */\n matched: string[];\n};\n\n/** The frontmatter `description:` of a SKILL.md, and its markdown headings. */\nexport function skillIndex(text: string): { description: string; headings: string[] } {\n const front = /^---\\n([\\s\\S]*?)\\n---\\n/.exec(text)?.[1] ?? \"\";\n const description = /^description:\\s*(.*)$/m.exec(front)?.[1]?.trim() ?? \"\";\n const headings = text\n .split(\"\\n\")\n .filter((line) => /^#{1,6}\\s+\\S/.test(line))\n .map((line) => line.replace(/^#+\\s+/, \"\").trim());\n return { description, headings };\n}\n\n/**\n * Which packaged skills a question is about: every query word is looked for,\n * case-insensitively, in each skill's frontmatter description and section\n * headings; skills matching more words rank first, and a skill matching none\n * is left out. So \"harbor\", \"benchmark\" and \"verifiers\" all find the\n * benchmarks skill, \"rows\" the ingestion one.\n */\nexport function searchSkills(words: string[]): SkillMatch[] {\n const terms = [...new Set(words.map((w) => w.trim().toLowerCase()).filter(Boolean))];\n if (!terms.length) throw new CliError(\"skill search needs at least one word\", 2);\n const stem = (term: string) => term.replace(/(ing|es|s)$/, \"\");\n const hit = (haystack: string, term: string) => haystack.toLowerCase().includes(stem(term));\n const out: SkillMatch[] = [];\n for (const name of packagedSkills()) {\n const { description, headings } = skillIndex(skillText(name));\n const matched = terms.filter((term) => hit(name, term) || hit(description, term) || headings.some((h) => hit(h, term)));\n if (!matched.length) continue;\n out.push({\n name,\n description,\n headings: headings.filter((h) => terms.some((term) => hit(h, term))),\n matched,\n });\n }\n return out.sort((a, b) => b.matched.length - a.matched.length || a.name.localeCompare(b.name));\n}\n\nfunction printSearch(ctx: CommandContext, words: string[]): number {\n const matches = searchSkills(words);\n if (!matches.length) {\n ctx.stderr(`No packaged skill mentions ${words.join(\" \")}; the package ships: ${packagedSkills().join(\", \")}`);\n return 1;\n }\n for (const match of matches) {\n ctx.stdout(`${match.name} (matches ${match.matched.join(\", \")})`);\n ctx.stdout(` ${match.description.length > 200 ? match.description.slice(0, 197) + \"...\" : match.description}`);\n for (const heading of match.headings.slice(0, 6)) ctx.stdout(` # ${heading}`);\n ctx.stdout(` print it: gateway worlds skill ${match.name}`);\n }\n return 0;\n}\n\nfunction listFiles(dir: string, rel = \"\"): string[] {\n const out: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n if (entry.name === \"__pycache__\") continue;\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isDirectory()) out.push(...listFiles(path.join(dir, entry.name), childRel));\n else if (entry.isFile()) out.push(childRel);\n }\n return out;\n}\n\n/** Repository-relative destination → packaged source, for every file the skill installs. */\nexport function packagedFiles(name: string): Record<string, string> {\n const directory = skillDir(name);\n const files: Record<string, string> = {};\n for (const relative of listFiles(directory)) files[`.claude/skills/${name}/${relative}`] = path.join(directory, relative);\n for (const agent of SKILL_AGENTS[name] ?? []) files[`.claude/agents/${agent}`] = path.join(skillsRoot(), \"agents\", agent);\n return files;\n}\n\nexport type InstallReport = { written: string[]; unchanged: string[]; conflicts: string[] };\n\n/**\n * Write the skill (and its agents) under `destination/.claude/`. An existing\n * file with the same content is left alone; one with different content is a\n * conflict and nothing is written unless `force`.\n */\nexport function installSkill(destination: string, name: string, force = false): InstallReport {\n const report: InstallReport = { written: [], unchanged: [], conflicts: [] };\n const planned: [string, Buffer][] = [];\n for (const [relative, source] of Object.entries(packagedFiles(name))) {\n const content = fs.readFileSync(source);\n const target = path.join(destination, relative);\n if (fs.existsSync(target) && fs.readFileSync(target).equals(content)) report.unchanged.push(relative);\n else if (fs.existsSync(target) && !force) report.conflicts.push(relative);\n else {\n planned.push([target, content]);\n report.written.push(relative);\n }\n }\n if (report.conflicts.length) {\n report.written = [];\n return report;\n }\n for (const [target, content] of planned) {\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, content);\n }\n return report;\n}\n\nexport function printOrInstallSkill(\n ctx: CommandContext,\n name: string,\n install: string | undefined,\n force: boolean,\n): number | void {\n const text = skillText(name);\n if (install === undefined) {\n process.stdout.write(text);\n return;\n }\n const report = installSkill(install, name, force);\n if (report.conflicts.length) {\n ctx.stderr(\"Refusing to overwrite files that differ from the packaged skill:\");\n for (const relative of report.conflicts) ctx.stderr(` ${path.join(install, relative)}`);\n ctx.stderr(\"Pass --force to replace them.\");\n return 1;\n }\n for (const relative of report.written) ctx.stdout(`wrote ${path.join(install, relative)}`);\n for (const relative of report.unchanged) ctx.stdout(`unchanged ${path.join(install, relative)}`);\n const step = NEXT_STEPS[name];\n if (step) ctx.stdout(`next: ${step}`);\n}\n\n/** `gateway worlds skill [NAME] [--list] [--search WORDS] [--install DIR] [--force]`; no NAME with `--install` lands every skill. */\nexport function registerSkillCommands(root: CommandGroup): void {\n const skill = root.group(\"skill\", \"The packaged guides for an agent: list them, search them by topic, print one.\");\n skill.command({\n name: \"list\",\n help: \"List the skills this SDK ships.\",\n run: async (_args, ctx) => {\n for (const name of packagedSkills()) ctx.stdout(`${name} ${skillIndex(skillText(name)).description.slice(0, 120)}`);\n },\n });\n skill.command({\n name: \"search\",\n help: \"Find the packaged skill for a topic: each word is looked for in every skill's description and section headings.\",\n positionals: [{ name: \"words\", help: \"Topic words, e.g. benchmark harbor verifiers, or rows import.\", variadic: true }],\n notes: \"Exit 1 when no skill mentions the words. `gateway worlds skill <name>` prints the one it names.\",\n run: async (args, ctx) => printSearch(ctx, args.positionals),\n });\n skill.command({\n name: \"show\",\n help: \"Print one packaged skill (the same as `gateway worlds skill <name>`).\",\n positionals: [{ name: \"name\", help: \"Packaged skill name (see `gateway skill list`).\" }],\n run: async (args, _ctx) => {\n process.stdout.write(skillText(args.positionals[0]!));\n },\n });\n\n root.group(\"worlds\", \"Build, seed, serve and run worlds.\").command({\n name: \"skill\",\n help: \"Print a packaged skill for an agent, --search them by topic, or --install one into a repository's .claude/.\",\n positionals: [\n {\n name: \"name\",\n help: \"Packaged skill: worlds-getting-started, benchmarks-getting-started, world-data-ingestion, connector-schema-authoring\",\n optional: true,\n },\n ],\n flags: [\n { name: \"list\", help: \"List the skills this SDK ships and exit\", boolean: true },\n { name: \"search\", help: \"Find the skill for a topic (words, comma- or space-separated); same as `gateway skill search`\" },\n {\n name: \"install\",\n help: \"Repository to install the skill (and any agent it ships) into, under .claude/; every skill when no NAME\",\n },\n { name: \"force\", help: \"Overwrite an existing file whose content differs\", boolean: true },\n ],\n run: async (args, ctx) => {\n const name = args.positionals[0];\n const install = arg.str(args, \"install\");\n const force = arg.bool(args, \"force\");\n const search = arg.str(args, \"search\");\n if (search !== undefined) return printSearch(ctx, [...search.split(/[\\s,]+/), ...(name ? [name] : [])]);\n if (arg.bool(args, \"list\") || (name === undefined && install === undefined)) {\n for (const skill of packagedSkills()) ctx.stdout(skill);\n if (name === undefined && !arg.bool(args, \"list\"))\n ctx.stderr(\"Name one to print it, or --install DIR to land every skill in a repository.\");\n return;\n }\n if (name === undefined) {\n // `--install DIR` alone: every packaged skill, so an agent needs one command.\n let code: number | undefined;\n for (const skill of packagedSkills()) code = printOrInstallSkill(ctx, skill, install, force) ?? code;\n return code;\n }\n return printOrInstallSkill(ctx, name, install, force);\n },\n });\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { api } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\nimport { credentials, HOST_FLAG, query } from \"./shared\";\nimport { printOrInstallSkill, SKILL_NAME } from \"./skill\";\n\nexport const CONNECTORS = \"/api/public/context/connectors\";\nexport const HUB = \"/api/public/connectors/hub\";\nexport const CLONE = \"/api/public/connectors/clone\";\n\n// ── collect_template (port of connectors/template.py) ───────────────────────\n\nconst WORLD_SKIPPED_DIRS = new Set([\"data\", \"captures\", \"db\"]);\nconst WORLD_SKIPPED_FILES = new Set([\"gateway-env.toml\", \"tool-schemas.json\"]);\n// Brex retrospective: a world initialized from `workspace:brex` arrived without its\n// test suite, its task list, its verifiers and the OpenAPI documents `conform` needs,\n// because publish left them behind. They are world artifacts, not contract, so the\n// runtime's template init does not lay them out; the CLI (and the platform) copy them\n// beside what it builds. Keep this set in step with WORLD_ARTIFACT_* below and with\n// `isCarriedTemplatePath` in gateway/packages/shared/src/domain/worldSchema.ts.\nconst WORLD_CARRIED_DIRS = new Set([\"api\", \"scenarios\", \"evidence\", \"reports\", \"tests\", \"verifiers\", \"openapi\"]);\nconst ROOT_CARRIED_FILES = new Set([\"connector.toml\", \"tasks.json\"]);\nconst SUPPORTING_SUFFIXES = new Set([\".json\", \".md\", \".toml\"]);\nconst GENERATED_NAMES = new Set([\"base.json\", \"runtime.json\", \"lock.json\", \"README.md\", \"tool-schemas.json\"]);\n\n/** Template paths the runtime's `init-template-files` does not lay out: world\n * artifacts (`tests/`, `tasks.json`, `verifiers/`, `openapi/`) that travel with a\n * workspace connector and are written into the world as they are. */\nconst WORLD_ARTIFACT_DIRS = new Set([\"tests\", \"verifiers\", \"openapi\"]);\nconst WORLD_ARTIFACT_FILES = new Set([\"tasks.json\"]);\n\nexport function isCarriedTemplatePath(relative: string): boolean {\n const slash = relative.indexOf(\"/\");\n if (slash === -1) return WORLD_ARTIFACT_FILES.has(relative);\n return WORLD_ARTIFACT_DIRS.has(relative.slice(0, slash));\n}\n\nexport type TemplateFiles = { source: \"template\" | \"world\"; files: Record<string, string>; skipped: string[] };\n\nexport function walk(root: string): string[] {\n const out: string[] = [];\n const visit = (rel: string) => {\n const abs = rel ? path.join(root, rel) : root;\n for (const entry of fs.readdirSync(abs, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const childRel = rel ? `${rel}/${entry.name}` : entry.name;\n if (entry.isSymbolicLink()) continue;\n if (entry.isDirectory()) {\n if (entry.name === \"__pycache__\" || entry.name.startsWith(\".\")) continue;\n visit(childRel);\n } else if (entry.isFile()) {\n if (entry.name.startsWith(\".\") || entry.name.endsWith(\".pyc\")) continue;\n out.push(childRel);\n }\n }\n };\n visit(\"\");\n return out;\n}\n\nfunction readText(root: string, relative: string): string {\n const bytes = fs.readFileSync(path.join(root, relative));\n const text = bytes.toString(\"utf8\");\n if (Buffer.from(text, \"utf8\").length !== bytes.length || text.includes(\"�\"))\n throw new CliError(`${relative} is not UTF-8 text; a connector template holds text files only`, 1);\n return text;\n}\n\n/** The template path a world-directory file maps to, or null to leave it behind. */\nfunction templatePath(relative: string): string | null {\n const parts = relative.split(\"/\");\n if (WORLD_SKIPPED_DIRS.has(parts[0]!) || WORLD_SKIPPED_FILES.has(relative)) return null;\n if (parts.length === 1) return ROOT_CARRIED_FILES.has(relative) ? relative : null;\n if (parts[0] === \"schema\") {\n const name = parts[parts.length - 1]!;\n if (parts.length !== 2 || !SUPPORTING_SUFFIXES.has(path.extname(name)) || GENERATED_NAMES.has(name)) return null;\n return name;\n }\n if (relative === \"tools/handlers.py\") return \"handlers.py\";\n if (WORLD_CARRIED_DIRS.has(parts[0]!)) return relative;\n return null;\n}\n\n/** The files a workspace connector is made of, from a template dir or the world dir it was authored in. */\nexport function collectTemplate(directory: string): TemplateFiles {\n if (fs.existsSync(path.join(directory, \"world.json\"))) {\n const files: Record<string, string> = {};\n for (const relative of walk(directory)) files[relative] = readText(directory, relative);\n return { source: \"template\", files, skipped: [] };\n }\n if (!fs.existsSync(path.join(directory, \"schema\", \"world.json\")))\n throw new CliError(`${directory}: neither a connector template (world.json) nor a world (schema/world.json)`, 1);\n const files: Record<string, string> = {};\n const skipped: string[] = [];\n for (const relative of walk(directory)) {\n const target = templatePath(relative);\n if (target === null) skipped.push(relative);\n else files[target] = readText(directory, relative);\n }\n return { source: \"world\", files, skipped };\n}\n\n// ── the client shapes ───────────────────────────────────────────────────────\n\ntype HubRow = {\n id?: string;\n slug?: string;\n name?: string;\n orgName?: string;\n isOwn?: boolean;\n visibility?: string;\n metadata?: { vendor?: string; auth?: string; entityCount?: number; operationCount?: number };\n};\n\ntype Pulled = {\n repo?: Record<string, unknown>;\n commit?: { commitHash?: string; id?: string };\n files?: Record<string, { type?: string; content?: unknown }>;\n};\n\nfunction oneRoute(slug: string, params: Record<string, string | undefined> = {}): string {\n if (!slug || slug.includes(\"/\")) throw new CliError(\"a connector slug is a single path segment\");\n return `${CONNECTORS}/${encodeURIComponent(slug)}${query(params)}`;\n}\n\nfunction table(rows: string[][], header: string[]): string {\n const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => (r[i] ?? \"\").length)));\n return [header, ...rows]\n .map((line) => line.map((cell, i) => cell.padEnd(widths[i]!)).join(\" \").trimEnd())\n .join(\"\\n\");\n}\n\n/** `gateway worlds connector list|pull|clone|publish|skill`. C2 registers validate|capture|conform|ingest. */\nexport function registerConnectorCommands(root: CommandGroup): void {\n const connector = root\n .group(\"worlds\", \"Build, seed, serve and run worlds.\")\n .group(\"connector\", \"Describe a vendor connection, capture what it returns, seed the world from it\");\n\n connector.command({\n name: \"publish\",\n help: \"Save the template as a workspace connector: created on first publish, a new commit after.\",\n positionals: [{ name: \"path\", help: \"A connector template directory, or the world directory it was authored in\" }],\n flags: [\n { name: \"slug\", help: \"Connector slug (default: the directory name)\" },\n { name: \"message\", short: \"m\", help: \"Commit message\" },\n { name: \"description\", help: \"One-line description shown in listings\" },\n { name: \"tag\", help: \"Tag (repeatable)\", repeat: true },\n { name: \"workspace-visible\", help: \"Visible to the whole workspace, not only this project's members\", boolean: true },\n { name: \"project-scope\", help: \"Own it in this project rather than the org\", boolean: true },\n HOST_FLAG,\n ],\n notes:\n \"A world directory is mapped back into the template layout (schema/world.json → world.json,\\n\" +\n \"tools/handlers.py → handlers.py, …) and tests/, tasks.json, verifiers/ and openapi/ travel with it;\\n\" +\n \"data/, captures/, db/ and generated files stay behind.\\n\" +\n \"The published connector equals the directory: paths no longer present are removed.\",\n run: async (args, ctx) => {\n const dir = args.positionals[0]!;\n const gathered = collectTemplate(dir);\n const slug = arg.str(args, \"slug\") ?? path.basename(path.resolve(dir));\n const creds = credentials(args);\n const files: Record<string, { content: string } | null> = Object.fromEntries(\n Object.entries(gathered.files).map(([p, content]) => [p, { content }]),\n );\n let parent: string | undefined;\n const exists = await api<{ exists?: boolean }>(creds, \"GET\", oneRoute(slug, { exists: \"true\" }));\n if (exists.exists) {\n const head = await api<Pulled>(creds, \"GET\", oneRoute(slug));\n for (const stale of Object.keys(head.files ?? {}).sort()) {\n if (stale in files) continue;\n files[stale] = null;\n ctx.stderr(`# removing ${stale}`);\n }\n const hash = head.commit?.commitHash;\n parent = typeof hash === \"string\" && hash.length >= 8 ? hash : undefined;\n }\n for (const left of gathered.skipped) ctx.stderr(`# left behind: ${left}`);\n const tags = arg.list(args, \"tag\");\n const description = arg.str(args, \"description\");\n const result = await api<Record<string, unknown>>(creds, \"POST\", oneRoute(slug), {\n files,\n message: arg.str(args, \"message\") ?? `publish ${slug}`,\n is_public: arg.bool(args, \"workspace-visible\"),\n scope: arg.bool(args, \"project-scope\") ? \"project\" : \"org\",\n source: \"sdk\",\n ...(parent ? { parent_commit: parent } : {}),\n ...(description ? { description } : {}),\n ...(tags.length ? { tags } : {}),\n });\n const commit = result.commitHash ?? result.commitId ?? \"\";\n ctx.stdout(`${result.status ?? \"committed\"} ${slug} ${commit} ${result.url ?? \"\"}`.trimEnd());\n },\n });\n\n connector.command({\n name: \"list\",\n help: \"List this organization's workspace connectors (--hub adds the ones other organizations published).\",\n flags: [\n { name: \"hub\", help: \"Every connector this organization can use, published ones included\", boolean: true },\n { name: \"query\", help: \"Filter by slug, name or description\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const hub = arg.bool(args, \"hub\");\n let rows = await hubRows(args);\n if (!hub) rows = rows.filter((row) => row.isOwn);\n if (rows.length === 0) {\n ctx.stderr(\"no connectors\" + (hub ? \" in the hub\" : \"; `gateway worlds connector publish` adds one\"));\n return;\n }\n const header = [\"slug\", \"name\", \"vendor\", \"auth\", \"entities\", \"operations\", \"visibility\", ...(hub ? [\"org\"] : [])];\n const lines = rows.map((row) => {\n const meta = row.metadata ?? {};\n const line = [\n row.slug ?? \"\",\n row.name ?? \"\",\n meta.vendor ?? \"-\",\n meta.auth ?? \"-\",\n String(meta.entityCount ?? \"-\"),\n String(meta.operationCount ?? \"-\"),\n row.visibility ?? \"\",\n ];\n if (hub) line.push(`${row.orgName ?? \"\"}${row.isOwn ? \" (own)\" : \"\"}`);\n return line;\n });\n ctx.stdout(table(lines, header));\n },\n });\n\n connector.command({\n name: \"pull\",\n help: \"Write the connector's template files to a directory.\",\n positionals: [{ name: \"slug\", help: \"Workspace connector slug\" }],\n flags: [\n { name: \"out\", help: \"New or empty directory (default: ./<slug>)\" },\n { name: \"version\", help: \"A label or commit hash; the head by default\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const slug = args.positionals[0]!;\n const out = arg.str(args, \"out\") ?? slug;\n if (fs.existsSync(out) && (!fs.statSync(out).isDirectory() || fs.readdirSync(out).length > 0))\n throw new CliError(`${out}: must be a new or empty directory`, 1);\n const pulled = await api<Pulled>(credentials(args), \"GET\", oneRoute(slug, { version: arg.str(args, \"version\") }));\n const files = flattenFiles(slug, pulled);\n for (const relative of Object.keys(files).sort()) {\n if (relative.startsWith(\"/\") || relative.split(\"/\").includes(\"..\"))\n throw new CliError(`Refusing a template path outside the directory: ${relative}`, 1);\n const target = path.join(out, relative);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, files[relative]!);\n ctx.stdout(relative);\n }\n ctx.stderr(`# ${slug} @ ${pulled.commit?.commitHash ?? pulled.commit?.id ?? \"\"} -> ${out}`);\n },\n });\n\n connector.command({\n name: \"clone\",\n help: \"Copy a connector another organization published into this organization, with provenance.\",\n positionals: [{ name: \"source\", help: \"A hub connector's slug or repo id\" }],\n flags: [\n { name: \"name\", help: \"Name for the clone (default: the source's)\" },\n { name: \"slug\", help: \"Slug for the clone (default: the source's)\" },\n { name: \"project-scope\", help: \"Own it in this project rather than the org\", boolean: true },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const source = args.positionals[0]!;\n const rows = await hubRows(args, undefined);\n let chosen = rows.find((row) => row.id === source);\n if (!chosen) {\n const matches = rows.filter((row) => row.slug === source);\n const candidates = matches.filter((row) => !row.isOwn);\n const pool = candidates.length ? candidates : matches;\n if (pool.length === 0)\n throw new CliError(`${source}: not in the hub; \\`gateway worlds connector list --hub\\` shows what is`, 1);\n if (pool.length > 1) {\n ctx.stderr(`${source} names ${pool.length} hub connectors; clone by repo id instead:`);\n for (const row of pool) ctx.stderr(` ${row.id} ${row.orgName}`);\n return 1;\n }\n chosen = pool[0]!;\n }\n const name = arg.str(args, \"name\");\n const slug = arg.str(args, \"slug\");\n const result = await api<Record<string, unknown>>(credentials(args), \"POST\", CLONE, {\n sourceRepoId: chosen.id,\n scope: arg.bool(args, \"project-scope\") ? \"project\" : \"org\",\n ...(name ? { name } : {}),\n ...(slug ? { slug } : {}),\n });\n ctx.stdout(\n `cloned ${chosen.slug} from ${chosen.orgName} -> ${result.slug} (${result.id}) commit ${result.commitId}`,\n );\n },\n });\n\n connector.command({\n name: \"skill\",\n help: \"The connector authoring skill for agents: print it, or --install it into a repository's .claude/.\",\n flags: [\n { name: \"install\", help: \"Repository to install the skill and agent into (under its .claude/)\" },\n { name: \"force\", help: \"Overwrite an existing file whose content differs\", boolean: true },\n ],\n notes: `An alias of \\`gateway worlds skill ${SKILL_NAME}\\`.`,\n run: async (args, ctx) => printOrInstallSkill(ctx, SKILL_NAME, arg.str(args, \"install\"), arg.bool(args, \"force\")),\n });\n}\n\nasync function hubRows(args: Parameters<typeof credentials>[0], q?: string): Promise<HubRow[]> {\n const search = q ?? arg.str(args, \"query\");\n const res = await api<{ connectors?: HubRow[] }>(credentials(args), \"GET\", `${HUB}${query({ query: search })}`);\n return res.connectors ?? [];\n}\n\n/** `pull` flattens each file entry to its text — the same mapping `push` takes. */\nexport function flattenFiles(slug: string, pulled: Pulled): Record<string, string> {\n const files: Record<string, string> = {};\n for (const [p, entry] of Object.entries(pulled.files ?? {})) {\n if (!entry || typeof entry !== \"object\" || entry.type !== \"file\" || typeof entry.content !== \"string\")\n throw new CliError(`${slug}: ${p} is not a file entry; a connector template holds files only`, 1);\n files[p] = entry.content;\n }\n return files;\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError, arg, type CommandGroup } from \"../router\";\nimport { api, resolveCredentials, type Credentials } from \"../config\";\nimport {\n credentialsForRuntime,\n localRuntime,\n localRuntimeReason,\n} from \"./local\";\nimport { isCarriedTemplatePath } from \"../platform/connector\";\nimport {\n readWorldFiles,\n runtime,\n sortedJson,\n withoutFiles,\n worldPayload,\n writeWorldFiles,\n type WorldFile,\n} from \"./client\";\n\n/**\n * `gateway worlds schema …` — the gateway-world/1 contract commands. Every one\n * of them used to run the Python compiler locally; they now send the\n * directory to the platform's runtime and print what the Python CLI printed.\n */\n\nconst HOST_FLAG = {\n name: \"host\",\n help: \"Platform host (default: GATEWAY_HOST or the saved login).\",\n env: \"GATEWAY_HOST\",\n};\n\n/** The `[ui]` section `schema ui init` writes into a connector.toml that has\n * none: the same one the shipped templates carry. */\nexport const UI_SECTION =\n \"# The browsable UI over these routes: `gateway worlds schema compile` generates\\n\" +\n \"# ui/static (index.html, app.js, contract.json) from the contract; a session\\n\" +\n \"# opened with `--surface ui` serves it and `--surface browser` drives it. Set\\n\" +\n \"# `generated = false` to hand-write ui/static instead.\\n\" +\n \"[ui]\\n\" +\n 'static = \"ui/static\"\\n' +\n 'entry = \"/\"\\n' +\n \"generated = true\\n\";\n\n/** The flat `key = value` pairs of connector.toml's `[ui]`, or `{}`. */\nexport function uiSection(toml: string): Record<string, string> {\n const start = /^\\[ui\\]\\s*$/m.exec(toml);\n if (!start) return {};\n const rest = toml.slice(start.index + start[0].length);\n const end = /^\\[\\[?[^\\]]+\\]\\]?\\s*$/m.exec(rest); // `[[operations]]` ends it too\n const out: Record<string, string> = {};\n for (const line of (end ? rest.slice(0, end.index) : rest).split(\"\\n\")) {\n const m = /^\\s*([A-Za-z_][\\w-]*)\\s*=\\s*(.+?)\\s*$/.exec(line);\n if (!m) continue;\n const value = m[2]!.replace(/\\s+#.*$/, \"\");\n const quoted = /^\"(.*)\"$|^'(.*)'$/.exec(value);\n out[m[1]!] = quoted ? (quoted[1] ?? quoted[2] ?? \"\") : value;\n }\n return out;\n}\n\n/** Declare `[ui]` in `dir`/connector.toml unless it already does; true when\n * the section was added. Before the first `[[operations]]` so it reads with\n * the other tables, at the end when the file declares no routes yet. */\nexport function declareUi(dir: string): boolean {\n const spec = path.join(dir, \"connector.toml\");\n if (!fs.existsSync(spec))\n throw new CliError(\n `${dir} has no connector.toml: a ui shows the world's routes, and this world declares none. ` +\n \"Add the vendor's routes first (`gateway worlds connector route add`), or start from a connector template.\",\n );\n const text = fs.readFileSync(spec, \"utf8\");\n if (/^\\[ui\\]\\s*$/m.test(text)) return false;\n const firstRoute = /^\\[\\[operations\\]\\]/m.exec(text);\n const next = firstRoute\n ? text.slice(0, firstRoute.index) +\n UI_SECTION +\n \"\\n\" +\n text.slice(firstRoute.index)\n : text.replace(/\\n*$/, \"\\n\") + \"\\n\" + UI_SECTION;\n fs.writeFileSync(spec, next);\n return true;\n}\n\ntype TemplateSummary = {\n slug: string;\n name?: string;\n description?: string;\n entities?: string[];\n tools?: string[];\n};\n\nasync function listTemplates(\n creds: Credentials | null,\n): Promise<TemplateSummary[]> {\n // The local runtime answers directly; the platform's memoized route is\n // only for a machine that has no Python.\n if (!creds || localRuntime()) {\n const res = await runtime<{ templates?: TemplateSummary[] | string[] }>(\n creds,\n {\n command: \"templates\",\n },\n );\n return normalizeTemplates(res.templates);\n }\n try {\n const res = await api<\n { templates?: TemplateSummary[] } | TemplateSummary[]\n >(creds, \"GET\", \"/api/public/worlds/templates\");\n const templates = Array.isArray(res) ? res : res.templates;\n if (Array.isArray(templates)) return templates;\n } catch {\n // Fall through to the runtime: older deployments have only the bridge.\n }\n return normalizeTemplates(\n (\n await runtime<{ templates?: TemplateSummary[] | string[] }>(creds, {\n command: \"templates\",\n })\n ).templates,\n );\n}\n\nfunction normalizeTemplates(\n raw: TemplateSummary[] | string[] | undefined,\n): TemplateSummary[] {\n const res = { templates: raw };\n return (res.templates ?? []).map((t) =>\n typeof t === \"string\" ? { slug: t } : t,\n );\n}\n\nfunction assertEmptyTarget(dir: string): void {\n if (!fs.existsSync(dir)) return;\n if (!fs.statSync(dir).isDirectory())\n throw new CliError(`${dir} exists and is not a directory`);\n if (fs.readdirSync(dir).length > 0)\n throw new CliError(`${dir} must be a new or empty directory`);\n}\n\nconst WORKSPACE_PREFIX = \"workspace:\";\n\n/** What to run after `schema init`, in order. A blank world is a contract with\n * one example entity and nothing else, so the steps that make it a world —\n * entities, the API surface (connector.toml), a graded task — come first; a\n * template already carries those and goes straight to data and publishing. */\nexport function initNextSteps(\n dir: string,\n shape: { hasRoutes: boolean; blank: boolean },\n): string[] {\n const steps: string[] = [];\n if (shape.blank)\n steps.push(\n `gateway worlds schema entity add ${dir} <entity> --fields id:string,name:string --key id`,\n );\n if (!shape.hasRoutes)\n steps.push(\n `gateway worlds connector route add ${dir} list_<entity> --path /<entity> --entity <entity> # API surface; creates connector.toml`,\n );\n if (shape.blank)\n steps.push(\n `gateway worlds schema task add ${dir} <task_id> --prompt \"<what the agent is told>\" --verifier state_present`,\n `gateway worlds schema compile ${dir}`,\n );\n steps.push(\n `gateway worlds schema check ${dir}`,\n `gateway worlds data import ${dir} <rows.json>`,\n `gateway worlds serve ${dir}`,\n `gateway worlds create <slug> --from ${dir}`,\n );\n return steps;\n}\n\n/** `resolveCredentials`, with why this step needs the platform in front of\n * its refusal — the refusal itself names `--host`, `GATEWAY_HOST` and the\n * login command. */\nfunction platformCredentials(\n hostFlag: string | undefined,\n why: string,\n): Credentials {\n try {\n return resolveCredentials(hostFlag);\n } catch (error) {\n if (!(error instanceof CliError)) throw error;\n throw new CliError(`${why} ${error.message}`, error.exitCode);\n }\n}\n\n/** A workspace connector's template, from the platform's copy: the Python CLI\n * pulls `/api/public/context/connectors/<slug>` and hands the files to the\n * compiler; here the compiler is the bridge's `init-template-files`. */\nasync function pullWorkspaceTemplate(\n creds: Credentials,\n slug: string,\n): Promise<{ files: WorldFile[]; commit: string | null }> {\n const pulled = await api<{\n commit?: { commitHash?: string; id?: string };\n files?: Record<string, { type?: string; content?: unknown }>;\n }>(\n creds,\n \"GET\",\n `/api/public/context/connectors/${encodeURIComponent(slug)}`,\n );\n const files: WorldFile[] = [];\n for (const [rel, entry] of Object.entries(pulled.files ?? {})) {\n if (!entry || entry.type !== \"file\" || typeof entry.content !== \"string\")\n throw new CliError(\n `${slug}: ${rel} is not a file entry; a connector template holds files only`,\n 1,\n );\n files.push({\n path: rel,\n content: Buffer.from(entry.content, \"utf8\").toString(\"base64\"),\n });\n }\n if (!files.length)\n throw new CliError(`${slug}: the workspace connector has no files`, 1);\n return {\n files,\n commit: pulled.commit?.commitHash ?? pulled.commit?.id ?? null,\n };\n}\n\ntype ContractReport = Record<string, unknown> & { files?: WorldFile[] };\n\n/** One `relationships` entry as text: `account_id -> crm_accounts`. */\nfunction relationshipText(relationship: unknown): string {\n const r = (relationship ?? {}) as Record<string, unknown>;\n const fields = Array.isArray(r.fields) ? r.fields.join(\"+\") : \"?\";\n return `${fields} -> ${String(r.target ?? \"?\")}`;\n}\n\n/** One `dependencies` entry as text, in either shape: the platform's resolved\n * link (`dependsOn: {slug, versionId}`) or the manifest's own, as the bridge's\n * describe of a directory reports it (`pin`, `path`, `tools`). A local pin is\n * not resolved here — the platform resolves it on create/push — and that is\n * said rather than rendered as `?@?`. */\nfunction linkText(dep: Record<string, unknown>): string {\n const on = dep.dependsOn as Record<string, unknown> | undefined;\n if (on)\n return `${String(dep.alias)} -> ${String(on.slug ?? \"?\")}@${String(on.versionId ?? \"?\").slice(0, 12)}`;\n const pin = dep.pin ?? `${String(dep.slug ?? \"?\")}@${String(dep.ref ?? \"?\")}`;\n const notes: string[] = [];\n if (typeof dep.path === \"string\" && dep.path) notes.push(`path ${dep.path}`);\n else notes.push(\"unresolved locally, resolves on create/push\");\n if (typeof dep.task === \"string\" && dep.task) notes.push(`task ${dep.task}`);\n if (Array.isArray(dep.tools) && dep.tools.length)\n notes.push(`tools ${dep.tools.join(\", \")}`);\n return `${String(dep.alias)} -> ${String(pin)} (${notes.join(\"; \")})`;\n}\n\n/**\n * The `describe` summary as text, the way the Python `describe` renders a\n * bundle; `--json` prints the document itself. Reads both shapes: the bridge's\n * (`domainId`, `packageVersion`, `connection`) and the platform's\n * `GET /api/public/worlds/{slug}` (`slug`, `version.semanticVersion`, tools\n * with `doc`). A field's `[redact]` policy prints as a tag after its type, an\n * entity's row count after its name, its relationships on a line of their own.\n */\nexport function renderDescription(\n description: Record<string, unknown>,\n): string {\n const lines: string[] = [];\n const domain = description.domainId ?? description.slug ?? \"(no $id)\";\n const pinned = description.version as Record<string, unknown> | undefined;\n const semver = description.packageVersion ?? pinned?.semanticVersion;\n lines.push(`${String(domain)}${semver ? ` v${String(semver)}` : \"\"}`);\n const entities = Array.isArray(description.entities)\n ? description.entities\n : [];\n if (entities.length) {\n lines.push(\"\", \"Entities:\");\n for (const entity of entities as Record<string, unknown>[]) {\n const pk = Array.isArray(entity.primaryKey)\n ? entity.primaryKey.join(\", \")\n : \"\";\n const rows =\n typeof entity.rowCount === \"number\"\n ? ` (rows: ${entity.rowCount})`\n : \"\";\n lines.push(` ${String(entity.name)}${pk ? ` (pk: ${pk})` : \"\"}${rows}`);\n for (const field of (Array.isArray(entity.fields)\n ? entity.fields\n : []) as Record<string, unknown>[]) {\n const tag = field.redaction ? ` [${String(field.redaction)}]` : \"\";\n lines.push(\n ` ${String(field.name)}: ${String(field.type ?? \"any\")}${field.required ? \"\" : \"?\"}${tag}`,\n );\n }\n if (Array.isArray(entity.relationships) && entity.relationships.length)\n lines.push(\n ` relationships: ${entity.relationships.map(relationshipText).join(\", \")}`,\n );\n }\n }\n const deps = Array.isArray(description.dependencies)\n ? (description.dependencies as Record<string, unknown>[])\n : [];\n if (deps.length) {\n lines.push(\"\", \"Links:\");\n for (const dep of deps) {\n lines.push(` ${linkText(dep)}`);\n for (const m of (Array.isArray(dep.entities)\n ? dep.entities\n : []) as Record<string, unknown>[]) {\n const chain =\n Array.isArray(m.transform) && m.transform.length\n ? ` via ${m.transform.join(\", \")}`\n : \"\";\n lines.push(\n ` ${String(m.localEntity)}.${String(m.localField)} -> ${String(m.depEntity)}.${String(m.depField)}${chain}`,\n );\n }\n }\n }\n const tools = Array.isArray(description.tools) ? description.tools : [];\n if (tools.length) {\n lines.push(\"\", \"Tools:\");\n for (const tool of tools) {\n if (typeof tool === \"string\") lines.push(` ${tool}`);\n else {\n const t = tool as Record<string, unknown>;\n const doc = t.description ?? t.doc;\n lines.push(` ${String(t.name)}${doc ? `: ${String(doc)}` : \"\"}`);\n }\n }\n }\n const connection = description.connection as\n | Record<string, unknown>\n | null\n | undefined;\n if (connection) {\n lines.push(\n \"\",\n `Connection: ${String(connection.slug)} ${String(connection.baseUrl)} auth=${String(connection.auth)}`,\n );\n for (const op of (Array.isArray(connection.operations)\n ? connection.operations\n : []) as Record<string, unknown>[]) {\n const target = op.entity ? ` -> ${String(op.entity)}` : \"\";\n lines.push(\n ` ${String(op.name)}: ${String(op.method)} ${String(op.path)}${target}`,\n );\n }\n }\n return lines.join(\"\\n\");\n}\n\n/** The bridge's `describe` of a world directory: entities (fields stamped\n * with their `[redact]` policy), tools, and the vendor connection with its\n * `redact` table. `gateway worlds describe` adds the row counts on top. */\nexport async function describeLocalWorld(\n dir: string,\n creds: Credentials | null,\n): Promise<Record<string, unknown>> {\n const res = await runtime<{ description?: Record<string, unknown> }>(creds, {\n command: \"describe\",\n files: readWorldFiles(dir),\n });\n return res.description ?? {};\n}\n\n/** The description with `rowCount` on every entity: the count the store\n * reports, or null for an entity it does not count. */\nexport function withRowCounts(\n description: Record<string, unknown>,\n counts: Record<string, number>,\n): Record<string, unknown> {\n const entities = (\n Array.isArray(description.entities) ? description.entities : []\n ) as Record<string, unknown>[];\n return {\n ...description,\n entities: entities.map((entity) => ({\n ...entity,\n rowCount:\n typeof counts[String(entity.name)] === \"number\"\n ? counts[String(entity.name)]\n : null,\n })),\n };\n}\n\nexport function registerSchemaCommands(schema: CommandGroup): void {\n schema.command({\n name: \"templates\",\n help: \"List the installed connector templates; `custom` is always offered last.\",\n flags: [\n {\n name: \"json\",\n help: \"Print each template's name, description, entities and tools.\",\n boolean: true,\n },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const templates = await listTemplates(creds);\n if (arg.bool(args, \"json\")) {\n ctx.stdout(JSON.stringify(templates, null, 2));\n return;\n }\n const slugs = templates.map((t) => t.slug).filter((s) => s !== \"custom\");\n if (templates.some((t) => t.slug === \"custom\")) slugs.push(\"custom\");\n for (const slug of slugs) ctx.stdout(slug);\n },\n });\n\n schema.command({\n name: \"init\",\n help: \"Initialize a schema world (the one supported world shape) from a connector template or blank, then compile it.\",\n positionals: [\n { name: \"path\", help: \"New or empty directory for the world\" },\n ],\n flags: [\n {\n name: \"connector\",\n help:\n \"Connector template slug; `custom` is the blank contract (one example entity, no tools, no API routes \" +\n \"yet), `workspace:<slug>` a workspace connector pulled from the platform. `gateway worlds schema templates` \" +\n \"lists what is installed.\",\n default: \"custom\",\n },\n { name: \"name\", help: \"Environment name and package id\" },\n {\n name: \"with-example-tool\",\n help:\n \"With --connector custom: also write tools/handlers.py with list_records, get_record and create_record \" +\n \"over the example entity, declared in gateway-env.toml, so the world has tools to call and test from the start.\",\n boolean: true,\n },\n HOST_FLAG,\n ],\n notes:\n \"The world is a gateway-world/1 tree: schema/world.json (entities), gateway-env.toml ([schema], [tools],\\n\" +\n \"[[tasks]]), tools/handlers.py, verifiers/*.sql, and connector.toml + api/handlers.py for its API surface.\\n\" +\n \"A shipped template arrives with its routes; a custom world declares its own with\\n\" +\n \"`gateway worlds connector route add`, which creates connector.toml on the first route. The output's\\n\" +\n \"`next` lists the commands in order.\",\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const connector = arg.str(args, \"connector\") ?? \"custom\";\n const name = arg.str(args, \"name\");\n const withExampleTool = arg.bool(args, \"with-example-tool\");\n if (withExampleTool && connector !== \"custom\")\n throw new CliError(\n \"--with-example-tool goes with --connector custom; a connector template ships its own tools\",\n );\n assertEmptyTarget(dir);\n const hostFlag = arg.str(args, \"host\");\n const workspace = connector.startsWith(WORKSPACE_PREFIX);\n let report: ContractReport;\n let commit: string | null = null;\n if (workspace) {\n // A workspace connector lives on the platform: this always needs a host.\n const slug = connector.slice(WORKSPACE_PREFIX.length);\n if (!slug)\n throw new CliError(\"workspace:<slug> needs the connector's slug\");\n const creds = platformCredentials(\n hostFlag,\n `${connector} pulls the connector from the platform.`,\n );\n const pulled = await pullWorkspaceTemplate(creds, slug);\n commit = pulled.commit;\n // Brex retrospective: tests/, tasks.json, verifiers/ and openapi/ travel with\n // the connector but are not contract — the runtime's init refuses paths it\n // does not lay out — so they are written beside what it builds.\n const carried = pulled.files.filter((file) =>\n isCarriedTemplatePath(file.path),\n );\n const contract = pulled.files.filter(\n (file) => !isCarriedTemplatePath(file.path),\n );\n report = await runtime<ContractReport>(creds, {\n command: \"init-template-files\",\n connector: slug,\n files: contract,\n ...(name ? { name } : {}),\n });\n report.files = [...(report.files ?? []), ...carried];\n } else {\n // A shipped template (and `custom`) is in the bundled runtime: with a\n // python3 on this machine it is written here and no credential is\n // resolved at all — no host, no keys, no config file. Without the\n // runtime the platform scaffolds it, and the refusal names both gaps.\n const creds = localRuntime()\n ? null\n : platformCredentials(\n hostFlag,\n `${connector} is a shipped template and scaffolds offline with the bundled runtime, but ` +\n `${localRuntimeReason()} Without it the platform scaffolds it.`,\n );\n report = await runtime<ContractReport>(creds, {\n command: \"init-template\",\n connector,\n ...(name ? { name } : {}),\n ...(withExampleTool ? { with_example_tool: true } : {}),\n });\n }\n const files = report.files ?? [];\n if (!files.length)\n throw new CliError(\n \"The runtime compiled the world but returned no files\",\n 1,\n );\n writeWorldFiles(dir, files);\n const hasRoutes = fs.existsSync(path.join(dir, \"connector.toml\"));\n const out: Record<string, unknown> = {\n status: \"ok\",\n domain: report.domain,\n kind: \"schema\",\n api: hasRoutes ? \"connector.toml\" : null,\n next: initNextSteps(args.positionals[0]!, { hasRoutes, blank: connector === \"custom\" }),\n };\n if (workspace)\n out.connector = {\n slug: connector.slice(WORKSPACE_PREFIX.length),\n commit,\n };\n ctx.stdout(sortedJson(out, 0));\n },\n });\n\n for (const [command, help] of [\n [\n \"compile\",\n \"Compile the world's contract on the platform and write back what the compiler produced.\",\n ],\n [\n \"check\",\n \"Check the world's contract, its handlers, verifiers, tasks and [dependencies] links; writes nothing.\",\n ],\n ] as const) {\n schema.command({\n name: command,\n help,\n positionals: [{ name: \"path\", help: \"World directory\" }],\n flags: [HOST_FLAG],\n ...(command === \"check\"\n ? {\n notes:\n \"With the bundled runtime (a python3 on this machine) the world is checked in place: its handlers are\\n\" +\n \"imported and every declared tool bound (`handler_execution.status: ok`), the verifiers run over the\\n\" +\n \"initial state (`verifiers.<name>.initial_score`), and each `[dependencies]` entry with a `path` is\\n\" +\n \"opened beside it so a cross-world verifier runs too. On the platform the handlers report `not_run`.\",\n }\n : {}),\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const report = await runtime<ContractReport>(\n creds,\n command === \"compile\"\n ? { command: \"compile\", files: readWorldFiles(dir) }\n : {\n command: \"validate\",\n ...worldPayload(dir),\n ...(localRuntime() ? { execute: true } : {}),\n },\n );\n if (command === \"compile\" && report.files?.length)\n writeWorldFiles(dir, report.files);\n ctx.stdout(sortedJson(withoutFiles(report), 0));\n },\n });\n }\n\n schema.command({\n name: \"describe\",\n help: \"Describe the world's contract: entities, tools and the vendor connection it answers to.\",\n positionals: [{ name: \"path\", help: \"World directory\" }],\n flags: [\n {\n name: \"json\",\n help: \"Print the description document as JSON.\",\n boolean: true,\n },\n HOST_FLAG,\n ],\n notes:\n \"`gateway worlds describe <dir|slug>` is the same view with row counts, and works on a platform slug.\",\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const description = await describeLocalWorld(dir, creds);\n if (arg.bool(args, \"json\"))\n ctx.stdout(JSON.stringify(description, null, 2));\n else ctx.stdout(renderDescription(description));\n },\n });\n\n schema.command({\n name: \"api-bundle\",\n help: \"Write the api-kind bundle that hosts this world's API (built by the platform runtime).\",\n positionals: [\n { name: \"path\", help: \"World directory holding connector.toml\" },\n {\n name: \"out\",\n help: \"Empty (or absent) directory for the api-kind bundle\",\n },\n ],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const [dir, out] = args.positionals as [string, string];\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const res = await runtime<{\n files?: { path: string; content: string }[];\n }>(creds, {\n command: \"api-bundle\",\n files: readWorldFiles(dir),\n });\n writeWorldFiles(out, res.files ?? [], { clean: false });\n ctx.stdout(`api bundle: ${out}`);\n },\n });\n\n schema\n .group(\"ui\", \"The world's browsable UI, generated from its contract.\")\n .command({\n name: \"init\",\n help: \"Declare [ui] in connector.toml (when missing) and generate ui/static from the contract.\",\n positionals: [\n { name: \"path\", help: \"World directory holding connector.toml\" },\n ],\n flags: [HOST_FLAG],\n notes:\n \"Writes ui/static/{index.html, app.js, contract.json}: a dependency-free page that lists, reads, creates,\\n\" +\n \"updates and deletes every entity through the world's own routes, with foreign keys linked. `schema compile`\\n\" +\n \"regenerates it as the contract changes; set `[ui] generated = false` to hand-write the directory instead.\\n\" +\n \"`worlds serve` mounts it at /__ui/; `worlds session open --surface ui,browser` serves it on the session's\\n\" +\n \"ui origin and `worlds session browse` drives it. A world with no connector.toml has no routes for a ui to\\n\" +\n \"call and is refused.\",\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const declared = declareUi(dir);\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const report = await runtime<ContractReport>(creds, {\n command: \"compile\",\n files: readWorldFiles(dir),\n });\n if (report.files?.length) writeWorldFiles(dir, report.files);\n const ui = uiSection(\n fs.readFileSync(path.join(dir, \"connector.toml\"), \"utf8\"),\n );\n const staticDir = ui.static ?? \"ui/static\";\n const files = (report.files ?? [])\n .map((f) => f.path)\n .filter((p) => p.startsWith(`${staticDir}/`));\n ctx.stdout(\n sortedJson(\n {\n status: \"ok\",\n declared,\n ui: {\n static: staticDir,\n entry: ui.entry ?? \"/\",\n generated: ui.generated !== \"false\",\n },\n files,\n domain: report.domain,\n },\n 0,\n ),\n );\n },\n });\n\n schema.command({\n name: \"reconcile\",\n help: \"Reconcile the contract with what the vendor really returned: relax required fields the captures omit, add undocumented keys as optional properties, drop formats the captured values do not meet.\",\n positionals: [\n {\n name: \"path\",\n help: \"World directory holding schema/world.json and captures/\",\n },\n ],\n flags: [\n {\n name: \"from\",\n help: \"Where the observed rows come from (captures).\",\n default: \"captures\",\n },\n {\n name: \"write\",\n help: \"Rewrite schema/world.json and recompile; without it only the report prints.\",\n boolean: true,\n },\n HOST_FLAG,\n ],\n notes:\n \"Brex retrospective: the documents drift from the live account (snake_case where the docs say camelCase, undocumented\\n\" +\n \"keys, required fields omitted, timestamps without a zone). Reconciling from the captures is the pass every\\n\" +\n \"connector needed by hand; it changes top-level fields only and lists every change it makes.\",\n run: async (args, ctx) => {\n const dir = args.positionals[0]!;\n const write = arg.bool(args, \"write\");\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n type Change = {\n entity: string;\n field: string;\n change: string;\n detail: string;\n };\n const res = await runtime<{\n report?: {\n source?: string;\n written?: boolean;\n entities?: Record<string, number>;\n changes?: Change[];\n };\n files?: { path: string; content: string }[];\n }>(creds, {\n command: \"reconcile\",\n files: readWorldFiles(dir),\n from: arg.str(args, \"from\") ?? \"captures\",\n ...(write ? { write: true } : {}),\n });\n const report = res.report ?? {};\n const changes = report.changes ?? [];\n const compared = Object.values(report.entities ?? {}).reduce(\n (a, b) => a + b,\n 0,\n );\n ctx.stdout(\n `reconciled from ${report.source ?? \"captures\"}: ${compared} captured rows compared, ${changes.length} changes`,\n );\n for (const c of changes)\n ctx.stdout(` ${c.entity}.${c.field} ${c.change} ${c.detail}`);\n if (write && res.files?.length) {\n writeWorldFiles(dir, res.files);\n ctx.stdout(`written: schema/world.json (${changes.length} changes)`);\n } else if (write) ctx.stdout(\"nothing to write\");\n else if (changes.length) ctx.stdout(\"dry run; add --write to apply\");\n },\n });\n}\n","import { api, type Credentials } from \"../../config\";\nimport { CliError } from \"../../router\";\nimport type { ObservationLike } from \"../../../worlds/ingest\";\n\n/**\n * TOOL observations out of the platform, for `gateway worlds data ingest\n * --from traces`: by trace id (`GET /api/public/observations?type=TOOL&traceId=`,\n * paged), by session (`GET /api/public/sessions/{id}?includeIO=true`, every\n * trace's observations in one call), or by time window alone\n * (`GET /api/public/observations?type=TOOL&fromStartTime=`). The conversion\n * to records is `toolCallsFromObservations`; this only fetches.\n */\n\nexport type TraceCallSelection = {\n traceIds: string[];\n sessionId?: string;\n since?: string;\n until?: string;\n};\n\nconst PAGE = 100;\n\nexport async function fetchToolObservations(creds: Credentials, selection: TraceCallSelection): Promise<ObservationLike[]> {\n const { traceIds, sessionId, since, until } = selection;\n if (!traceIds.length && !sessionId && !since) throw new CliError(\"--from traces needs --trace, --session or --since to say which calls\");\n if (sessionId) {\n const session = await api<{ traces?: { id?: string; observations?: ObservationLike[] }[] }>(\n creds,\n \"GET\",\n `/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`,\n );\n const wanted = traceIds.length ? new Set(traceIds) : null;\n const out: ObservationLike[] = [];\n for (const trace of session.traces ?? []) {\n if (wanted && (!trace.id || !wanted.has(trace.id))) continue;\n for (const observation of trace.observations ?? []) out.push({ traceId: trace.id ?? null, ...observation });\n }\n return out;\n }\n const out: ObservationLike[] = [];\n const window = { ...(since ? { fromStartTime: since } : {}), ...(until ? { toStartTime: until } : {}) };\n if (traceIds.length) {\n for (const traceId of traceIds) out.push(...(await pagedObservations(creds, { traceId, ...window })));\n return out;\n }\n return pagedObservations(creds, window);\n}\n\nasync function pagedObservations(creds: Credentials, params: Record<string, string>): Promise<ObservationLike[]> {\n const out: ObservationLike[] = [];\n for (let page = 1; ; page++) {\n const query = new URLSearchParams({ type: \"TOOL\", limit: String(PAGE), page: String(page), ...params });\n const answer = await api<{ data?: ObservationLike[]; meta?: { totalPages?: number } }>(creds, \"GET\", `/api/public/observations?${query.toString()}`);\n const items = answer.data ?? [];\n out.push(...items);\n const totalPages = answer.meta?.totalPages ?? (items.length < PAGE ? page : page + 1);\n if (!items.length || page >= totalPages) break;\n }\n return out;\n}\n","import { CommandGroup, dispatch } from \"./router\";\nimport { ENV_FILE_FORM, loadEnvFile } from \"./config\";\nimport { registerPlatformCommands } from \"./platform/index\";\nimport { registerRuntimeCommands } from \"./runtime/index\";\n\n/** The whole tree, built once; `gateway --help` lists the groups. */\nexport function buildCli(): CommandGroup {\n const root = new CommandGroup(\n \"gateway\",\n \"Gateway: worlds, benchmarks, connectors, sessions, runs and releases from the terminal.\\n\\n\" +\n \" Credentials: --host or GATEWAY_HOST, plus GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY,\\n\" +\n \" or `gateway auth login`. \" +\n ENV_FILE_FORM,\n );\n root.notes =\n \"Start here: `gateway worlds --help` (a mock world of a vendor) or `gateway benchmarks --help` (a benchmark:\\n\" +\n \"a world with tasks, or a harbor / verifiers container benchmark). Packaged guides for an agent:\\n\" +\n \"`gateway skill search <words>` finds one by topic,\\n\" +\n \"`gateway worlds skill worlds-getting-started` / `benchmarks-getting-started` prints it.\";\n root.group(\"auth\", \"Save or inspect the platform credentials this CLI uses.\");\n root.group(\"secret\", \"Project secrets (write-only).\");\n root.group(\"agent\", \"Registered agents.\");\n root.group(\"run\", \"Platform optimization runs.\");\n root.group(\"dataset\", \"Datasets and task files.\");\n root.group(\n \"bench\",\n \"Versions of a world or benchmark: push, pull, fork, diff, propose, dispatch.\",\n );\n root.group(\n \"benchmarks\",\n \"Build, validate, dry-run, push, run and read a benchmark: a world with tasks, or a container benchmark, in benchmark order.\",\n );\n const worlds = root.group(\"worlds\", \"Build, seed, serve and run worlds.\");\n worlds.notes =\n \"New here? `gateway worlds skill worlds-getting-started` is the walkthrough. A world is a directory:\\n\" +\n \" schema init <dir> --connector custom|<template> [--with-example-tool] scaffold it (needs no credentials)\\n\" +\n \" schema entity add · schema link · schema task add declare entities, link another world, add a task\\n\" +\n \" schema check <dir> · test <dir> · data import <dir> · data show <dir> check it, run its tests, put rows in, read them\\n\" +\n \" serve <dir> --task <id> then call <url> <tool> [--state|--grade|--close] act on it as an agent would\\n\" +\n \"Everything above runs locally; `worlds create`, `bench push` and `session` need `gateway auth login`.\\n\" +\n \"Building a benchmark (tasks graded on this world, run k times per model)? `gateway benchmarks --help` —\\n\" +\n \"the same commands in benchmark order; skill `benchmarks-getting-started`.\";\n worlds.group(\n \"session\",\n \"Live hosted sessions with api, ui and browser surfaces.\",\n );\n const schema = worlds.group(\n \"schema\",\n \"Compile and check gateway-world/1 contracts (the runtime runs on the platform).\",\n );\n schema.notes =\n \"Order of work: init → entity add (or edit schema/world.json) → tools/handlers.py → check → link → task add.\\n\" +\n \"`check` names what is missing; `gateway worlds skill connector-schema-authoring` explains the files.\";\n worlds.group(\n \"connector\",\n \"Vendor connections: validate, capture, conform, ingest, publish, clone.\",\n );\n worlds.group(\"data\", \"Put rows into a world, or see what it holds.\");\n root.group(\n \"environment\",\n \"Environments: runs, tasks, rollouts, performance, agent triggers.\",\n );\n root.group(\"release\", \"Release gates.\");\n root.group(\"traces\", \"Traces, observations and trace sessions: list, get, export; import OTLP.\");\n root.group(\"files\", \"The project's file drive: upload, list, download, move, delete.\");\n root.group(\"skill\", \"The packaged guides for an agent: list them, search them by topic, print one.\");\n registerPlatformCommands(root);\n registerRuntimeCommands(root);\n return root;\n}\n\nexport async function main(argv = process.argv.slice(2)): Promise<number> {\n // Before anything reads the environment: an env file the user named, in the\n // form people write (`KEY = \"value\"`), so `.env` need not be shell-sourceable.\n loadEnvFile();\n const stdinOnce = async () => {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) chunks.push(chunk as Buffer);\n return Buffer.concat(chunks).toString(\"utf8\");\n };\n return dispatch(buildCli(), argv, {\n stdout: (line) => process.stdout.write(line + \"\\n\"),\n stderr: (line) => process.stderr.write(line + \"\\n\"),\n stdin: stdinOnce,\n stdinStream: () => process.stdin,\n });\n}\n","import { api } from \"../config\";\nimport type { CommandGroup } from \"../router\";\nimport { API_KEY_FLAG, credentials, HOST_FLAG } from \"./shared\";\n\nexport type AgentRow = {\n name?: string;\n image?: string;\n compatibleAlgorithms?: string[];\n taskInputSchema?: unknown;\n};\n\n/** `gateway agent list` over /api/public/agents. */\nexport function registerAgentCommands(root: CommandGroup): void {\n const agent = root.group(\"agent\", \"Manage registered agents.\");\n\n agent.command({\n name: \"list\",\n help: \"List registered agents.\",\n flags: [HOST_FLAG, API_KEY_FLAG],\n run: async (args, ctx) => {\n const res = await api<{ agents?: AgentRow[] }>(credentials(args), \"GET\", \"/api/public/agents\");\n const agents = res.agents ?? [];\n if (agents.length === 0) {\n ctx.stdout(\"No agents registered. Run `gateway deploy` to register an agent.\");\n return;\n }\n ctx.stdout(`${\"Name\".padEnd(20)} ${\"Image\".padEnd(30)} Compatible`);\n ctx.stdout(\"-\".repeat(70));\n for (const a of agents) {\n const compat = (a.compatibleAlgorithms ?? []).join(\", \");\n ctx.stdout(`${(a.name ?? \"\").padEnd(20)} ${(a.image ?? \"\").slice(0, 28).padEnd(30)} ${compat}`);\n }\n },\n });\n}\n","import { clearConfig, configPath, ENV_FILE_FORM, readConfig, writeConfig } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\n\n/** `gateway auth login|logout|status` — the credentials file the other commands read. */\nexport function registerAuthCommands(root: CommandGroup): void {\n const auth = root.group(\"auth\", \"Manage authentication credentials.\");\n\n auth.command({\n name: \"login\",\n help: \"Store credentials for the gateway CLI.\",\n flags: [\n { name: \"host\", help: \"Gateway server URL\", env: \"GATEWAY_HOST\" },\n { name: \"public-key\", help: \"Project public key (pk-lf-...)\", env: \"GATEWAY_PUBLIC_KEY\" },\n { name: \"api-key\", help: \"Project secret key (sk-lf-...)\", env: \"GATEWAY_SECRET_KEY\" },\n ],\n notes:\n \"The Python CLI prompts for what is missing; here pass all three flags (or set the env vars).\\n\" +\n ENV_FILE_FORM,\n run: async (args, ctx) => {\n const host = arg.str(args, \"host\");\n const publicKey = arg.str(args, \"public-key\");\n const apiKey = arg.str(args, \"api-key\");\n if (!host || !publicKey || !apiKey)\n throw new CliError(\"auth login needs --host, --public-key and --api-key\");\n writeConfig({ host: host.replace(/\\/+$/, \"\"), public_key: publicKey, api_key: apiKey });\n ctx.stdout(`Credentials saved to ${configPath()}`);\n },\n });\n\n auth.command({\n name: \"logout\",\n help: \"Clear stored credentials.\",\n run: async (_args, ctx) => {\n ctx.stdout(clearConfig() ? \"Credentials cleared.\" : \"No credentials stored.\");\n },\n });\n\n auth.command({\n name: \"status\",\n help: \"Show current authentication status.\",\n run: async (_args, ctx) => {\n // The environment wins over the stored file, the same order every\n // command resolves credentials in; say which one is in effect.\n const envHost = process.env.GATEWAY_HOST;\n const envKey = process.env.GATEWAY_SECRET_KEY ?? process.env.GATEWAY_API_KEY;\n if (envHost || envKey) {\n ctx.stdout(`Host: ${envHost ?? \"(not set)\"} (from environment)`);\n ctx.stdout(`API key: ${envKey ? \"configured\" : \"not set\"} (from environment)`);\n return;\n }\n const config = readConfig();\n if (!config.host) {\n ctx.stdout(\"No credentials stored. Run `gateway auth login`.\");\n return;\n }\n ctx.stdout(`Host: ${config.host}`);\n ctx.stdout(`API key: ${config.api_key ? \"configured\" : \"not set\"}`);\n },\n });\n}\n","import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { api, printJson } from \"../config\";\nimport { arg, CliError, type CommandContext, type CommandGroup, type FlagSpec, type Parsed } from \"../router\";\nimport { readWorldFiles, runtime, writeWorldFiles } from \"../runtime/client\";\nimport { credentialsForRuntime } from \"../runtime/local\";\nimport {\n deleteEnvSecret,\n getRun,\n listEnvSecretKeys,\n listRunConfigs,\n openWorld,\n parseWorldTaskRefs,\n setEnvSecret,\n waitForRun,\n} from \"../../worlds/index\";\nimport {\n computeContentHash,\n createRef,\n DEFAULT_BRANCH,\n localTreeState,\n propose,\n pull,\n push,\n readLocalMeta,\n writeLocalMeta,\n} from \"../../worlds/hub\";\nimport { validateWorld } from \"../../worlds/validate\";\nimport { credentials, HOST_FLAG, pythonOnly, query, worldsOptions } from \"./shared\";\n\n// ── semver bumps (port of benchmark_hub/versioning.py) ──────────────────────\n\n/** Patch bump: `1.2.3` -> `1.2.4`; strips a `-`/`+` suffix to find the patch. */\nexport function bumpVersion(version: string): string {\n const parts = version.split(\".\");\n if (parts.length >= 3) {\n const patchPart = parts[2]!;\n const patchNum = patchPart.includes(\"-\")\n ? patchPart.split(\"-\")[0]!\n : patchPart.includes(\"+\")\n ? patchPart.split(\"+\")[0]!\n : patchPart;\n if (/^\\d+$/.test(patchNum)) {\n parts[2] = String(Number(patchNum) + 1);\n return parts.join(\".\");\n }\n return `${version}.1`;\n }\n if (parts.length === 2) return `${version}.1`;\n return `${version}.0.1`;\n}\n\n/** `1.2.3` -> `1.2.3.rc0`, `1.2.3.rc0` -> `1.2.3.rc1`. */\nexport function bumpRcVersion(version: string): string {\n const m = /^(.*?)(?:\\.rc|rc)(\\d+)$/.exec(version);\n if (m) return `${m[1]}.rc${Number(m[2]) + 1}`;\n return `${version.replace(/([+-].*)$/, \"\")}.rc0`;\n}\n\n/** `1.2.3` -> `1.2.3.post0`, `1.2.3.post0` -> `1.2.3.post1`. */\nexport function bumpPostVersion(version: string): string {\n const m = /^(.*?)(?:\\.post|post)(\\d+)$/.exec(version);\n if (m) return `${m[1]}.post${Number(m[2]) + 1}`;\n return `${version.replace(/([+-].*)$/, \"\")}.post0`;\n}\n\nfunction readPyprojectVersion(dir: string): string | undefined {\n try {\n const text = fs.readFileSync(path.join(dir, \"pyproject.toml\"), \"utf8\");\n const section = /\\[project\\]([\\s\\S]*?)(\\n\\[|$)/.exec(text)?.[1] ?? \"\";\n return /\\bversion\\s*=\\s*\"([^\"]+)\"/.exec(section)?.[1];\n } catch {\n return undefined;\n }\n}\n\n/** Rewrite the `version = \"...\"` line in place (formatting and comments kept). */\nexport function updatePyprojectVersion(file: string, newVersion: string): void {\n const content = fs.readFileSync(file, \"utf8\");\n const updated = content.replace(/(\\s*)version\\s*=\\s*[\"'][^\"']*[\"']/, `$1version = \"${newVersion}\"`);\n if (updated === content) throw new CliError(\"version line not found or unchanged in pyproject.toml\", 1);\n fs.writeFileSync(file, updated);\n}\n\n/** Apply `--auto-bump` / `--rc` / `--post` to the working tree before hashing. */\nexport function applyVersionBump(dir: string, args: Parsed): string | null {\n const picked = [\"auto-bump\", \"rc\", \"post\"].filter((name) => arg.bool(args, name));\n if (picked.length === 0) return null;\n if (picked.length > 1) throw new CliError(\"--auto-bump, --rc and --post are mutually exclusive\");\n const current = readPyprojectVersion(dir);\n if (!current)\n throw new CliError(\n `--${picked[0]} needs a [project].version in ${path.join(dir, \"pyproject.toml\")} to bump; this dir has none.`,\n 1,\n );\n const next =\n picked[0] === \"auto-bump\" ? bumpVersion(current) : picked[0] === \"rc\" ? bumpRcVersion(current) : bumpPostVersion(current);\n updatePyprojectVersion(path.join(dir, \"pyproject.toml\"), next);\n return next;\n}\n\n// ── helpers ─────────────────────────────────────────────────────────────────\n\ntype RefRow = {\n name: string;\n kind: string;\n versionId?: string | null;\n semanticVersion?: string | null;\n contentHash?: string | null;\n state?: string | null;\n};\n\nconst VERSION_ID_FLAG: FlagSpec = { name: \"version-id\", help: \"Version id (default: the main tip).\" };\n\nfunction slugForDir(args: Parsed, dir: string): string {\n const slug = arg.str(args, \"slug\") ?? readLocalMeta(dir)?.slug;\n if (!slug) throw new CliError(\"Error: no --slug and this dir tracks no container (pull first).\", 1);\n return slug;\n}\n\n/**\n * `branch`/`tag` take EITHER the Python shape (`<name> --path D --slug S`) or\n * the earlier TypeScript shape (`<slug> <name>`); two positionals mean the latter.\n */\nfunction slugAndName(args: Parsed, kind: \"branch\" | \"tag\"): { slug: string; name: string | undefined } {\n const [first, second] = args.positionals;\n if (second !== undefined) return { slug: first!, name: second };\n const dir = arg.str(args, \"path\") ?? \".\";\n if (first === undefined && kind === \"tag\") throw new CliError(\"bench tag needs <name>\");\n return { slug: slugForDir(args, dir), name: first };\n}\n\n// ── the group ───────────────────────────────────────────────────────────────\n\n/** `gateway bench …` — worlds as versioned bundles. */\n/** A schema world that serves a vendor API: connector.toml beside schema/world.json,\n * and not already packaged (no gateway-api-world.toml at its root). */\nexport function isConnectorWorld(dir: string): boolean {\n return (\n fs.existsSync(path.join(dir, \"connector.toml\")) &&\n fs.existsSync(path.join(dir, \"schema\", \"world.json\")) &&\n !fs.existsSync(path.join(dir, \"gateway-api-world.toml\"))\n );\n}\n\n/** Package a connector world as its api bundle in a scratch directory, carrying\n * the world dir's .gateway base metadata so the push fast-forwards. */\nasync function packageApiBundle(dir: string, args: Parsed, ctx: CommandContext): Promise<string> {\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const res = await runtime<{ files?: { path: string; content: string }[] }>(creds, {\n command: \"api-bundle\",\n files: readWorldFiles(dir),\n });\n const out = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-api-bundle-\"));\n writeWorldFiles(out, res.files ?? [], { clean: false });\n const meta = readLocalMeta(dir);\n if (meta) writeLocalMeta(out, meta);\n ctx.stderr(`packaged ${dir} as its api bundle (${(res.files ?? []).length} files)`);\n return out;\n}\n\nexport function registerBenchCommands(root: CommandGroup): void {\n const bench = root.group(\n \"bench\",\n \"Benchmark container hub — version and push benchmark environments to Gateway.\",\n );\n\n bench.command({\n name: \"push\",\n help: \"Push a benchmark container to Gateway as a content-hashed source bundle.\",\n positionals: [{ name: \"path\", help: \"Path to the environment directory (default: cwd).\", optional: true }],\n flags: [\n { name: \"slug\", help: \"Container slug (defaults to the directory name).\" },\n { name: \"name\", help: \"Human-readable container name.\" },\n { name: \"description\", help: \"Container description.\" },\n { name: \"tag\", help: \"Tag (repeatable).\", repeat: true },\n { name: \"visibility\", help: \"PRIVATE or PUBLIC.\" },\n { name: \"auto-bump\", help: \"Patch-bump pyproject version before pushing.\", boolean: true },\n { name: \"rc\", help: \"Bump/create an .rc pre-release before pushing.\", boolean: true },\n { name: \"post\", help: \"Bump/create a .post release before pushing.\", boolean: true },\n { name: \"image\", help: \"Pre-built OCI image ref for image/agentic envs (recorded on the version).\" },\n {\n name: \"build-wheel\",\n help: \"Build a wheel (uv build --wheel) + upload it — Python-only, refused here.\",\n boolean: true,\n },\n { name: \"branch\", short: \"b\", help: \"Branch to push to (default: the dir's tracked branch, else main).\" },\n { name: \"force\", help: \"Skip the fast-forward check (move the branch even if it diverged).\", boolean: true },\n { name: \"message\", short: \"m\", help: \"Change reason, shown in History.\" },\n { name: \"author\", help: \"Attribution shown in History (default: GATEWAY_AUTHOR env).\", env: \"GATEWAY_AUTHOR\" },\n HOST_FLAG,\n ],\n notes:\n \"The dir's .gateway/.env-metadata.json (written by pull/push) supplies the BASE version —\\n\" +\n \"pushing onto a branch whose tip moved refuses with a 409. --auto-bump/--rc/--post rewrite\\n\" +\n \"[project].version in pyproject.toml before hashing, so the bump lands in the bundle.\\n\" +\n \"A connector world (connector.toml + schema/world.json, no gateway-api-world.toml) is packaged\\n\" +\n \"as its api bundle first — the form the platform hosts — through the schema runtime, and the\\n\" +\n \"bundle is what lands; the directory's own .gateway base metadata is kept in step.\",\n run: async (args, ctx) => {\n if (arg.bool(args, \"build-wheel\"))\n return pythonOnly(\n ctx,\n \"bench push --build-wheel\",\n \"it runs `uv build --wheel` on a Python package.\",\n \"Push without --build-wheel, or build the wheel with the Python CLI.\",\n );\n const dir = args.positionals[0] ?? \".\";\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);\n const options = worldsOptions(credentials(args));\n applyVersionBump(dir, args);\n // A connector world is pushed as its api bundle: the schema runtime\n // packages it (server/world = the authored tree), the bundle is what the\n // platform stores and hosts, and the world dir keeps the base metadata.\n const packaged = isConnectorWorld(dir) ? await packageApiBundle(dir, args, ctx) : null;\n const result = await push(packaged ?? dir, {\n slug: arg.str(args, \"slug\") ?? (packaged ? path.basename(path.resolve(dir)) : undefined),\n name: arg.str(args, \"name\"),\n description: arg.str(args, \"description\"),\n tags: arg.list(args, \"tag\"),\n visibility: arg.str(args, \"visibility\"),\n imageRef: arg.str(args, \"image\"),\n branch: arg.str(args, \"branch\"),\n force: arg.bool(args, \"force\"),\n message: arg.str(args, \"message\"),\n author: arg.str(args, \"author\"),\n options,\n });\n if (packaged) {\n const meta = readLocalMeta(packaged);\n if (meta) writeLocalMeta(dir, meta);\n fs.rmSync(packaged, { recursive: true, force: true });\n }\n printJson(ctx, { ...result, wheelBuilt: false, ...(packaged ? { packaged: \"api-bundle\" } : {}) });\n },\n });\n\n bench.command({\n name: \"pull\",\n help: \"Reconstruct a container version's source directory, addressed by name.\",\n positionals: [{ name: \"slug\", help: \"Container slug, optionally slug@latest | @<semver> | @<hash-prefix>.\" }],\n flags: [\n { name: \"target\", short: \"t\", help: \"Target dir (defaults to ./<slug>).\" },\n { name: \"dir\", help: \"Alias of --target.\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const slugRef = args.positionals[0]!;\n const target = arg.str(args, \"target\") ?? arg.str(args, \"dir\");\n printJson(ctx, await pullJson(slugRef, target, args));\n },\n });\n\n bench.command({\n name: \"checkout\",\n help: \"Materialize a ref into a working dir and track it (pull + set base).\",\n positionals: [{ name: \"slug_ref\", help: \"slug@<branch|tag|semver|hash> (bare slug = main).\" }],\n flags: [\n { name: \"target\", short: \"t\", help: \"Target dir (defaults to ./<slug>).\" },\n { name: \"dir\", help: \"Alias of --target.\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const slugRef = args.positionals[0]!;\n const target = arg.str(args, \"target\") ?? arg.str(args, \"dir\");\n printJson(ctx, await pullJson(slugRef, target, args));\n },\n });\n\n bench.command({\n name: \"fork\",\n help: \"Fork a container into a new one (shares the bundle; records forkedFromVersionId).\",\n positionals: [{ name: \"slug\", help: \"Source container slug (forks the head; omit @version).\" }],\n flags: [{ name: \"into\", help: \"Target slug (defaults to <slug>-fork).\" }, HOST_FLAG],\n run: async (args, ctx) => {\n const slug = args.positionals[0]!;\n if (slug.includes(\"@\")) throw new CliError(\"fork a container head; omit the @version suffix\", 1);\n const into = arg.str(args, \"into\");\n const result = await api(credentials(args), \"POST\", \"/api/public/benchmark-containers/fork\", {\n slug,\n ...(into ? { targetSlug: into } : {}),\n });\n printJson(ctx, result);\n },\n });\n\n bench.command({\n name: \"status\",\n help: \"Where this dir stands: tracked branch, base version, local edits (dirty), remote tip moved (behind).\",\n positionals: [{ name: \"path\", help: \"Working dir (defaults to cwd).\", optional: true }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const dir = args.positionals[0] ?? \".\";\n const meta = readLocalMeta(dir);\n if (!meta?.slug)\n throw new CliError(\n `${dir} has no .gateway/.env-metadata.json — pull or push it first so the dir knows which container/branch it tracks.`,\n 1,\n );\n const branch = meta.branch ?? DEFAULT_BRANCH;\n const localHash = computeContentHash(dir);\n const refs = await api<{ refs: RefRow[] }>(\n credentials(args),\n \"GET\",\n `/api/public/benchmark-containers/refs${query({ slug: meta.slug })}`,\n );\n const tip = refs.refs.find((r) => r.name === branch);\n const behind = Boolean(tip && tip.versionId !== meta.versionId);\n const dirty = localHash !== meta.contentHash;\n printJson(ctx, {\n slug: meta.slug,\n branch,\n baseVersionId: meta.versionId ?? null,\n baseContentHash: meta.contentHash ?? null,\n localContentHash: localHash,\n dirty,\n behind,\n remoteTipVersionId: tip?.versionId ?? null,\n remoteTipContentHash: tip?.contentHash ?? null,\n dirtyFiles: localTreeState(dir).dirty,\n });\n if (dirty) ctx.stderr(\"# local edits not pushed\");\n if (behind) ctx.stderr(\"# branch tip moved past your base — `gateway bench pull` before pushing\");\n },\n });\n\n bench.command({\n name: \"log\",\n help: \"A branch's version lineage, tip first — hash, semver, author, reason.\",\n positionals: [{ name: \"slug\", help: \"Container slug.\" }],\n flags: [\n { name: \"branch\", short: \"b\", help: \"Branch (default main).\" },\n { name: \"limit\", short: \"n\", help: \"Max entries.\", default: \"20\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const result = await api(\n credentials(args),\n \"GET\",\n `/api/public/benchmark-containers/log${query({\n slug: args.positionals[0],\n limit: arg.int(args, \"limit\") ?? 20,\n branch: arg.str(args, \"branch\"),\n })}`,\n );\n printJson(ctx, result);\n },\n });\n\n bench.command({\n name: \"branch\",\n help: \"List branches/tags (the dir's current branch marked with *), or create one.\",\n positionals: [\n { name: \"name\", help: \"Create a branch with this name (omit to list). `<slug> <name>` also works.\", optional: true },\n { name: \"name2\", help: \"The branch name when the first argument is a slug.\", optional: true },\n ],\n flags: [\n { name: \"path\", help: \"Working dir whose container/branch to use.\", default: \".\" },\n { name: \"slug\", help: \"Container slug (default: the dir's tracked slug).\" },\n { name: \"from\", help: \"Start version id (default: the main tip).\" },\n VERSION_ID_FLAG,\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const creds = credentials(args);\n const { slug, name } = slugAndName(args, \"branch\");\n if (name) {\n const ref = await createRef(slug, name, \"branch\", arg.str(args, \"from\") ?? arg.str(args, \"version-id\"), worldsOptions(creds));\n printJson(ctx, ref);\n return;\n }\n const dir = arg.str(args, \"path\") ?? \".\";\n const meta = readLocalMeta(dir);\n const current = meta?.slug === slug ? meta?.branch : undefined;\n const refs = await api<{ refs: RefRow[] }>(\n creds,\n \"GET\",\n `/api/public/benchmark-containers/refs${query({ slug })}`,\n );\n for (const ref of refs.refs) {\n const marker = ref.kind === \"branch\" && ref.name === current ? \"*\" : \" \";\n ctx.stdout(\n `${marker} ${ref.kind.padEnd(6)} ${ref.name.padEnd(24)} ${(ref.contentHash ?? \"\").slice(0, 12).padEnd(12)} ${ref.semanticVersion ?? \"\"}`.trimEnd(),\n );\n }\n },\n });\n\n bench.command({\n name: \"tag\",\n help: \"Create an immutable tag pointing at a version.\",\n positionals: [\n { name: \"name\", help: \"Tag name (immutable). `<slug> <name>` also works.\" },\n { name: \"name2\", help: \"The tag name when the first argument is a slug.\", optional: true },\n ],\n flags: [\n { name: \"path\", help: \"Working dir whose container to use.\", default: \".\" },\n { name: \"slug\", help: \"Container slug (default: the dir's tracked slug).\" },\n { name: \"version\", help: \"Version id to tag (default: main tip).\" },\n VERSION_ID_FLAG,\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const { slug, name } = slugAndName(args, \"tag\");\n const ref = await createRef(\n slug,\n name!,\n \"tag\",\n arg.str(args, \"version\") ?? arg.str(args, \"version-id\"),\n worldsOptions(credentials(args)),\n );\n printJson(ctx, ref);\n },\n });\n\n bench.command({\n name: \"propose\",\n help: \"File local edits as a change proposal (a PR to the env) instead of pushing to the branch.\",\n positionals: [{ name: \"path\", help: \"Working dir with local edits (default: cwd).\", optional: true }],\n flags: [\n { name: \"title\", help: \"Proposal title, shown to the reviewer.\" },\n { name: \"message\", short: \"m\", help: \"Why this changeset.\" },\n { name: \"reason\", help: \"Alias of --message.\" },\n { name: \"branch\", short: \"b\", help: \"Branch the proposal merges into (default main).\" },\n { name: \"target-branch\", help: \"Alias of --branch.\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const title = arg.str(args, \"title\");\n const reason = arg.str(args, \"message\") ?? arg.str(args, \"reason\");\n if (!title || !reason) throw new CliError(\"bench propose needs --title and --message\");\n const result = await propose(args.positionals[0] ?? \".\", {\n title,\n reason,\n targetBranch: arg.str(args, \"branch\") ?? arg.str(args, \"target-branch\"),\n options: worldsOptions(credentials(args)),\n });\n printJson(ctx, result);\n },\n });\n\n bench.command({\n name: \"diff\",\n help: \"Per-file diff (added/removed/modified/unchanged) between two version ids.\",\n positionals: [\n { name: \"base\", help: \"Base version id.\" },\n { name: \"head\", help: \"Head version id.\" },\n ],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const [base, head] = args.positionals;\n const result = await api(\n credentials(args),\n \"GET\",\n `/api/public/benchmark-containers/versions/diff${query({ base, head })}`,\n );\n printJson(ctx, result);\n },\n });\n\n bench.command({\n name: \"dispatch\",\n help: \"Start a hosted run of a run config — the same dispatch the Run button uses, parallelism included.\",\n positionals: [{ name: \"run_config_id\", help: \"Run config id (world page -> Runs -> Configs).\" }],\n flags: [\n { name: \"container-id\", help: \"Which environment, when the project hosts several.\" },\n { name: \"version-id\", help: \"Pin to a specific READY version (default: head).\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const containerId = arg.str(args, \"container-id\");\n const versionId = arg.str(args, \"version-id\");\n const result = await api<{ versionLabel: string; runs: { ok: boolean }[] }>(\n credentials(args),\n \"POST\",\n \"/api/public/benchmark-containers/run-configs/dispatch\",\n {\n runConfigId: args.positionals[0],\n ...(containerId ? { containerId } : {}),\n ...(versionId ? { versionId } : {}),\n },\n );\n printJson(ctx, result);\n return result.runs.every((r) => r.ok) ? 0 : 1;\n },\n });\n\n bench.command({\n name: \"run\",\n help: \"One hosted run: status, score, per-task rewards (--wait polls to terminal).\",\n positionals: [{ name: \"run_id\", help: \"Run id from `bench dispatch`.\" }],\n flags: [\n { name: \"wait\", help: \"Poll until the run is terminal.\", boolean: true },\n { name: \"timeout-min\", help: \"Minutes to wait (with --wait).\", default: \"45\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const runId = args.positionals[0]!;\n const options = worldsOptions(credentials(args));\n const report = arg.bool(args, \"wait\")\n ? await waitForRun(runId, {\n timeoutMinutes: arg.int(args, \"timeout-min\") ?? 45,\n options,\n onTick: (r) =>\n ctx.stderr(`…${r.status.toLowerCase()} (${r.shardsCompleted ?? 0}/${r.parallelism} shards)`),\n })\n : await getRun(runId, options);\n ctx.stdout(\n `${report.id} ${report.status}${report.score !== null ? ` score=${report.score.toFixed(3)}` : \"\"}` +\n ` (${report.model ?? \"?\"} · ${report.versionLabel ?? \"?\"} · x${report.parallelism})`,\n );\n for (const sample of report.samples) {\n const subs = Object.entries(sample.rewards)\n .filter(([, v]) => typeof v === \"number\")\n .map(([k, v]) => `${k}=${(v as number).toFixed(2)}`)\n .join(\" \");\n ctx.stdout(` ${(sample.reward ?? 0).toFixed(2)} ${sample.task ?? \"?\"}${subs ? ` [${subs}]` : \"\"}`);\n }\n if (report.summary) ctx.stdout(` ${report.summary}`);\n return report.terminal && report.status.toUpperCase() === \"COMPLETED\" ? 0 : 1;\n },\n });\n\n bench.command({\n name: \"run-configs\",\n help: \"Run configs from the CLI — list them, create one for CI, delete one.\",\n positionals: [{ name: \"action\", help: \"list | create | delete (default list).\", optional: true }],\n flags: [\n { name: \"name\", help: \"Config name (create).\" },\n { name: \"models\", help: \"Comma-separated model list (create).\" },\n { name: \"parallelism\", help: \"Containers per model, 1-16 (create).\", default: \"1\" },\n { name: \"tasks\", help: \"Comma-separated bundled task names (create).\" },\n {\n name: \"world-tasks\",\n help: \"Comma-separated stored task refs, <id> or <id>@<version> (create; api worlds, not with --tasks).\",\n },\n { name: \"agent\", help: \"harbor agent (create).\" },\n { name: \"auto-run-on-push\", help: \"Dispatch on every pushed READY version (create).\", boolean: true },\n { name: \"id\", help: \"Config id (delete/update).\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const action = args.positionals[0] ?? \"list\";\n const creds = credentials(args);\n const options = worldsOptions(creds);\n if (action === \"list\") {\n const rows = await listRunConfigs(options);\n if (rows.length === 0) {\n ctx.stdout(\"No run configs in this project.\");\n return;\n }\n for (const row of rows) {\n const extras = [\n row.parallelism > 1 ? `x${row.parallelism} containers` : null,\n row.autoRunOnPush ? \"auto-on-push\" : null,\n ].filter(Boolean);\n ctx.stdout(\n `${row.id} ${row.name} (${row.models.join(\", \") || \"no models\"})${extras.length ? ` [${extras.join(\", \")}]` : \"\"}`,\n );\n }\n return;\n }\n if (action === \"delete\") {\n const id = arg.str(args, \"id\");\n if (!id) throw new CliError(\"--id is required for delete\");\n await api(creds, \"DELETE\", \"/api/public/benchmark-containers/run-configs\", { id });\n ctx.stdout(`Deleted ${id}.`);\n return;\n }\n if (action !== \"create\") throw new CliError(\"action must be one of: list | create | delete\");\n const name = arg.str(args, \"name\");\n const models = arg.str(args, \"models\");\n if (!name || !models) throw new CliError(\"--name and --models are required for create\");\n const fields: Record<string, unknown> = {\n name,\n models: models.split(\",\").map((m) => m.trim()).filter(Boolean),\n parallelism: arg.int(args, \"parallelism\") ?? 1,\n };\n const agent = arg.str(args, \"agent\");\n if (agent) fields.agent = agent;\n const tasks = arg.str(args, \"tasks\");\n if (tasks) fields.taskNames = tasks.split(\",\").map((t) => t.trim()).filter(Boolean);\n const worldTasks = arg.str(args, \"world-tasks\");\n if (worldTasks) {\n if (tasks) throw new CliError(\"--tasks and --world-tasks are exclusive: a config runs bundled scenarios or stored tasks\");\n try {\n fields.worldTasks = parseWorldTaskRefs(worldTasks);\n } catch (e) {\n throw new CliError(e instanceof Error ? e.message : String(e));\n }\n }\n if (arg.bool(args, \"auto-run-on-push\")) fields.autoRunOnPush = true;\n const id = arg.str(args, \"id\");\n if (id) fields.id = id;\n const row = await api<{ id: string; name: string; models?: string[] }>(\n creds,\n \"POST\",\n \"/api/public/benchmark-containers/run-configs\",\n fields,\n );\n ctx.stdout(`${row.id} ${row.name} (${(row.models ?? []).join(\", \")})`);\n },\n });\n\n bench.command({\n name: \"secrets\",\n help: \"Environment secrets — env vars every HOSTED run of the world receives (write-only).\",\n positionals: [{ name: \"action\", help: \"set | list | unset\" }],\n flags: [\n { name: \"env\", help: \"World slug the secret belongs to.\" },\n { name: \"key\", help: \"Secret name (UPPER_SNAKE_CASE) — required for set/unset.\" },\n { name: \"value\", help: \"Secret value for `set`; omit to read from stdin (keeps it out of shell history).\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const action = args.positionals[0]!;\n const env = arg.str(args, \"env\");\n if (!env) throw new CliError(\"--env <world slug> is required\");\n const options = worldsOptions(credentials(args));\n if (action === \"list\") {\n const rows = await listEnvSecretKeys(env, options);\n if (rows.length === 0) {\n ctx.stdout(`No secrets on ${env}.`);\n return;\n }\n for (const row of rows) ctx.stdout(`${row.key} (rotated ${row.updatedAt})`);\n return;\n }\n if (action !== \"set\" && action !== \"unset\") throw new CliError(\"action must be one of: set | list | unset\");\n const key = arg.str(args, \"key\");\n if (!key) throw new CliError(`--key is required for \\`${action}\\``);\n if (action === \"unset\") {\n await deleteEnvSecret(env, key, options);\n ctx.stdout(`Deleted ${key} from ${env}.`);\n return;\n }\n const value = arg.str(args, \"value\") ?? (await ctx.stdin()).trim();\n if (!value) throw new CliError(\"empty value — nothing stored\");\n const res = await setEnvSecret(env, key, value, options);\n ctx.stdout(`${res.created ? \"Added\" : \"Rotated\"} ${key} on ${env} — next hosted run receives it.`);\n },\n });\n\n bench.command({\n name: \"validate\",\n help: \"Push this checkout, run the named run config against it, gate — the PR-validation entry.\",\n positionals: [{ name: \"path\", help: \"World directory (default: cwd).\", optional: true }],\n flags: [\n { name: \"run-config\", help: \"Run config NAME to dispatch.\" },\n { name: \"slug\", help: \"Container slug (default: pyproject name / dir name).\" },\n { name: \"branch\", help: \"Branch to push (default: the checkout's git branch).\" },\n { name: \"min-score\", help: \"Fail any run scoring below this.\" },\n { name: \"summary-file\", help: \"Write the markdown summary here (PR comment).\" },\n { name: \"timeout-min\", help: \"Minutes to wait for the runs.\", default: \"45\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const runConfig = arg.str(args, \"run-config\");\n if (!runConfig) throw new CliError(\"bench validate needs --run-config NAME\");\n const minScoreRaw = arg.str(args, \"min-score\");\n const report = await validateWorld(args.positionals[0] ?? \".\", {\n slug: arg.str(args, \"slug\"),\n runConfig,\n branch: arg.str(args, \"branch\"),\n minScore: minScoreRaw === undefined ? null : Number(minScoreRaw),\n timeoutMinutes: arg.int(args, \"timeout-min\") ?? 45,\n onProgress: (line) => ctx.stderr(line),\n options: worldsOptions(credentials(args)),\n });\n for (const run of report.runs) {\n ctx.stdout(\n `${run.model}: ${run.failure ? `FAIL — ${run.failure}` : \"pass\"}` +\n `${run.report?.score != null ? ` score=${run.report.score.toFixed(3)}` : \"\"}` +\n `${run.report?.url ? ` ${run.report.url}` : \"\"}`,\n );\n }\n const summaryFile = arg.str(args, \"summary-file\");\n if (summaryFile) fs.writeFileSync(summaryFile, report.markdown + \"\\n\");\n const stepSummary = process.env.GITHUB_STEP_SUMMARY;\n if (stepSummary) fs.appendFileSync(stepSummary, report.markdown + \"\\n\");\n ctx.stdout(report.ok ? \"validation passed\" : \"validation FAILED\");\n return report.ok ? 0 : 1;\n },\n });\n\n bench.command({\n name: \"resolve\",\n help: \"Pinned version + task count for slug[@ref].\",\n positionals: [{ name: \"slug_ref\", help: \"slug, or slug@branch|tag|semver|hash.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const world = await openWorld(args.positionals[0]!, worldsOptions(credentials(args)));\n ctx.stdout(\n `${world.slug}@${world.ref ?? \"latest\"}: ${world.version.semanticVersion ?? \"-\"} ` +\n `(${world.version.contentHash.slice(0, 12)}) · ${world.version.state ?? \"?\"} · ${world.tasks.length} tasks`,\n );\n ctx.stdout(`versionId: ${world.version.versionId}`);\n },\n });\n\n bench.command({\n name: \"tests\",\n help: \"The runs of the tests a world ships (on push, from the CLI, from the API), newest first; --run <id> prints one report.\",\n positionals: [{ name: \"slug\", help: \"World slug.\" }],\n flags: [\n { name: \"run\", help: \"Print this run's full report instead of the list.\" },\n { name: \"limit\", help: \"How many runs to list (default 20).\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const slug = args.positionals[0];\n if (!slug) throw new CliError(\"bench tests needs a world slug\", 1);\n const creds = credentials(args);\n const runId = arg.str(args, \"run\");\n if (runId) {\n const one = await api<{ run: Record<string, unknown> }>(creds, \"GET\", `/api/public/worlds/${encodeURIComponent(slug)}/tests/${encodeURIComponent(runId)}`);\n printJson(ctx, one.run);\n return 0;\n }\n const limit = arg.int(args, \"limit\");\n const listed = await api<{ runs: { id: string; state: string; trigger: string; versionId: string; createdAt: string; summary?: { passed?: number; failed?: number; skipped?: number } | null; error?: string | null }[] }>(\n creds,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug)}/tests${limit ? `?limit=${limit}` : \"\"}`,\n );\n if (!listed.runs.length) ctx.stdout(\"no test runs yet — ship tests/ with the world and push, or `gateway worlds test <slug>`\");\n for (const r of listed.runs) {\n const s = r.summary;\n ctx.stdout(\n `${r.createdAt} ${r.state.padEnd(7)} ${r.trigger.padEnd(6)} ${r.versionId} ${s ? `${s.passed ?? 0} passed, ${s.failed ?? 0} failed` : r.error ?? \"\"} ${r.id}`,\n );\n }\n return 0;\n },\n });\n\n bench.command({\n name: \"tasks\",\n help: \"The task list of slug[@ref].\",\n positionals: [{ name: \"slug_ref\", help: \"slug, or slug@branch|tag|semver|hash.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const world = await openWorld(args.positionals[0]!, worldsOptions(credentials(args)));\n if (world.tasks.length === 0) {\n ctx.stdout(\"No task manifest served for this version.\");\n return;\n }\n for (const task of world.tasks) ctx.stdout(`${task.name}${task.variant ? ` (${task.variant})` : \"\"}`);\n },\n });\n\n bench.command({\n name: \"refs\",\n help: \"Branches and tags of a container.\",\n positionals: [{ name: \"slug\", help: \"Container slug.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const res = await api<{ refs: RefRow[] }>(\n credentials(args),\n \"GET\",\n `/api/public/benchmark-containers/refs${query({ slug: args.positionals[0] })}`,\n );\n for (const ref of res.refs) {\n ctx.stdout(\n `${ref.kind === \"tag\" ? \"tag \" : \"branch\"} ${ref.name} ${ref.semanticVersion ?? \"-\"} (${ref.contentHash?.slice(0, 12) ?? \"?\"}) ${ref.state ?? \"\"}`.trimEnd(),\n );\n }\n },\n });\n\n bench.command({\n name: \"proposals\",\n help: \"Change proposals filed against a container.\",\n positionals: [{ name: \"slug\", help: \"Container slug.\" }],\n flags: [{ name: \"status\", help: \"open | applied | dismissed\" }, HOST_FLAG],\n run: async (args, ctx) => {\n const res = await api<{ proposals: { id: string; title?: string | null; status: string }[] }>(\n credentials(args),\n \"GET\",\n `/api/public/benchmark-containers/proposals${query({ slug: args.positionals[0], status: arg.str(args, \"status\") })}`,\n );\n if (res.proposals.length === 0) {\n ctx.stdout(\"No proposals.\");\n return;\n }\n for (const p of res.proposals) ctx.stdout(`${p.id} [${p.status}] ${p.title ?? \"\"}`.trimEnd());\n },\n });\n\n // ── Python-only: local engines and pip ────────────────────────────────────\n\n bench.command({\n name: \"eval\",\n help: \"Python-only (local verifiers/harbor engines) — run hosted with `bench dispatch` instead.\",\n flags: [HOST_FLAG],\n run: async (_args, ctx) =>\n pythonOnly(\n ctx,\n \"bench eval\",\n \"it runs the world locally on the Python engines (verifiers/harbor), which a JS process cannot host.\",\n \"Run hosted instead: gateway bench dispatch <runConfigId> — same worlds, graded on the platform.\",\n ),\n });\n\n bench.command({\n name: \"install\",\n help: \"Python-only (pip-installs a version's wheel) — n/a from TypeScript.\",\n flags: [HOST_FLAG],\n run: async (_args, ctx) =>\n pythonOnly(\n ctx,\n \"bench install\",\n \"it pip-installs a Python wheel into the current Python environment.\",\n \"Use `pip install gatewaysdk` and `gateway bench install <slug>` from the Python CLI.\",\n ),\n });\n\n bench.command({\n name: \"harvest-harbor\",\n help: \"Python-only (harvests a local harbor jobs dir) — n/a from TypeScript.\",\n flags: [HOST_FLAG],\n run: async (_args, ctx) =>\n pythonOnly(\n ctx,\n \"bench harvest-harbor\",\n \"it reads a harbor jobs directory produced by the Python runner.\",\n \"Hosted runs file themselves: gateway bench dispatch <runConfigId>.\",\n ),\n });\n}\n\nasync function pullJson(slugRef: string, target: string | undefined, args: Parsed) {\n const res = await pull(slugRef, target, worldsOptions(credentials(args)));\n const meta = readLocalMeta(res.dir);\n const at = slugRef.indexOf(\"@\");\n return {\n slug: res.slug,\n ref: at === -1 ? \"latest\" : slugRef.slice(at + 1),\n branch: meta?.branch ?? DEFAULT_BRANCH,\n versionId: res.versionId,\n contentHash: meta?.contentHash ?? null,\n target: res.dir,\n files: res.files,\n };\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { api, printJson, type Credentials } from \"../config\";\nimport { arg, CliError, parseArgs, type CommandContext, type CommandGroup, type Parsed } from \"../router\";\nimport { push } from \"../../worlds/hub\";\nimport {\n BENCHMARK_KINDS,\n BENCHMARKS_SKILL,\n classifyTree,\n declaredTasks,\n importReport,\n kindOfTree,\n SHAPE_LABELS,\n type BenchmarkKind,\n type TreeClassification,\n} from \"../../benchmarks/index\";\nimport {\n dryRunHarbor,\n dryRunVerifiers,\n harborRunPlan,\n shellLine,\n validateHarbor,\n validateVerifiers,\n verifiersRunPlan,\n writeHarborScaffold,\n writeVerifiersScaffold,\n type DryRunResult,\n type TreeValidation,\n} from \"../../benchmarks/container\";\nimport { resolveEnvironmentId, runEnvironment } from \"./environment\";\nimport { BridgeRejected, detailFrom } from \"../runtime/client\";\nimport { findPython, localBridge, localRuntime, localRuntimeReason } from \"../runtime/local\";\nimport { credentials, HOST_FLAG, printDeprecations, worldsOptions } from \"./shared\";\nimport { collectFiles, WORLDS, type CreatedWorld } from \"./worlds\";\n\n/**\n * `gateway benchmarks …` — one front door for both benchmark substrates.\n *\n * A benchmark is a world with tasks (the worlds substrate: World Host, one\n * session per rollout, SQL verifiers over world state) or a container\n * benchmark (the runner substrate: a harbor task tree graded by its own\n * tests/test.sh, or a verifiers package graded by Python reward functions).\n * The kind is read from the tree, never guessed: `init --kind` writes one,\n * `validate`, `dry-run`, `push` route on it, and a `--kind` that disagrees\n * with the tree is refused by name before anything is written or sent.\n *\n * Segmentation, as enforced: a world tree goes to POST /api/public/worlds\n * (`worlds create`, which refuses a container tree with `world_kind_retired`)\n * or, for a slug that already holds a world, to the hub as a new version; a\n * container tree goes to the hub (`bench push`). The hub's versions door is\n * where both converge, and it refuses a cross-substrate push by slug\n * (`benchmark_substrate_mismatch`: a container tree under a world's slug, a\n * world under a container's slug); `push` here reads the slug's substrate\n * first and refuses before any request. A container benchmark that IS a\n * container benchmark opens on the runner — `session open` and `task create`\n * do not refuse it (only the legacy tools bundle is retired on serve); the\n * runner's harbor engine refuses a schema bundle (`require_legacy_bundle`).\n */\n\nexport const BENCHMARK_CONFIG = \"benchmark.json\";\n\ntype BenchmarkConfig = { kind?: BenchmarkKind; slug?: string; models?: string[]; rollouts?: number; note?: string };\n\n/** Run another registered command in-process, so the front door cannot drift from the command it fronts. */\nasync function runSub(root: CommandGroup, argv: string[], ctx: CommandContext): Promise<number> {\n let node: CommandGroup = root;\n let i = 0;\n while (i < argv.length && node.groups.has(argv[i]!)) node = node.groups.get(argv[i++]!)!;\n const command = node.commands.get(argv[i]!);\n if (!command) throw new CliError(`benchmarks: no command at ${argv.slice(0, i + 1).join(\" \")}`, 1);\n const code = await command.run(parseArgs(command, argv.slice(i + 1)), ctx);\n return code ?? 0;\n}\n\n/** Same, capturing stdout as text (the fronted command prints JSON). */\nasync function captureSub(root: CommandGroup, argv: string[], ctx: CommandContext): Promise<{ code: number; out: string }> {\n const lines: string[] = [];\n const code = await runSub(root, argv, { ...ctx, stdout: (line) => lines.push(line) });\n return { code, out: lines.join(\"\\n\") };\n}\n\nfunction safeJson(text: string): Record<string, unknown> {\n try {\n const parsed: unknown = JSON.parse(text);\n return parsed && typeof parsed === \"object\" ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\n }\n}\n\nconst KIND_LABELS: Record<BenchmarkKind, string> = {\n world: \"a world with [[tasks]] (World Host, SQL verifiers over world state)\",\n harbor: \"a harbor task tree (benchmark runner, each task graded by its tests/test.sh in a container)\",\n verifiers: \"a verifiers package (benchmark runner, Python reward functions over the completion)\",\n image: \"a bring-your-own image (not shipped: see `benchmarks init --kind image`)\",\n};\n\n/** The sentence a directory of the wrong kind, or of no kind, is refused with. */\nexport function refuseKind(dir: string, classified: TreeClassification, wanted: BenchmarkKind | null, command: string): never {\n const what = SHAPE_LABELS[classified.shape];\n const actual = kindOfTree(classified);\n if (actual === null)\n throw new CliError(\n `benchmarks ${command}: ${dir} is ${what}. A benchmark is a world with [[tasks]] or a container benchmark: \\`gateway benchmarks init ${dir}\\` scaffolds a world, ` +\n `\\`--kind harbor\\` a harbor task tree, \\`--kind verifiers\\` a verifiers package. Skill: \\`gateway worlds skill ${BENCHMARKS_SKILL}\\`.`,\n 2,\n );\n const marker = classified.markers.slice(0, 2).join(\", \");\n const doors: Record<BenchmarkKind, string> = {\n world: `\\`gateway benchmarks push ${dir}\\` publishes it as a world (POST /api/public/worlds, the request \\`gateway worlds create\\` sends); the benchmark runner never sees it`,\n harbor: `\\`gateway benchmarks push ${dir}\\` pushes it to the benchmark runner (\\`gateway bench push\\` into the environment project); the World Host never sees it. \\`gateway benchmarks import ${dir} --from harbor\\` reports what of it is expressible as world tasks`,\n verifiers: `\\`gateway benchmarks push ${dir}\\` pushes it to the benchmark runner (\\`gateway bench push\\`); the World Host never sees it. \\`gateway benchmarks import ${dir} --from verifiers\\` reports what of it is expressible as world tasks`,\n image: \"\",\n };\n throw new CliError(\n `benchmarks ${command}: ${dir} is a ${what} (${marker}), ${KIND_LABELS[actual]}, not ${wanted ? KIND_LABELS[wanted] : \"what this command takes\"}. ` +\n `${doors[actual]}. Drop --kind to take the tree as it is, or \\`gateway benchmarks init <new-dir> --kind ${wanted ?? \"harbor\"}\\` for a new one. Skill: \\`gateway worlds skill ${BENCHMARKS_SKILL}\\`.`,\n 2,\n );\n}\n\n/** The tree's kind, checked against `--kind` when given. Refuses before anything is written or sent. */\nfunction resolveKind(dir: string, args: Parsed, command: string): { kind: BenchmarkKind; classified: TreeClassification } {\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);\n const classified = classifyTree(dir);\n const actual = kindOfTree(classified);\n const wanted = arg.str(args, \"kind\") as BenchmarkKind | undefined;\n if (wanted !== undefined && !BENCHMARK_KINDS.includes(wanted)) throw new CliError(`--kind is one of ${BENCHMARK_KINDS.join(\", \")}`);\n if (actual === null || (wanted !== undefined && wanted !== actual)) refuseKind(dir, classified, wanted ?? null, command);\n return { kind: actual, classified };\n}\n\nfunction firstEntity(dir: string): string | null {\n try {\n const world = JSON.parse(fs.readFileSync(path.join(dir, \"schema\", \"world.json\"), \"utf8\")) as {\n \"x-gateway\"?: { entities?: Record<string, unknown> };\n entities?: Record<string, unknown> | { name?: string }[];\n };\n // gateway-world/1 declares entities under x-gateway; a bare `entities` map is the older spelling.\n const entities = world[\"x-gateway\"]?.entities ?? world.entities;\n if (Array.isArray(entities)) return entities[0]?.name ?? null;\n if (entities && typeof entities === \"object\") return Object.keys(entities)[0] ?? null;\n } catch {\n // no contract yet; the caller reports it\n }\n return null;\n}\n\nfunction verifierNames(dir: string): string[] {\n const folder = path.join(dir, \"verifiers\");\n if (!fs.existsSync(folder)) return [];\n return fs\n .readdirSync(folder)\n .filter((f) => f.endsWith(\".sql\"))\n .map((f) => f.slice(0, -4))\n .sort();\n}\n\nfunction readConfig(dir: string): BenchmarkConfig {\n const file = path.join(dir, BENCHMARK_CONFIG);\n if (!fs.existsSync(file)) return {};\n try {\n return JSON.parse(fs.readFileSync(file, \"utf8\")) as BenchmarkConfig;\n } catch {\n throw new CliError(`${file} is not JSON`, 1);\n }\n}\n\nfunction writeConfig(dir: string, config: BenchmarkConfig): void {\n fs.writeFileSync(path.join(dir, BENCHMARK_CONFIG), JSON.stringify({ ...config, note: \"Defaults for `gateway benchmarks run` when --model / --rollouts are not given.\" }, null, 2) + \"\\n\");\n}\n\nfunction printValidation(ctx: CommandContext, report: TreeValidation): void {\n ctx.stdout(`${report.dir}: ${report.kind} benchmark — runner reads it as ${report.detectedKind} — ${report.ok ? \"ok\" : `${report.problems.length + report.tasks.reduce((n, t) => n + t.problems.length, 0)} problem(s)`}`);\n for (const task of report.tasks) {\n const image = task.image.ref ?? (task.image.dockerfile ? `build ${task.image.dockerfile}` : \"no image\");\n ctx.stdout(` ${task.problems.length ? \"FAIL\" : \"ok \"} ${task.id}: image ${image}; instruction ${task.files.instruction ? \"yes\" : \"MISSING\"}; tests/test.sh ${task.files.tests ? \"yes\" : \"MISSING\"}; solution ${task.files.solution ? \"yes\" : \"none\"}`);\n for (const problem of task.problems) ctx.stdout(` problem: ${problem}`);\n for (const warning of task.warnings) ctx.stdout(` note: ${warning}`);\n }\n if (report.package)\n ctx.stdout(` package ${report.package.name} (${report.package.init}): ${report.package.v1 ? \"verifiers v1\" : \"verifiers v0\"}; Taskset ${report.package.taskset ?? \"NONE\"}; rewards ${report.package.rewards.join(\", \") || \"none by name\"}`);\n for (const problem of report.problems) ctx.stdout(` problem: ${problem}`);\n for (const warning of report.warnings) ctx.stdout(` note: ${warning}`);\n}\n\nfunction printDryRun(ctx: CommandContext, plan: Record<string, unknown>, result: DryRunResult): void {\n ctx.stdout(`plan (${String(plan.kind)}${plan.task ? ` · task ${String(plan.task)}` : \"\"}):`);\n if (plan.kind === \"harbor\") {\n const commands = plan.commands as { build?: string[]; pull?: string[]; run: string[] };\n if (commands.build) ctx.stdout(` build ${shellLine(commands.build)}`);\n if (commands.pull) ctx.stdout(` pull ${shellLine(commands.pull)}`);\n ctx.stdout(` run ${shellLine(commands.run)}`);\n ctx.stdout(` <tmp>/logs is a scratch directory created at run time; the reward is read from it`);\n }\n if (plan.kind === \"verifiers\") {\n const commands = plan.commands as { build: string[]; run: string[] };\n const image = plan.image as { tag: string; dockerfile: string };\n ctx.stdout(` build ${shellLine(commands.build)} # Dockerfile on stdin: ${JSON.stringify(image.dockerfile)}`);\n ctx.stdout(` run ${shellLine(commands.run.slice(0, -1))} <discover script>`);\n ctx.stdout(` the tree is mounted read-only, no network; the package's module-level code runs in the container. --here runs it in this machine's Python, as you`);\n }\n for (const step of plan.steps as { name: string; command: string; note: string }[]) ctx.stdout(` ${step.name.padEnd(9)} ${step.command}\\n ${step.note}`);\n if (plan.reward) ctx.stdout(` reward ${(plan.reward as { file: string }).file}`);\n ctx.stdout(` runner ${String(plan.runner)}`);\n const validation = plan.validation as TreeValidation[\"tasks\"][number] | undefined;\n if (validation) {\n for (const problem of validation.problems) ctx.stdout(` problem ${problem}`);\n for (const warning of validation.warnings) ctx.stdout(` note ${warning}`);\n }\n if (!result.executed) {\n ctx.stdout(`not executed: ${result.reason}`);\n return;\n }\n for (const command of result.commands) ctx.stdout(`ran: ${command}`);\n if (result.reward !== undefined) ctx.stdout(`reward: ${result.reward === null ? \"null (ungraded)\" : result.reward}${result.rewards ? ` ${JSON.stringify(result.rewards)}` : \"\"} · exit ${result.exitCode}`);\n if (result.reason) ctx.stdout(result.reason);\n if (result.output?.trim()) ctx.stdout(result.output.trim());\n}\n\ntype ExistingSlug = { id: string; substrate: \"world\" | \"container\" | null; shape: string | null };\n\n/** What a slug already holds in this project, from the environment detail's newest version that recorded files. Null when the slug is free. */\nasync function existingSlug(creds: Credentials, slug: string): Promise<ExistingSlug | null> {\n const listing = await api<{ environments?: { id: string; slug?: string }[] }>(creds, \"GET\", `/api/public/environments?slug=${encodeURIComponent(slug)}&limit=5`);\n const hit = listing.environments?.find((env) => env.slug === slug);\n if (!hit) return null;\n const detail = await api<{ substrate?: \"world\" | \"container\" | null; versions?: { shape?: string | null }[] }>(creds, \"GET\", `/api/public/environments/${encodeURIComponent(hit.id)}`);\n return { id: hit.id, substrate: detail.substrate ?? null, shape: detail.versions?.find((v) => v.shape)?.shape ?? null };\n}\n\nconst STORED_SHAPE_LABELS: Record<string, string> = {\n schema: \"schema world (gateway-world/1)\",\n \"api-bundle\": \"api bundle (a schema world packaged with gateway-api-world.toml)\",\n \"legacy-tools\": \"legacy tools world (gateway-env.toml without a contract)\",\n harbor: \"harbor task tree\",\n verifiers: \"verifiers package\",\n};\n\n/** One slug, one substrate: the CLI's reading of the hub's `benchmark_substrate_mismatch`, before any request writes. */\nfunction refuseSlug(slug: string, existing: ExistingSlug, classified: TreeClassification, incoming: \"world\" | \"container\"): never {\n const held = existing.shape ? STORED_SHAPE_LABELS[existing.shape] ?? existing.shape : existing.substrate;\n const heldSide = existing.substrate === \"world\" ? \"a world, hosted on the World Host\" : \"a container benchmark, executed by the benchmark runner\";\n const thisSide = incoming === \"world\" ? \"a world for the World Host\" : \"a container benchmark for the benchmark runner\";\n throw new CliError(\n `benchmarks push: slug \\`${slug}\\` already holds a ${held} — ${heldSide} — and this tree is a ${SHAPE_LABELS[classified.shape]}, ${thisSide}. ` +\n `A slug holds one substrate: pass --slug <new-slug>, or push a ${existing.substrate === \"world\" ? \"world\" : \"container\"} tree to add a version of \\`${slug}\\`. ` +\n `Nothing was written (the hub's versions door refuses the same push with benchmark_substrate_mismatch).`,\n 2,\n );\n}\n\n/** What the bridge's `dry-run` answers for a world. */\ntype WorldDryRunAnswer = {\n task: string;\n prompt: string;\n tools: string[];\n verifiers: string[];\n worlds: Record<string, string[]>;\n state: { entities?: Record<string, unknown[]>; worlds?: Record<string, { entities?: Record<string, unknown[]> }> };\n grade: { reward: number | null; rewards: Record<string, number | null> } | null;\n verifier_errors?: Record<string, string>;\n};\n\nexport type WorldDryRun = {\n kind: \"world\";\n task: string;\n prompt: string | null;\n tools: string[];\n verifiers: string[];\n seed: Record<string, number>;\n steps: { name: string; command: string; note: string }[];\n runner: string;\n reward: number | null;\n rewards: Record<string, number | null>;\n verifierErrors: Record<string, string>;\n executed: boolean;\n note: string;\n};\n\nconst WORLD_DRY_RUN_STEPS = (dir: string, task: string): WorldDryRun[\"steps\"] => [\n { name: \"open\", command: `open_world(${dir}, task=${JSON.stringify(task)}, http=False)`, note: \"the bundled runtime opens one session under the task: its seed laid (data/initial.json, the task's scenario), its tool allow-list served\" },\n { name: \"tools\", command: \"session.tools\", note: \"what an agent could call in this session\" },\n { name: \"grade\", command: \"session.grade()\", note: \"the task's verifiers over the UNTOUCHED state: reward, rewards by verifier (a dependency's as alias/name)\" },\n { name: \"close\", command: \"session.close()\", note: \"no server is left running\" },\n];\n\nconst WORLD_DRY_RUN_NOTE = (dir: string, task: string) =>\n `reward is for the untouched world; an agent's rollout is what \\`benchmarks run\\` grades. Drive one by hand: \\`gateway worlds serve ${dir} --task ${task} --port 8080\\` then \\`gateway worlds call http://localhost:8080 <tool> --args '{…}' --grade --close\\`.`;\n\nfunction rowCounts(state: WorldDryRunAnswer[\"state\"]): Record<string, number> {\n const counts: Record<string, number> = {};\n for (const [entity, rows] of Object.entries(state.entities ?? {})) counts[entity] = Array.isArray(rows) ? rows.length : 0;\n for (const [alias, world] of Object.entries(state.worlds ?? {}))\n for (const [entity, rows] of Object.entries(world.entities ?? {})) counts[`${alias}.${entity}`] = Array.isArray(rows) ? rows.length : 0;\n return counts;\n}\n\n/** The world dry-run: the task's session opened, graded untouched, closed — or the exact steps when the runtime is absent. */\nasync function dryRunWorld(dir: string, task: string, opts: { plan?: boolean } = {}): Promise<WorldDryRun> {\n const local = opts.plan ? null : localRuntime();\n const base: WorldDryRun = {\n kind: \"world\",\n task,\n prompt: null,\n tools: [],\n verifiers: [],\n seed: {},\n steps: WORLD_DRY_RUN_STEPS(dir, task),\n runner: \"World Host: one hosted session per rollout, the same open / tools / grade / close verbs (POST /api/public/environments/{id}/run)\",\n reward: null,\n rewards: {},\n verifierErrors: {},\n executed: false,\n note: WORLD_DRY_RUN_NOTE(dir, task),\n };\n if (!local)\n return { ...base, note: `not executed: ${opts.plan ? \"--plan\" : localRuntimeReason() || \"no bundled runtime\"} — the steps above are what would run. ${base.note}` };\n const payload = await localBridge<Record<string, unknown>>({ command: \"dry-run\", world: path.resolve(dir), task }, local);\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n const answer = payload as unknown as WorldDryRunAnswer;\n const verifiers = [...answer.verifiers, ...Object.entries(answer.worlds ?? {}).flatMap(([alias, names]) => names.map((n) => `${alias}/${n}`))];\n return {\n ...base,\n prompt: answer.prompt,\n tools: answer.tools,\n verifiers,\n seed: rowCounts(answer.state ?? {}),\n reward: answer.grade?.reward ?? null,\n rewards: answer.grade?.rewards ?? {},\n verifierErrors: answer.verifier_errors ?? {},\n executed: true,\n };\n}\n\nfunction printWorldDryRun(ctx: CommandContext, run: WorldDryRun): void {\n ctx.stdout(`plan (world · task ${run.task}):`);\n for (const step of run.steps) ctx.stdout(` ${step.name.padEnd(9)} ${step.command}\\n ${step.note}`);\n ctx.stdout(` runner ${run.runner}`);\n if (!run.executed) {\n ctx.stdout(run.note);\n return;\n }\n ctx.stdout(`prompt: ${run.prompt ?? \"(none)\"}`);\n ctx.stdout(`tools: ${run.tools.join(\", \") || \"(none)\"}`);\n ctx.stdout(`verifiers: ${run.verifiers.join(\", \") || \"(none)\"}`);\n ctx.stdout(`seed: ${Object.entries(run.seed).map(([entity, rows]) => `${entity} ${rows}`).join(\", \") || \"(no rows)\"}`);\n if (Object.keys(run.verifierErrors).length) {\n for (const [name, error] of Object.entries(run.verifierErrors)) ctx.stdout(`FAIL verifier '${name}': ${error}`);\n return;\n }\n ctx.stdout(`reward: ${run.reward === null ? \"null (no verifier scored)\" : run.reward} ${JSON.stringify(run.rewards)}`);\n ctx.stdout(run.note);\n}\n\nexport function registerBenchmarksCommands(root: CommandGroup): void {\n const benchmarks = root.group(\n \"benchmarks\",\n \"Build, validate, dry-run, push, run and read a benchmark: a world with tasks, or a container benchmark, in benchmark order.\",\n );\n benchmarks.notes =\n \"A benchmark is either a WORLD with [[tasks]] (tools + data, a schema when the vendor has one; a prompt and the\\n\" +\n \"SQL verifiers that grade the world's end state; hosted on the World Host, one session per rollout) or a\\n\" +\n \"CONTAINER benchmark (a harbor task tree graded by its own tests/test.sh inside a container, or a verifiers\\n\" +\n \"package graded by Python reward functions; executed by the benchmark runner). Same commands, kind read from\\n\" +\n \"the tree, never guessed; `--kind` that disagrees with the tree is refused by name before anything is sent.\\n\" +\n \" init <dir> [--kind world|harbor|verifiers] world: worlds schema init + schema task add · harbor: one task\\n\" +\n \" (task.toml, instruction, tests, solution, environment) · verifiers: a Taskset\\n\" +\n \" validate <dir> world: worlds schema check + a task declared · container: every task's files,\\n\" +\n \" the reward contract in tests/test.sh, and the kind the runner will read\\n\" +\n \" dry-run <dir> [--task <name>] harbor: ONE task end to end in Docker (image, solution, tests, reward), or the\\n\" +\n \" exact plan when Docker is absent · verifiers: import and find the Taskset\\n\" +\n \" push <dir> [--slug s] world: worlds create --from <dir> · container: bench push (the runner's hub)\\n\" +\n \" run <slug> -m <model> [-k rollouts] the hosted run: every task × k rollouts per model, graded, one job per model\\n\" +\n \" results <slug> per-task mean reward, pass rate, samples, null scores (Results tab)\\n\" +\n \" import <dir> --from harbor|verifiers what of a container benchmark is expressible as world tasks (a report)\\n\" +\n \"A world never reaches the runner; a container tree never reaches the World Host. Versions, branches, tags,\\n\" +\n `proposals: \\`gateway bench\\`. Walkthrough: \\`gateway worlds skill ${BENCHMARKS_SKILL}\\` (\\`gateway skill search benchmark\\`).`;\n\n benchmarks.command({\n name: \"init\",\n help: \"Scaffold a benchmark of one kind: a world with a graded task (default), a harbor task tree, or a verifiers package. Local.\",\n positionals: [{ name: \"dir\", help: \"New or empty directory (its basename is the default slug).\" }],\n flags: [\n { name: \"kind\", help: \"world (default) | harbor | verifiers | image.\", default: \"world\" },\n {\n name: \"connector\",\n help: \"world: custom (blank contract + example entity, tools and verifier) or a shipped template (`gateway worlds schema templates`).\",\n default: \"custom\",\n },\n { name: \"name\", help: \"Benchmark name and package id (default: the directory name).\" },\n { name: \"task\", help: \"Id of the first task (world: first_task; harbor: hello-world; verifiers: capital_of_france).\" },\n { name: \"prompt\", help: \"What the agent is told for the first task (world: the [[tasks]] prompt; harbor: instruction.md).\" },\n { name: \"image\", help: \"harbor: the task's docker_image (default python:3.11-slim); image kind: the image ref.\" },\n { name: \"model\", help: \"Default model(s) for `benchmarks run`, written to benchmark.json (repeatable).\", repeat: true },\n { name: \"rollouts\", short: \"k\", help: \"Default rollouts per task for `benchmarks run`.\", default: \"1\" },\n HOST_FLAG,\n ],\n notes:\n \"world: writes what `gateway worlds schema init <dir> --connector …` writes (schema/world.json, gateway-env.toml,\\n\" +\n \"tools/handlers.py for custom, verifiers/state_present.sql) and appends one [[tasks]] entry with `schema task add`.\\n\" +\n \"harbor: pyproject.toml (slug, version), tasks/<task>/{task.toml, instruction.md, environment/Dockerfile,\\n\" +\n \"tests/test.sh, solution/solve.sh} — the hello-world task whose solution scores 1.0 and whose grader writes\\n\" +\n \"/logs/verifier/reward.json. verifiers: pyproject.toml (verifiers>=0.2) and <pkg>/__init__.py with one Taskset and\\n\" +\n \"one @vf.reward. Every kind writes benchmark.json (kind, models, rollouts). Then: validate, dry-run, push, run.\\n\" +\n \"image: refused — the runner has no hub engine for a bare image (its generic engine runs registry entries only).\",\n run: async (args, ctx) => {\n const dir = args.positionals[0]!;\n const kind = (arg.str(args, \"kind\") ?? \"world\") as BenchmarkKind;\n if (!BENCHMARK_KINDS.includes(kind)) throw new CliError(`--kind is one of ${BENCHMARK_KINDS.join(\", \")}`);\n if (kind === \"image\")\n throw new CliError(\n \"benchmarks init --kind image is not shipped: the benchmark runner has no hub engine for a bring-your-own image — \" +\n \"its generic engine (deploy/benchmark-runner/engines/generic_runner.py) runs registry entries from benchmarks.json, not pushed versions, \" +\n \"and `bench push --image` only records the ref on a world's server image. Shipping it needs an `image` kind in detect_env_kind, a runner branch \" +\n \"that runs the version's imageRef through the generic engine and harvests a reward, and the harvest itself. \" +\n \"Package the benchmark as a harbor task instead (`--kind harbor`: your image in [environment] docker_image, your grader in tests/test.sh).\",\n 2,\n );\n if (fs.existsSync(dir) && fs.readdirSync(dir).length > 0)\n throw new CliError(`${dir} is not empty; init writes a fresh ${kind} tree`, 1);\n const models = arg.list(args, \"model\");\n const rollouts = arg.int(args, \"rollouts\") ?? 1;\n const slug = path.basename(path.resolve(dir));\n\n if (kind === \"harbor\") {\n const scaffold = writeHarborScaffold(dir, {\n name: arg.str(args, \"name\"),\n task: arg.str(args, \"task\"),\n prompt: arg.str(args, \"prompt\"),\n image: arg.str(args, \"image\"),\n });\n writeConfig(dir, { kind, slug, models, rollouts });\n printJson(ctx, {\n status: \"ok\",\n dir,\n kind,\n tasks: [scaffold.task],\n files: [BENCHMARK_CONFIG, ...scaffold.files],\n next: [\n `gateway benchmarks validate ${dir}`,\n `gateway benchmarks dry-run ${dir} --task ${scaffold.task}`,\n `gateway benchmarks push ${dir}`,\n `gateway benchmarks run ${slug} --model <provider/model> -k 3`,\n ],\n });\n return 0;\n }\n if (kind === \"verifiers\") {\n const scaffold = writeVerifiersScaffold(dir, { name: arg.str(args, \"name\"), task: arg.str(args, \"task\") });\n writeConfig(dir, { kind, slug, models, rollouts });\n printJson(ctx, {\n status: \"ok\",\n dir,\n kind,\n package: scaffold.pkg,\n files: [BENCHMARK_CONFIG, ...scaffold.files],\n next: [`gateway benchmarks validate ${dir}`, `gateway benchmarks dry-run ${dir}`, `gateway benchmarks push ${dir}`, `gateway benchmarks run ${slug} --model <provider/model> -k 3`],\n });\n return 0;\n }\n\n const connector = arg.str(args, \"connector\") ?? \"custom\";\n const initArgs = [\"worlds\", \"schema\", \"init\", dir, \"--connector\", connector];\n const name = arg.str(args, \"name\");\n if (name) initArgs.push(\"--name\", name);\n if (connector === \"custom\") initArgs.push(\"--with-example-tool\");\n const host = arg.str(args, \"host\");\n if (host) initArgs.push(\"--host\", host);\n const init = await captureSub(root, initArgs, ctx);\n if (init.code !== 0) return init.code;\n\n // A task grades on a verifier; the custom scaffold ships state_present.sql,\n // a template may not, so the placeholder is written for the first entity.\n let verifiers = verifierNames(dir);\n if (verifiers.length === 0) {\n const entity = firstEntity(dir);\n if (!entity) throw new CliError(`${dir}: schema/world.json declares no entity to write a verifier for`, 1);\n fs.mkdirSync(path.join(dir, \"verifiers\"), { recursive: true });\n fs.writeFileSync(\n path.join(dir, \"verifiers\", \"state_present.sql\"),\n `-- Scores 1.0 once the world holds any ${entity} row; edit for real tasks.\\n` +\n `SELECT CASE WHEN COUNT(*) > 0 THEN 1.0 ELSE 0.0 END FROM \"${entity}\";\\n`,\n );\n verifiers = [\"state_present\"];\n }\n const taskId = arg.str(args, \"task\") ?? \"first_task\";\n const prompt = arg.str(args, \"prompt\") ?? \"Complete the task described here; the verifiers grade the world's end state.\";\n const task = await captureSub(root, [\"worlds\", \"schema\", \"task\", \"add\", dir, taskId, \"--prompt\", prompt, \"--verifier\", verifiers[0]!], ctx);\n if (task.code !== 0) return task.code;\n writeConfig(dir, { kind, slug, models, rollouts });\n printJson(ctx, {\n status: \"ok\",\n dir,\n kind,\n connector,\n tasks: declaredTasks(dir),\n verifiers,\n files: [BENCHMARK_CONFIG, \"gateway-env.toml\", \"schema/world.json\", `verifiers/${verifiers[0]}.sql`],\n next: [\n `gateway benchmarks validate ${dir}`,\n `gateway worlds schema task add ${dir} <id> --prompt \"...\" --verifier ${verifiers[0]}`,\n `gateway benchmarks push ${dir}`,\n `gateway benchmarks run ${slug} --model <provider/model> -k 3`,\n ],\n });\n return 0;\n },\n });\n\n const validate = async (args: Parsed, ctx: CommandContext, command: string): Promise<number> => {\n const dir = args.positionals[0]!;\n const { kind } = resolveKind(dir, args, command);\n if (kind === \"world\") {\n const host = arg.str(args, \"host\");\n const checked = await captureSub(root, [\"worlds\", \"schema\", \"check\", dir, ...(host ? [\"--host\", host] : [])], ctx);\n ctx.stdout(checked.out);\n if (checked.code !== 0) return checked.code;\n const report = safeJson(checked.out);\n const tasks = Array.isArray(report.tasks) ? (report.tasks as { id?: string }[]) : [];\n if (tasks.length === 0) {\n ctx.stderr(`${dir} declares no [[tasks]]; a benchmark needs at least one: gateway worlds schema task add ${dir} <id> --prompt \"...\" --verifier <name>`);\n return 2;\n }\n ctx.stderr(`benchmark ok (world): ${tasks.length} task(s): ${tasks.map((t) => t.id ?? \"?\").join(\", \")}`);\n return 0;\n }\n const report = kind === \"harbor\" ? validateHarbor(dir) : validateVerifiers(dir);\n if (arg.bool(args, \"json\")) printJson(ctx, report);\n else printValidation(ctx, report);\n if (!report.ok) return 2;\n ctx.stderr(\n `benchmark ok (${kind}): ${kind === \"harbor\" ? `${report.tasks.length} task(s): ${report.tasks.map((t) => t.id).join(\", \")}` : `package ${report.package?.name}`}; next: gateway benchmarks dry-run ${dir}`,\n );\n return 0;\n };\n\n benchmarks.command({\n name: \"validate\",\n help: \"Validate a benchmark of any kind before pushing: the world's contract and tasks, or every container task's files and reward contract. Local.\",\n positionals: [{ name: \"dir\", help: \"Benchmark directory (a world tree, a harbor tree or a verifiers package).\" }],\n flags: [\n { name: \"kind\", help: \"Refuse unless the tree is this kind: world | harbor | verifiers.\" },\n { name: \"json\", help: \"Print the report as JSON.\", boolean: true },\n HOST_FLAG,\n ],\n notes:\n \"world: `gateway worlds schema check <dir>` and at least one [[tasks]] entry (exit 2 otherwise).\\n\" +\n \"harbor: every tasks/<name>/ has task.toml, instruction.md, an image ([environment] docker_image or\\n\" +\n \"environment/Dockerfile) and tests/test.sh that writes /logs/verifier/reward.json; solution/solve.sh is noted\\n\" +\n \"when absent (dry-run needs it, the runner does not); and detect_env_kind — the runner's own dispatch rule —\\n\" +\n \"reads the tree as harbor. verifiers: pyproject.toml pins verifiers>=0.2, the package exports a Taskset\\n\" +\n \"through __all__, reward functions exist. Exit 2 on any problem; notes never fail it.\",\n run: (args, ctx) => validate(args, ctx, \"validate\"),\n });\n\n benchmarks.command({\n name: \"check\",\n help: \"The same as `benchmarks validate`.\",\n positionals: [{ name: \"dir\", help: \"Benchmark directory.\" }],\n flags: [{ name: \"kind\", help: \"Refuse unless the tree is this kind.\" }, { name: \"json\", help: \"Print the report as JSON.\", boolean: true }, HOST_FLAG],\n run: (args, ctx) => validate(args, ctx, \"check\"),\n });\n\n benchmarks.command({\n name: \"dry-run\",\n help: \"Run ONE task locally the way the platform would (world: open, grade untouched, close; harbor: Docker; verifiers: import), or print the exact plan when it cannot. Local.\",\n positionals: [{ name: \"dir\", help: \"Benchmark directory (a world tree, a harbor tree or a verifiers package).\" }],\n flags: [\n { name: \"task\", help: \"Which task (default: the first).\" },\n { name: \"kind\", help: \"Refuse unless the tree is this kind.\" },\n { name: \"plan\", help: \"Print the plan only; never execute.\", boolean: true },\n { name: \"here\", help: \"verifiers: import the package in THIS machine's Python instead of Docker — runs the package's module-level code as you.\", boolean: true },\n { name: \"json\", help: \"Print plan and result as JSON.\", boolean: true },\n ],\n notes:\n \"harbor: builds environment/Dockerfile (or pulls docker_image), runs the container with tests/ at /tests,\\n\" +\n \"solution/ at /solution and a scratch /logs, executes `bash /solution/solve.sh` then `bash /tests/test.sh`\\n\" +\n \"— what harbor's oracle agent and the task's verifier do on the runner — and reads /logs/verifier/reward.json.\\n\" +\n \"The reference solution must score 1.0. Without Docker (`GATEWAY_DOCKER` names the binary) the plan is printed\\n\" +\n \"with the static check of the tests and the run is marked not executed; the plan is exact, not a summary.\\n\" +\n \"verifiers: the runner's first pass — import verifiers.v1, then the package, find the Taskset in __all__ —\\n\" +\n \"inside Docker: an image built from python:3.11-slim + `pip install verifiers>=0.2`, then `docker run --rm\\n\" +\n \"--network none` with the tree mounted read-only. Trust boundary: importing a package runs its module-level\\n\" +\n \"code; by default that happens in the container, never as you. `--here` runs the same import in this\\n\" +\n \"machine's Python (GATEWAY_PYTHON) — as you, with your files and network. The rewards themselves need a\\n\" +\n \"model and run in `benchmarks run`. The harbor container also runs with --network none.\\n\" +\n \"world: the bundled runtime opens one session under the task exactly as `worlds serve --task` does (its seed\\n\" +\n \"laid, its tools served), grades the UNTOUCHED state with the task's verifiers, and closes; prints the prompt,\\n\" +\n \"tools, verifiers, seed rows per entity, reward and rewards. A verifier that cannot run (bad SQL, a missing\\n\" +\n \"entity) is named with SQLite's words and exits 1 — that is what the dry run is for. The reward is the untouched\\n\" +\n \"world's; an agent's rollout is what `benchmarks run` grades (`worlds serve` + `worlds call … --grade` by hand).\\n\" +\n \"Exit 0 when the plan holds (executed or not); 2 when the task is invalid or a harbor reward is not 1.0; 1 when\\n\" +\n \"a world verifier fails to run.\",\n run: async (args, ctx) => {\n const dir = args.positionals[0]!;\n const { kind } = resolveKind(dir, args, \"dry-run\");\n if (kind === \"world\") {\n const declared = declaredTasks(dir);\n if (declared.length === 0)\n throw new CliError(\n `benchmarks dry-run: ${dir} declares no [[tasks]]; add one with \\`gateway worlds schema task add ${dir} <id> --prompt \"...\" --verifier <name>\\``,\n 2,\n );\n const wanted = arg.str(args, \"task\");\n if (wanted !== undefined && !declared.includes(wanted))\n throw new CliError(`benchmarks dry-run: no task ${wanted} in ${dir}; tasks: ${declared.join(\", \")}`, 2);\n const task = wanted ?? declared[0]!;\n if (wanted === undefined && declared.length > 1) ctx.stderr(`no --task: the first of ${declared.length} tasks, ${task} (${declared.join(\", \")})`);\n const result = await dryRunWorld(dir, task, { plan: arg.bool(args, \"plan\") });\n if (arg.bool(args, \"json\")) printJson(ctx, result);\n else printWorldDryRun(ctx, result);\n const failed = Object.keys(result.verifierErrors ?? {});\n if (failed.length) {\n ctx.stderr(`verifier${failed.length > 1 ? \"s\" : \"\"} ${failed.map((n) => `'${n}'`).join(\", \")} cannot run on this world; fix the SQL, then dry-run again`);\n return 1;\n }\n return 0;\n }\n if (kind === \"harbor\") {\n let plan;\n try {\n plan = harborRunPlan(dir, arg.str(args, \"task\"));\n } catch (error) {\n throw new CliError(`benchmarks dry-run: ${(error as Error).message}`, 2);\n }\n const invalid = plan.validation.problems.length > 0;\n const result: DryRunResult = invalid\n ? { executed: false, reason: `the task is invalid (${plan.validation.problems.length} problem(s) above); fix it, then dry-run`, commands: [] }\n : arg.bool(args, \"plan\")\n ? { executed: false, reason: \"--plan: not executed\", commands: [] }\n : dryRunHarbor(dir, plan);\n if (arg.bool(args, \"json\")) printJson(ctx, { plan, result });\n else printDryRun(ctx, plan as unknown as Record<string, unknown>, result);\n if (invalid) return 2;\n if (result.executed && result.reward !== 1) {\n ctx.stderr(result.reward === null ? \"ungraded: the grader wrote no reward\" : `the reference solution scored ${result.reward}, not 1.0`);\n return 2;\n }\n return 0;\n }\n const validation = validateVerifiers(dir);\n const python = arg.bool(args, \"here\") ? findPython() : null;\n const plan = verifiersRunPlan(dir, validation, python);\n const result: DryRunResult = !validation.ok\n ? { executed: false, reason: `the package is invalid: ${validation.problems.join(\"; \")}`, commands: [] }\n : arg.bool(args, \"plan\")\n ? { executed: false, reason: \"--plan: not executed\", commands: [] }\n : dryRunVerifiers(dir, plan, { here: arg.bool(args, \"here\"), python });\n if (arg.bool(args, \"json\")) printJson(ctx, { plan, result });\n else printDryRun(ctx, plan as unknown as Record<string, unknown>, result);\n return validation.ok && (!result.executed || result.exitCode === 0) ? 0 : 2;\n },\n });\n\n benchmarks.command({\n name: \"push\",\n help: \"Publish the benchmark: a world tree as a world (`worlds create`), a container tree to the benchmark runner (`bench push`).\",\n positionals: [{ name: \"dir\", help: \"Benchmark directory.\" }],\n flags: [\n { name: \"kind\", help: \"Refuse unless the tree is this kind: world | harbor | verifiers.\" },\n { name: \"slug\", help: \"Slug (default: the directory name; container trees: pyproject name).\" },\n { name: \"name\", help: \"Display name (default: the slug).\" },\n { name: \"message\", short: \"m\", help: \"Change reason recorded on the version.\" },\n { name: \"json\", help: \"Print the created world / pushed version as JSON.\", boolean: true },\n HOST_FLAG,\n ],\n notes:\n \"world: POST /api/public/worlds with the tree (the request `gateway worlds create <slug> --from <dir>` sends): stored\\n\" +\n \"as it is, compiled by the schema runtime, refused with the path when the contract does not hold; when the slug\\n\" +\n \"exists the tree is pushed as the next version (`gateway bench push`, unpackaged). The benchmark runner is never\\n\" +\n \"involved. container (harbor, verifiers): the benchmark-container hub (`gateway bench push <dir>` into this\\n\" +\n \"project: resolve, versions, finalize); the runner executes it on `benchmarks run`. The World Host, sessions and\\n\" +\n \"data batches are never involved. A `--kind` that disagrees with the tree is refused before any request.\",\n run: async (args, ctx) => {\n const dir = args.positionals[0]!;\n const { kind, classified } = resolveKind(dir, args, \"push\");\n const slug = arg.str(args, \"slug\") ?? path.basename(path.resolve(dir));\n const message = arg.str(args, \"message\");\n const name = arg.str(args, \"name\");\n // What the tree is, checked before any request.\n let report: TreeValidation | null = null;\n if (kind !== \"world\") {\n report = kind === \"harbor\" ? validateHarbor(dir) : validateVerifiers(dir);\n if (!report.ok)\n throw new CliError(\n `benchmarks push: ${dir} does not validate (${[...report.problems, ...report.tasks.flatMap((t) => t.problems)].slice(0, 3).join(\"; \")}); run \\`gateway benchmarks validate ${dir}\\``,\n 2,\n );\n }\n const tasks = declaredTasks(dir);\n if (kind === \"world\" && tasks.length === 0)\n throw new CliError(\n `benchmarks push: ${dir} declares no [[tasks]]; add one with \\`gateway worlds schema task add ${dir} <id> --prompt \"...\" --verifier <name>\\` (a world without tasks is published with \\`gateway worlds create\\`).`,\n 2,\n );\n const creds = credentials(args);\n // What the slug already holds, read before any write: one slug, one substrate.\n const existing = await existingSlug(creds, slug);\n const incoming: \"world\" | \"container\" = kind === \"world\" ? \"world\" : \"container\";\n if (existing?.substrate && existing.substrate !== incoming) refuseSlug(slug, existing, classified, incoming);\n const describe = kind === \"harbor\" ? `${report!.tasks.length} task(s)` : kind === \"verifiers\" ? `package ${report!.package?.name}` : `${tasks.length} task(s)`;\n if (kind !== \"world\" || existing?.substrate === \"world\") {\n // A container tree, or a new version of a world the slug already holds: the hub.\n const pushed = await push(dir, { slug, name, message, options: worldsOptions(creds) });\n const landed = pushed.slug ?? slug;\n if (arg.bool(args, \"json\")) printJson(ctx, { ...pushed, slug: landed, kind, substrate: incoming });\n else if (kind === \"world\") ctx.stdout(`pushed ${landed} as a new version ${pushed.contentHash.slice(0, 12)} · ${describe}`);\n else ctx.stdout(`pushed ${landed} (${kind}, benchmark runner) ${pushed.contentHash.slice(0, 12)} · ${describe} · version ${pushed.versionId}${pushed.state ? ` · ${pushed.state}` : \"\"}`);\n ctx.stderr(`next: gateway benchmarks run ${landed} --model <provider/model> -k 3`);\n return 0;\n }\n if (existing)\n throw new CliError(\n `benchmarks push: slug \\`${slug}\\` is taken by an environment with no version to read a substrate from; pass --slug <new-slug>. Nothing was written.`,\n 2,\n );\n const body: Record<string, unknown> = { slug, from: { files: collectFiles(dir) } };\n if (name) body.name = name;\n if (message) body.message = message;\n const world = await api<CreatedWorld>(creds, \"POST\", WORLDS, body, { timeoutMs: 600_000 });\n printDeprecations(ctx, world.deprecations);\n if (arg.bool(args, \"json\")) printJson(ctx, world);\n else ctx.stdout(`created ${world.slug} (${world.kind}) ${world.version.contentHash.slice(0, 12)} · ${describe} · ${world.url}`);\n ctx.stderr(`next: gateway benchmarks run ${world.slug} --model <provider/model> -k 3`);\n return 0;\n },\n });\n\n benchmarks.command({\n name: \"run\",\n help: \"Run the benchmark hosted: every task × k rollouts per model, graded on the platform (`environment run`).\",\n positionals: [{ name: \"slug\", help: \"The pushed benchmark's slug (or container id).\" }],\n flags: [\n {\n name: \"model\",\n short: \"m\",\n help: \"Model, provider-prefixed (anthropic/…, openrouter/vendor/model, gateway/vendor/model); repeatable. Default: benchmark.json in --dir.\",\n repeat: true,\n },\n { name: \"rollouts\", short: \"k\", help: \"Rollouts per task (default: benchmark.json, else 1).\" },\n { name: \"num-examples\", short: \"n\", help: \"Cap the tasks run (default: all).\" },\n { name: \"version-id\", help: \"Pin a READY version (default: newest).\" },\n { name: \"dir\", help: \"The benchmark's directory, whose benchmark.json supplies model and rollout defaults; its slug must match.\" },\n { name: \"no-wait\", help: \"Return after dispatch instead of blocking until every run settles.\", boolean: true },\n { name: \"wait-timeout\", help: \"Seconds to wait before giving up.\", default: \"1200\" },\n HOST_FLAG,\n ],\n notes:\n \"One run per model (POST /api/public/environments/{id}/run, the same request as `gateway environment run`).\\n\" +\n \"A world: each rollout is a session on the World Host graded by the task's SQL verifiers. A harbor tree: one\\n\" +\n \"runner job per model runs `harbor run` over every task (the agent in the task's container, then tests/test.sh).\\n\" +\n \"A verifiers package: the runner installs it and runs v1's run_eval in-process. Each run files an evaluation;\\n\" +\n \"the verdict prints per model, then per task. Follow a run with `gateway environment run-status <run_id>`;\\n\" +\n \"read the aggregate with `gateway benchmarks results <slug>`. Never set max_tokens on the model.\",\n run: async (args, ctx) => {\n const slug = args.positionals[0]!;\n const dirFlag = arg.str(args, \"dir\");\n const config = dirFlag ? readConfig(dirFlag) : {};\n if (dirFlag) {\n // A benchmark.json belongs to one benchmark: never read another's defaults into this run.\n const owner = config.slug ?? path.basename(path.resolve(dirFlag));\n if (owner !== slug)\n throw new CliError(`benchmarks run: --dir ${dirFlag} is the benchmark \\`${owner}\\` (its benchmark.json), not \\`${slug}\\`; pass that benchmark's --dir, or --model and -k explicitly`, 2);\n }\n const models = arg.list(args, \"model\").length ? arg.list(args, \"model\") : (config.models ?? []);\n if (models.length === 0)\n throw new CliError(\n dirFlag\n ? `benchmarks run needs --model <provider/model> (benchmark.json in ${dirFlag} lists no models)`\n : \"benchmarks run needs --model <provider/model>, or --dir <benchmark dir> whose benchmark.json supplies models and rollouts\",\n );\n const rollouts = arg.int(args, \"rollouts\") ?? config.rollouts;\n return runEnvironment(credentials(args), slug, ctx, {\n models,\n versionId: arg.str(args, \"version-id\"),\n numExamples: arg.int(args, \"num-examples\"),\n rollouts,\n wait: !arg.bool(args, \"no-wait\"),\n waitTimeoutSeconds: arg.int(args, \"wait-timeout\") ?? 1200,\n });\n },\n });\n\n benchmarks.command({\n name: \"results\",\n help: \"Per-task results across every run: mean reward, pass rate, samples, null scores (what the Results tab shows).\",\n positionals: [{ name: \"slug\", help: \"The benchmark's slug (or container id).\" }],\n flags: [\n { name: \"runs\", help: \"Also list the runs (rollouts), newest first.\", boolean: true },\n { name: \"json\", help: \"Print the aggregate as JSON.\", boolean: true },\n HOST_FLAG,\n ],\n notes:\n \"GET /api/public/environments/{id}/performance (and /rollouts with --runs) — the same rows for a world and for a\\n\" +\n \"container benchmark. Null scores are their own count, never 0. In the app: the benchmark's page → Results tab;\\n\" +\n \"each run links its evaluation and samples.\",\n run: async (args, ctx) => {\n const creds = credentials(args);\n const id = await resolveEnvironmentId(creds, args.positionals[0]!);\n const performance = await api<{\n tasks: {\n task: string;\n sampleCount: number;\n nullScoreCount: number;\n avgReward: number | null;\n passRate: number | null;\n }[];\n totalSamples: number;\n totalNullScoreSamples: number;\n }>(creds, \"GET\", `/api/public/environments/${encodeURIComponent(id)}/performance`);\n const runs = arg.bool(args, \"runs\")\n ? await api<{ rollouts: { id: string; model: string | null; status: string; createdAt: string; sampleCount: number; rolloutsPerExample: number | null }[] }>(\n creds,\n \"GET\",\n `/api/public/environments/${encodeURIComponent(id)}/rollouts`,\n )\n : null;\n if (arg.bool(args, \"json\")) {\n printJson(ctx, runs ? { ...performance, runs: runs.rollouts } : performance);\n return 0;\n }\n if (performance.tasks.length === 0) {\n ctx.stdout(`no results yet for ${args.positionals[0]}: gateway benchmarks run ${args.positionals[0]} --model <provider/model>`);\n return 0;\n }\n ctx.stdout(`task mean reward pass rate samples no score`);\n for (const t of performance.tasks)\n ctx.stdout(\n `${t.task.padEnd(30).slice(0, 30)}${(t.avgReward === null ? \"-\" : t.avgReward.toFixed(3)).padStart(11)}${(t.passRate === null ? \"-\" : (t.passRate * 100).toFixed(0) + \"%\").padStart(12)}${String(t.sampleCount).padStart(10)}${String(t.nullScoreCount).padStart(11)}`,\n );\n ctx.stdout(`${performance.totalSamples} samples, ${performance.totalNullScoreSamples} without a score`);\n if (runs) {\n ctx.stdout(\"\");\n for (const r of runs.rollouts)\n ctx.stdout(`${r.createdAt} ${r.status.padEnd(10)} ${(r.model ?? \"?\").padEnd(32)} k=${r.rolloutsPerExample ?? \"?\"} ${r.sampleCount} samples ${r.id}`);\n }\n return 0;\n },\n });\n\n benchmarks.command({\n name: \"import\",\n help: \"Report what of a harbor task tree or a verifiers package is expressible as world tasks; writes nothing.\",\n positionals: [{ name: \"dir\", help: \"The harbor task tree or verifiers package.\" }],\n flags: [\n { name: \"from\", help: \"harbor or verifiers.\" },\n { name: \"json\", help: \"Print the report as JSON.\", boolean: true },\n ],\n notes:\n \"A world task is a prompt plus SQL verifiers over world state. A harbor task grades a container filesystem\\n\" +\n \"with tests/test.sh and a verifiers task grades the completion text with Python, so neither converts on its\\n\" +\n \"own: each is listed with the reason. The tree stays a first-class container benchmark (`benchmarks validate`,\\n\" +\n \"`dry-run`, `push`, `run`); to grade the same work over world state, author it with `gateway benchmarks init`.\\n\" +\n \"Exit 2 when any task was refused, 0 when every task converted.\",\n run: async (args, ctx) => {\n const dir = args.positionals[0]!;\n const from = arg.str(args, \"from\");\n if (from !== \"harbor\" && from !== \"verifiers\") throw new CliError(\"benchmarks import needs --from harbor|verifiers\");\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);\n const report = importReport(dir, from);\n if (arg.bool(args, \"json\")) printJson(ctx, report);\n else {\n ctx.stdout(`${dir}: ${SHAPE_LABELS[report.shape]} — ${report.tasks.length} ${from} task(s), ${report.converted} converted, ${report.refused} refused`);\n for (const task of report.tasks)\n ctx.stdout(` ${task.expressible ? \"ok \" : \"refused\"} ${task.id}: ${task.grader}${task.prompt ? ` — \"${task.prompt.slice(0, 80)}\"` : \"\"}\\n ${task.reason}`);\n ctx.stdout(report.note);\n }\n return report.refused > 0 || report.tasks.length === 0 ? 2 : 0;\n },\n });\n}\n","/**\n * BENCHMARKS — what a directory IS, for the benchmark front door.\n *\n * Owner, 2026-09-16: \"combine the two infras as much as possible to make it\n * easy for people to use the schema worlds to build benchmarks, which is just\n * creating one world with tools + data and an optional schema, versus the\n * normal benchmarking setup.\" And: \"if an agent wants to make a benchmark\n * e2e properly, we need guides for that and a dry run and the\n * harbor/verifiers (prio harbor) or a generic benchmark infra (pure container\n * logic + runner) should ALL work and be properly segmented and not crash\n * with each other's infra.\"\n *\n * Two substrates, one front door. A benchmark is either\n *\n * - a **world** (`gateway-env.toml` with `[schema]`, `schema/world.json`,\n * optional tools and connector) plus `[[tasks]]` (a prompt and the SQL\n * verifiers that grade world state) — hosted on the World Host, one session\n * per rollout; or\n * - a **container** benchmark: a harbor task tree (`tasks/<name>/task.toml`,\n * the task grades a container filesystem with `tests/test.sh`) or a\n * verifiers package (`pyproject.toml` + a Python Taskset whose reward\n * functions grade the completion) — executed by the benchmark runner\n * (AWS Batch), one job per model.\n *\n * This module tells them apart from the tree alone, with the same rules as\n * `classifyWorldPaths` in gateway/packages/shared and `detect_env_kind` in\n * gatewaysdk/benchmark_hub/harbor_adapter.py (the runner's dispatch), so the\n * CLI, the worlds paths and the runner never disagree about what a tree is.\n * The container substrate's scaffolds, validation, run plan and dry-run live\n * in ./container.ts.\n */\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nexport const BENCHMARKS_SKILL = \"benchmarks-getting-started\";\n\nexport type TreeShape =\n | \"schema-world\"\n | \"api-bundle\"\n | \"legacy-tools\"\n | \"harbor\"\n | \"verifiers\"\n | \"none\";\nexport type Substrate = \"world\" | \"container\" | \"none\";\n/** What `benchmarks init --kind` builds and what `push`/`run` route on. */\nexport type BenchmarkKind = \"world\" | \"harbor\" | \"verifiers\" | \"image\";\nexport const BENCHMARK_KINDS: BenchmarkKind[] = [\"world\", \"harbor\", \"verifiers\", \"image\"];\n\nexport type TreeClassification = {\n shape: TreeShape;\n substrate: Substrate;\n /** The files that decided it, relative to the directory. */\n markers: string[];\n};\n\nconst exists = (dir: string, rel: string): boolean => fs.existsSync(path.join(dir, rel));\n\n/** Task directories of a harbor tree: `tasks/<name>/task.toml` or `<name>/task.toml`. */\nexport function harborTaskDirs(dir: string): string[] {\n const out: string[] = [];\n for (const base of [path.join(dir, \"tasks\"), dir]) {\n if (!fs.existsSync(base) || !fs.statSync(base).isDirectory()) continue;\n for (const entry of fs.readdirSync(base, { withFileTypes: true })) {\n if (entry.isDirectory() && fs.existsSync(path.join(base, entry.name, \"task.toml\")))\n out.push(path.relative(dir, path.join(base, entry.name)).split(path.sep).join(\"/\"));\n }\n if (out.length) break;\n }\n return out.sort();\n}\n\n/** The Python package of a verifiers tree (`<pkg>/__init__.py` or `src/<pkg>/__init__.py`), or null. */\nexport function verifiersPackage(dir: string): { name: string; init: string } | null {\n if (!exists(dir, \"pyproject.toml\")) return null;\n for (const base of [dir, path.join(dir, \"src\")]) {\n if (!fs.existsSync(base)) continue;\n for (const entry of fs.readdirSync(base, { withFileTypes: true })) {\n if (!entry.isDirectory() || entry.name.startsWith(\".\") || entry.name === \"tests\") continue;\n const init = path.join(base, entry.name, \"__init__.py\");\n if (fs.existsSync(init)) return { name: entry.name, init: path.relative(dir, init).split(path.sep).join(\"/\") };\n }\n }\n return null;\n}\n\nexport function classifyTree(dir: string): TreeClassification {\n if (exists(dir, \"gateway-api-world.toml\"))\n return { shape: \"api-bundle\", substrate: \"world\", markers: [\"gateway-api-world.toml\"] };\n if (exists(dir, \"schema/world.json\"))\n return {\n shape: \"schema-world\",\n substrate: \"world\",\n markers: [\"schema/world.json\", ...(exists(dir, \"gateway-env.toml\") ? [\"gateway-env.toml\"] : [])],\n };\n if (exists(dir, \"gateway-env.toml\"))\n return {\n shape: \"legacy-tools\",\n substrate: \"world\",\n markers: [\"gateway-env.toml\", ...(exists(dir, \"db/schema.sql\") ? [\"db/schema.sql\"] : [])],\n };\n const tasks = harborTaskDirs(dir);\n if (tasks.length) return { shape: \"harbor\", substrate: \"container\", markers: tasks.map((t) => `${t}/task.toml`) };\n const pkg = verifiersPackage(dir);\n if (pkg) return { shape: \"verifiers\", substrate: \"container\", markers: [\"pyproject.toml\", pkg.init] };\n return { shape: \"none\", substrate: \"none\", markers: [] };\n}\n\n/** The kind a tree is, for `--kind` agreement; null when it is nothing. */\nexport function kindOfTree(classified: TreeClassification): BenchmarkKind | null {\n if (classified.substrate === \"world\") return \"world\";\n if (classified.shape === \"harbor\") return \"harbor\";\n if (classified.shape === \"verifiers\") return \"verifiers\";\n return null;\n}\n\n/**\n * The runner's `detect_env_kind` (gatewaysdk/benchmark_hub/harbor_adapter.py,\n * kept in step with engines/hub_bundle.py), in TypeScript: the kind the\n * dispatcher will execute a pushed tree as. `validate` prints it beside the\n * CLI's own classification so a tree that the two would read differently is\n * caught before it is pushed.\n */\nexport type EnvKind = \"api\" | \"mock-tools\" | \"harbor\" | \"verifiers-v1\" | \"verifiers\";\n\nconst V1_DEP = /[\"']verifiers\\s*(?:\\[[^\\]]*\\])?\\s*(?:>=|~=|==|>)\\s*(?:0\\.(?:[2-9]\\d*|[1-9]\\d+)|[1-9]\\d*)/;\nconst V1_IMPORT = /^\\s*(?:from\\s+verifiers\\.v1\\s+import\\b|from\\s+verifiers\\s+import\\s+v1\\b|import\\s+verifiers\\.v1\\b)/m;\nconst V1_TASKSET = /class\\s+\\w+\\s*\\(\\s*(?:(?:vf|v1|verifiers(?:\\.v1)?)\\.)?Taskset\\s*[,)]/;\n\nfunction isVerifiersV1(dir: string): boolean {\n const pyproject = path.join(dir, \"pyproject.toml\");\n if (fs.existsSync(pyproject) && V1_DEP.test(fs.readFileSync(pyproject, \"utf8\"))) return true;\n for (const base of [dir, path.join(dir, \"src\")]) {\n if (!fs.existsSync(base)) continue;\n for (const entry of fs.readdirSync(base, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const init = path.join(base, entry.name, \"__init__.py\");\n if (!fs.existsSync(init)) continue;\n const text = fs.readFileSync(init, \"utf8\");\n if (V1_IMPORT.test(text)) return true;\n if (text.includes(\"__all__\") && V1_TASKSET.test(text)) return true;\n }\n }\n return false;\n}\n\nexport function detectEnvKind(dir: string): EnvKind {\n if (exists(dir, \"gateway-api-world.toml\")) return \"api\";\n if (exists(dir, \"gateway-env.toml\")) return \"mock-tools\";\n if (harborTaskDirs(dir).length) return \"harbor\";\n if (isVerifiersV1(dir)) return \"verifiers-v1\";\n return \"verifiers\";\n}\n\nexport const SHAPE_LABELS: Record<TreeShape, string> = {\n \"schema-world\": \"schema world (gateway-world/1)\",\n \"api-bundle\": \"api bundle (a schema world packaged with gateway-api-world.toml)\",\n \"legacy-tools\": \"legacy tools world (gateway-env.toml without a contract)\",\n harbor: \"harbor task tree\",\n verifiers: \"verifiers package\",\n none: \"not a world and not a benchmark package\",\n};\n\n/** `[[tasks]]` ids declared in a world's gateway-env.toml. */\nexport function declaredTasks(dir: string): string[] {\n const file = path.join(dir, \"gateway-env.toml\");\n if (!fs.existsSync(file)) return [];\n const toml = fs.readFileSync(file, \"utf8\");\n const ids: string[] = [];\n let inTask = false;\n for (const raw of toml.split(\"\\n\")) {\n const line = raw.trim();\n if (/^\\[\\[tasks\\]\\]$/.test(line)) {\n inTask = true;\n continue;\n }\n if (/^\\[/.test(line)) inTask = false;\n if (inTask) {\n const m = /^id\\s*=\\s*\"([^\"]+)\"/.exec(line);\n if (m) ids.push(m[1]!);\n }\n }\n return ids;\n}\n\nexport type ImportTask = {\n id: string;\n /** What the agent is told, when the source names it. */\n prompt: string | null;\n grader: string;\n /** Whether the task can be expressed as a world task (a prompt + verifiers over world state). */\n expressible: boolean;\n reason: string;\n};\n\nexport type ImportReport = {\n dir: string;\n from: \"harbor\" | \"verifiers\";\n shape: TreeShape;\n tasks: ImportTask[];\n converted: number;\n refused: number;\n /** Why nothing was written, when nothing was. */\n note: string;\n};\n\nfunction firstLine(file: string): string | null {\n if (!fs.existsSync(file)) return null;\n const text = fs.readFileSync(file, \"utf8\").trim();\n return text ? text.split(\"\\n\")[0]!.trim() : null;\n}\n\n/**\n * What of a container-substrate benchmark is expressible over world state.\n *\n * A harbor task grades with `tests/test.sh` in a container: it reads a\n * filesystem or runs a program, neither of which a world holds, so the task\n * is refused by name. A verifiers task grades with a Python reward function\n * over the model's completion; a world grades state, not text. Conversion is\n * therefore a report today (phase 2 of `.llm_artifacts/plans/benchmarks-on-\n * worlds-2026-09-16.md`): every task is listed with the reason, nothing is\n * written. The tree itself is a first-class container benchmark: `benchmarks\n * validate`, `dry-run` and `push` run it on the benchmark runner as it is.\n */\nexport function importReport(dir: string, from: \"harbor\" | \"verifiers\"): ImportReport {\n const classified = classifyTree(dir);\n const tasks: ImportTask[] = [];\n if (from === \"harbor\") {\n for (const taskDir of harborTaskDirs(dir)) {\n const id = path.basename(taskDir);\n const tests = path.join(dir, taskDir, \"tests\");\n const grader = fs.existsSync(tests)\n ? fs\n .readdirSync(tests)\n .map((f) => `tests/${f}`)\n .join(\", \") || \"tests/ (empty)\"\n : \"no tests/\";\n tasks.push({\n id,\n prompt: firstLine(path.join(dir, taskDir, \"instruction.md\")),\n grader,\n expressible: false,\n reason: `${grader} grades a container filesystem after the agent runs; a world task grades world state with SQL verifiers`,\n });\n }\n } else {\n const pkg = verifiersPackage(dir);\n if (pkg) {\n const source = fs.readFileSync(path.join(dir, pkg.init), \"utf8\");\n const rewards = [...source.matchAll(/@vf\\.reward[^\\n]*\\n\\s*(?:async\\s+)?def\\s+(\\w+)/g)].map((m) => m[1]!);\n const tasksets = [...source.matchAll(/class\\s+(\\w+)\\s*\\(\\s*(?:vf|v1|verifiers(?:\\.v1)?)?\\.?Taskset\\s*[,)]/g)].map(\n (m) => m[1]!,\n );\n const names = tasksets.length ? tasksets : [pkg.name];\n for (const id of names)\n tasks.push({\n id,\n prompt: null,\n grader: rewards.length ? `reward functions ${rewards.join(\", \")}` : \"reward functions (none found by name)\",\n expressible: false,\n reason: \"the reward runs Python over the model's completion text; a world task grades world state with SQL verifiers\",\n });\n }\n }\n const refused = tasks.filter((t) => !t.expressible).length;\n return {\n dir,\n from,\n shape: classified.shape,\n tasks,\n converted: tasks.length - refused,\n refused,\n note:\n tasks.length === 0\n ? `${dir} holds no ${from} tasks (${SHAPE_LABELS[classified.shape]})`\n : \"nothing written: conversion to world tasks is not implemented; the tree runs as it is on the benchmark runner (`gateway benchmarks validate <dir>`, `dry-run`, `push`, `run`), or author the same tasks on a world: `gateway benchmarks init ./<dir>` then `gateway worlds schema task add`\",\n };\n}\n","/**\n * CONTAINER-SUBSTRATE BENCHMARKS — harbor task trees and verifiers packages,\n * built, validated and dry-run locally the way the benchmark runner\n * (deploy/benchmark-runner) executes them.\n *\n * A harbor task (`tasks/<name>/`) is a container filesystem the agent works\n * in: `instruction.md` is what the agent is told, `environment/` (or\n * `[environment] docker_image` in `task.toml`) is the image, `tests/test.sh`\n * runs after the agent and writes `/logs/verifier/reward.json` (named numeric\n * metrics; `reward` is the headline) — the open grading ABI the runner reads\n * and nothing else. `solution/solve.sh` is the reference solution harbor's\n * `oracle` agent runs; the dry-run here uses it the same way.\n *\n * A verifiers package is a Python package whose Taskset's reward functions\n * grade the model's completion; the runner installs it (`pip install -e`) and\n * runs v1's `run_eval` in-process. There is no filesystem to grade, so its\n * dry-run is the import-and-discover pass the runner does first.\n *\n * Nothing here touches the platform: every function reads and writes the\n * directory, or runs Docker / Python on this machine.\n */\nimport { spawnSync } from \"node:child_process\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport { detectEnvKind, harborTaskDirs, verifiersPackage, type EnvKind } from \"./index\";\n\nexport const DEFAULT_IMAGE = \"python:3.11-slim\";\nexport const REWARD_JSON = \"/logs/verifier/reward.json\";\nexport const REWARD_TXT = \"/logs/verifier/reward.txt\";\n\nconst DOCKER_PROBE_MS = 8_000;\n\n// ── scaffolds ────────────────────────────────────────────────────────────────\n\nexport type HarborScaffold = {\n name: string;\n task: string;\n prompt: string;\n image: string;\n};\n\nconst HELLO_PROMPT = \"Create a file at `/app/hello.txt` whose content is exactly `Hello, Gateway!` (one line, a trailing newline, nothing else).\";\n\nfunction taskToml(image: string): string {\n return (\n 'version = \"1.0\"\\n\\n' +\n \"[metadata]\\n\" +\n 'difficulty = \"easy\"\\n' +\n 'category = \"smoke\"\\n' +\n 'tags = [\"gateway\"]\\n\\n' +\n \"[agent]\\n\" +\n \"timeout_sec = 300.0\\n\\n\" +\n \"[verifier]\\n\" +\n \"timeout_sec = 120.0\\n\\n\" +\n \"[environment]\\n\" +\n `docker_image = \"${image}\"\\n`\n );\n}\n\nconst TEST_SH =\n \"#!/bin/bash\\n\" +\n \"# The task owns its grading. The only contract the platform reads is the\\n\" +\n \"# named numeric metrics this script writes to /logs/verifier/reward.json;\\n\" +\n \"# `reward` is the headline (1.0 = pass), every other key a sub-reward.\\n\" +\n \"mkdir -p /logs/verifier\\n\\n\" +\n \"file_exists=0.0\\n\" +\n \"content_ok=0.0\\n\" +\n \"if [ -f /app/hello.txt ]; then\\n\" +\n \" file_exists=1.0\\n\" +\n \" if [ \\\"$(tr -d '\\\\n' < /app/hello.txt)\\\" = \\\"Hello, Gateway!\\\" ]; then\\n\" +\n \" content_ok=1.0\\n\" +\n \" fi\\n\" +\n \"fi\\n\" +\n \"reward=$content_ok\\n\\n\" +\n \"cat > /logs/verifier/reward.json <<EOF\\n\" +\n '{\"reward\": ${reward}, \"file_exists\": ${file_exists}, \"content_ok\": ${content_ok}}\\n' +\n \"EOF\\n\" +\n 'echo \"reward=${reward} file_exists=${file_exists} content_ok=${content_ok}\"\\n';\n\nconst SOLVE_SH =\n \"#!/bin/bash\\n\" +\n \"# The reference solution: what harbor's `oracle` agent runs, and what\\n\" +\n \"# `gateway benchmarks dry-run` runs before the tests. It must score 1.0.\\n\" +\n \"set -euo pipefail\\n\" +\n \"mkdir -p /app\\n\" +\n \"printf 'Hello, Gateway!\\\\n' > /app/hello.txt\\n\";\n\n/** Write a minimal, valid harbor tree: one task with instruction, tests, a solution and an environment. */\nexport function writeHarborScaffold(dir: string, opts: Partial<HarborScaffold> = {}): { task: string; files: string[] } {\n const name = opts.name ?? path.basename(path.resolve(dir));\n const task = opts.task ?? \"hello-world\";\n const image = opts.image ?? DEFAULT_IMAGE;\n const prompt = opts.prompt ?? HELLO_PROMPT;\n const taskDir = path.join(dir, \"tasks\", task);\n const files: Record<string, string> = {\n \"pyproject.toml\":\n \"[project]\\n\" +\n `name = \"${name}\"\\n` +\n 'version = \"0.1.0\"\\n' +\n `description = \"harbor benchmark: ${name}\"\\n` +\n 'requires-python = \">=3.10\"\\n\\n' +\n \"# A harbor tree is not a Python package: this file only names the slug and\\n\" +\n \"# the version `gateway benchmarks push` records (`--auto-bump` bumps it).\\n\",\n \"README.md\":\n `# ${name}\\n\\n` +\n \"A harbor benchmark: every task under `tasks/` is a container the agent works in, graded by its own\\n\" +\n \"`tests/test.sh` writing `/logs/verifier/reward.json`. `gateway benchmarks validate`, `dry-run`, `push`,\\n\" +\n \"`run`, `results`; skill: `gateway worlds skill benchmarks-getting-started`.\\n\",\n [`tasks/${task}/task.toml`]: taskToml(image),\n [`tasks/${task}/instruction.md`]: prompt.endsWith(\"\\n\") ? prompt : prompt + \"\\n\",\n [`tasks/${task}/environment/Dockerfile`]: `FROM ${image}\\nWORKDIR /app\\n`,\n [`tasks/${task}/tests/test.sh`]: TEST_SH,\n [`tasks/${task}/solution/solve.sh`]: SOLVE_SH,\n };\n for (const [rel, content] of Object.entries(files)) {\n const target = path.join(dir, rel);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, content);\n if (rel.endsWith(\".sh\")) fs.chmodSync(target, 0o755);\n }\n void taskDir;\n return { task, files: Object.keys(files) };\n}\n\nexport type VerifiersScaffold = { name: string; task: string };\n\n/** Write a minimal verifiers v1 Taskset package: one task, one reward function. */\nexport function writeVerifiersScaffold(dir: string, opts: Partial<VerifiersScaffold> = {}): { pkg: string; files: string[] } {\n const name = opts.name ?? path.basename(path.resolve(dir));\n const pkg = name.replace(/-/g, \"_\").replace(/[^A-Za-z0-9_]/g, \"_\");\n const task = opts.task ?? \"capital_of_france\";\n const files: Record<string, string> = {\n \"pyproject.toml\":\n \"[project]\\n\" +\n `name = \"${name}\"\\n` +\n 'version = \"0.1.0\"\\n' +\n `description = \"verifiers benchmark: ${name}\"\\n` +\n 'requires-python = \">=3.10\"\\n' +\n 'dependencies = [\"verifiers>=0.2\"]\\n\\n' +\n \"[build-system]\\n\" +\n 'requires = [\"setuptools>=68\"]\\n' +\n 'build-backend = \"setuptools.build_meta\"\\n\\n' +\n \"[tool.setuptools.packages.find]\\n\" +\n `include = [\"${pkg}*\"]\\n`,\n [`${pkg}/__init__.py`]:\n '\"\"\"A verifiers v1 Taskset: tasks are prompts, rewards grade the model\\'s completion.\\n\\n' +\n \"The benchmark runner installs this package, discovers the Taskset exported in\\n\" +\n \"__all__, and runs every task through v1's run_eval; each reward function's\\n\" +\n \"value lands as a named sub-reward, their sum as the headline reward.\\n\" +\n '\"\"\"\\n\\n' +\n \"import verifiers.v1 as vf\\n\\n\\n\" +\n `class ${pkgClass(pkg)}(vf.Taskset):\\n` +\n ' \"\"\"One task per prompt; add more Task entries to load().\"\"\"\\n\\n' +\n \" def load(self):\\n\" +\n \" return [\\n\" +\n \" vf.Task(\\n\" +\n ` id=\"${task}\",\\n` +\n ' prompt=\"What is the capital of France? Answer with the city name only.\",\\n' +\n ' answer=\"Paris\",\\n' +\n \" ),\\n\" +\n \" ]\\n\\n\" +\n \" @vf.reward(weight=1.0)\\n\" +\n \" async def exact_answer(self, task, state) -> float:\\n\" +\n \" completion = (state.completion_text() or \\\"\\\").strip().rstrip(\\\".\\\")\\n\" +\n \" return 1.0 if completion.lower() == str(task.answer).lower() else 0.0\\n\\n\\n\" +\n `__all__ = [\"${pkgClass(pkg)}\"]\\n`,\n \"README.md\":\n `# ${name}\\n\\n` +\n \"A verifiers v1 benchmark. `gateway benchmarks validate`, `dry-run` (imports the package and finds the\\n\" +\n \"Taskset), `push`, `run`, `results`; skill: `gateway worlds skill benchmarks-getting-started`.\\n\",\n };\n for (const [rel, content] of Object.entries(files)) {\n const target = path.join(dir, rel);\n fs.mkdirSync(path.dirname(target), { recursive: true });\n fs.writeFileSync(target, content);\n }\n return { pkg, files: Object.keys(files) };\n}\n\nfunction pkgClass(pkg: string): string {\n return pkg\n .split(\"_\")\n .filter(Boolean)\n .map((part) => part[0]!.toUpperCase() + part.slice(1))\n .join(\"\") + \"Taskset\";\n}\n\n// ── the minimal TOML this needs (task.toml: top-level and [section] scalars) ──\n\nexport function readTomlScalars(text: string): Record<string, Record<string, string | number | boolean>> {\n const out: Record<string, Record<string, string | number | boolean>> = { \"\": {} };\n let section = \"\";\n for (const raw of text.split(\"\\n\")) {\n const line = raw.replace(/#.*$/, \"\").trim();\n if (!line) continue;\n const head = /^\\[([^\\]]+)\\]$/.exec(line);\n if (head) {\n section = head[1]!.trim();\n out[section] ??= {};\n continue;\n }\n const kv = /^([A-Za-z0-9_.-]+)\\s*=\\s*(.+)$/.exec(line);\n if (!kv) continue;\n const value = kv[2]!.trim();\n let parsed: string | number | boolean = value;\n if (/^\".*\"$/.test(value) || /^'.*'$/.test(value)) parsed = value.slice(1, -1);\n else if (value === \"true\" || value === \"false\") parsed = value === \"true\";\n else if (/^-?\\d+(\\.\\d+)?$/.test(value)) parsed = Number(value);\n out[section]![kv[1]!] = parsed;\n }\n return out;\n}\n\n// ── validation ───────────────────────────────────────────────────────────────\n\nexport type TaskValidation = {\n id: string;\n dir: string;\n image: { ref: string | null; dockerfile: string | null };\n files: { instruction: boolean; tests: boolean; solution: boolean; environment: boolean };\n timeouts: { agent: number | null; verifier: number | null };\n problems: string[];\n warnings: string[];\n};\n\nexport type TreeValidation = {\n kind: \"harbor\" | \"verifiers\";\n dir: string;\n /** What the runner's detect_env_kind will read the tree as. */\n detectedKind: EnvKind;\n tasks: TaskValidation[];\n /** For verifiers: the package and what was found in it. */\n package?: { name: string; init: string; taskset: string | null; rewards: string[]; v1: boolean };\n problems: string[];\n warnings: string[];\n ok: boolean;\n};\n\nfunction readText(file: string): string | null {\n return fs.existsSync(file) ? fs.readFileSync(file, \"utf8\") : null;\n}\n\n/** Static check of a grader script: the reward contract it must honour. */\nexport function checkTestScript(text: string, rel: string): { problems: string[]; warnings: string[] } {\n const problems: string[] = [];\n const warnings: string[] = [];\n if (!text.trim()) problems.push(`${rel} is empty`);\n if (!text.startsWith(\"#!\")) warnings.push(`${rel} has no shebang; harbor runs it with bash`);\n if (!text.includes(REWARD_JSON) && !text.includes(REWARD_TXT))\n problems.push(`${rel} never writes ${REWARD_JSON} (or ${REWARD_TXT}); the runner reads nothing else, so every trial would be ungraded (null)`);\n else if (!/mkdir\\s+-p\\s+\\/logs\\/verifier/.test(text) && !text.includes(REWARD_TXT))\n warnings.push(`${rel} writes ${REWARD_JSON} without \\`mkdir -p /logs/verifier\\`; harbor creates the directory, a bare container does not`);\n return { problems, warnings };\n}\n\nexport function validateHarborTask(dir: string, taskDir: string): TaskValidation {\n const full = path.join(dir, taskDir);\n const id = path.basename(taskDir);\n const problems: string[] = [];\n const warnings: string[] = [];\n const toml = readText(path.join(full, \"task.toml\"));\n let ref: string | null = null;\n let agent: number | null = null;\n let verifier: number | null = null;\n if (toml === null) problems.push(`${taskDir}/task.toml missing`);\n else {\n const parsed = readTomlScalars(toml);\n if (parsed[\"\"]?.version === undefined) warnings.push(`${taskDir}/task.toml declares no \\`version\\``);\n const image = parsed.environment?.docker_image;\n ref = typeof image === \"string\" && image ? image : null;\n agent = typeof parsed.agent?.timeout_sec === \"number\" ? parsed.agent.timeout_sec : null;\n verifier = typeof parsed.verifier?.timeout_sec === \"number\" ? parsed.verifier.timeout_sec : null;\n }\n const dockerfileRel = [\"environment/Dockerfile\", \"environment/docker-compose.yaml\", \"environment/docker-compose.yml\"].find((rel) =>\n fs.existsSync(path.join(full, rel)),\n );\n const environment = fs.existsSync(path.join(full, \"environment\"));\n if (!ref && !dockerfileRel)\n problems.push(`${taskDir}: no image — set [environment] docker_image in task.toml or add environment/Dockerfile`);\n if (!environment) warnings.push(`${taskDir}/environment/ missing; harbor expects the directory (a Dockerfile, a compose file, or files to upload)`);\n const instruction = readText(path.join(full, \"instruction.md\"));\n if (instruction === null) problems.push(`${taskDir}/instruction.md missing (what the agent is told)`);\n else if (!instruction.trim()) problems.push(`${taskDir}/instruction.md is empty`);\n const tests = readText(path.join(full, \"tests\", \"test.sh\"));\n if (tests === null) problems.push(`${taskDir}/tests/test.sh missing (the grader; it must write ${REWARD_JSON})`);\n else {\n const checked = checkTestScript(tests, `${taskDir}/tests/test.sh`);\n problems.push(...checked.problems);\n warnings.push(...checked.warnings);\n }\n // `docker -v` follows host symlinks: a tests/ that points elsewhere would be\n // mounted from wherever it points, on the dry-run and on the runner alike.\n for (const sub of [\"tests\", \"solution\", \"environment\"]) {\n const linked = path.join(full, sub);\n let isLink = false;\n try {\n isLink = fs.lstatSync(linked).isSymbolicLink(); // lstat: a dangling link still counts\n } catch {\n isLink = false;\n }\n if (isLink)\n problems.push(`${taskDir}/${sub} is a symlink (docker -v follows host symlinks, so whatever it points at would be mounted); make it a real directory`);\n }\n const solution = fs.existsSync(path.join(full, \"solution\", \"solve.sh\"));\n if (!solution) warnings.push(`${taskDir}/solution/solve.sh missing: dry-run and harbor's oracle agent have no reference solution to prove the grader with (the runner does not need it)`);\n return {\n id,\n dir: taskDir,\n image: { ref, dockerfile: dockerfileRel ? `${taskDir}/${dockerfileRel}` : null },\n files: { instruction: instruction !== null, tests: tests !== null, solution, environment },\n timeouts: { agent, verifier },\n problems,\n warnings,\n };\n}\n\nexport function validateHarbor(dir: string): TreeValidation {\n const problems: string[] = [];\n const warnings: string[] = [];\n const tasks = harborTaskDirs(dir).map((taskDir) => validateHarborTask(dir, taskDir));\n if (tasks.length === 0) problems.push(`${dir} holds no harbor task (tasks/<name>/task.toml)`);\n if (!fs.existsSync(path.join(dir, \"pyproject.toml\")))\n warnings.push(\"no pyproject.toml: the slug is the directory name and the version is unrecorded (`benchmarks init --kind harbor` writes one)\");\n const detectedKind = detectEnvKind(dir);\n if (detectedKind !== \"harbor\")\n problems.push(\n `the runner would read this tree as \\`${detectedKind}\\`, not harbor: ${detectedKind === \"mock-tools\" ? \"a gateway-env.toml sits at the root (that marks a world)\" : detectedKind === \"api\" ? \"gateway-api-world.toml sits at the root (an api world)\" : \"no task.toml was found where the runner looks\"}`,\n );\n const ok = problems.length === 0 && tasks.every((t) => t.problems.length === 0);\n return { kind: \"harbor\", dir, detectedKind, tasks, problems, warnings, ok };\n}\n\nexport function validateVerifiers(dir: string): TreeValidation {\n const problems: string[] = [];\n const warnings: string[] = [];\n const pkg = verifiersPackage(dir);\n let info: TreeValidation[\"package\"];\n if (!pkg) problems.push(`${dir} is not a verifiers package (pyproject.toml plus a Python package with __init__.py)`);\n else {\n const source = fs.readFileSync(path.join(dir, pkg.init), \"utf8\");\n const taskset = /class\\s+(\\w+)\\s*\\(\\s*(?:(?:vf|v1|verifiers(?:\\.v1)?)\\.)?Taskset\\s*[,)]/.exec(source)?.[1] ?? null;\n const rewards = [...source.matchAll(/@vf\\.reward[^\\n]*\\n\\s*(?:async\\s+)?def\\s+(\\w+)/g)].map((m) => m[1]!);\n const pyproject = fs.readFileSync(path.join(dir, \"pyproject.toml\"), \"utf8\");\n const v1 = /verifiers\\s*(?:\\[[^\\]]*\\])?\\s*(?:>=|~=|==|>)\\s*(?:0\\.(?:[2-9]\\d*|[1-9]\\d+)|[1-9]\\d*)/.test(pyproject) || /verifiers\\.v1|from\\s+verifiers\\s+import\\s+v1/.test(source);\n info = { name: pkg.name, init: pkg.init, taskset, rewards, v1 };\n if (!v1) warnings.push(\"pyproject.toml pins no `verifiers>=0.2`: the runner will run it as a v0 (legacy `load_environment`) package\");\n if (v1 && !taskset) problems.push(`${pkg.init} exports no \\`class X(vf.Taskset)\\``);\n if (v1 && taskset && !source.includes(\"__all__\")) problems.push(`${pkg.init} has no __all__; the runner discovers the Taskset through it`);\n if (rewards.length === 0) warnings.push(`${pkg.init} declares no @vf.reward function by name; every trace would be ungraded (null) unless the Taskset scores elsewhere`);\n }\n const detectedKind = detectEnvKind(dir);\n if (detectedKind !== \"verifiers\" && detectedKind !== \"verifiers-v1\")\n problems.push(`the runner would read this tree as \\`${detectedKind}\\`, not a verifiers package`);\n const tasks: TaskValidation[] = [];\n const ok = problems.length === 0;\n return { kind: \"verifiers\", dir, detectedKind, tasks, package: info, problems, warnings, ok };\n}\n\n// ── the run plan and the dry-run ─────────────────────────────────────────────\n\nexport type Mount = { host: string; container: string; mode: \"ro\" | \"rw\" };\n\nexport const LOGS_PLACEHOLDER = \"<tmp>/logs\";\n\nexport type HarborPlan = {\n kind: \"harbor\";\n task: string;\n taskDir: string;\n image: { ref: string | null; dockerfile: string | null; tag: string };\n workdir: string;\n mounts: Mount[];\n env: Record<string, string>;\n steps: { name: string; command: string; note: string }[];\n /** The exact argv the dry-run spawns, in order; `<tmp>/logs` in `run` is the scratch directory created at run time. */\n commands: { build?: string[]; pull?: string[]; run: string[] };\n reward: { file: string; fallback: string };\n timeouts: { agent: number; verifier: number };\n /** How the benchmark runner runs the whole tree (deploy/benchmark-runner/engines/harbor_runner.py). */\n runner: string;\n validation: TaskValidation;\n};\n\nexport function harborRunPlan(dir: string, taskId: string | undefined, logsDir = LOGS_PLACEHOLDER): HarborPlan {\n const dirs = harborTaskDirs(dir);\n const taskDir = taskId ? dirs.find((d) => path.basename(d) === taskId) : dirs[0];\n if (!taskDir)\n throw new Error(\n taskId ? `no task ${taskId} in ${dir}; tasks: ${dirs.map((d) => path.basename(d)).join(\", \") || \"none\"}` : `${dir} holds no harbor task`,\n );\n const validation = validateHarborTask(dir, taskDir);\n const full = path.resolve(dir, taskDir);\n const slug = path.basename(path.resolve(dir)).replace(/[^a-z0-9_.-]/gi, \"-\").toLowerCase();\n const tag = `gateway-benchmarks-dryrun-${slug}-${validation.id}`.toLowerCase();\n const mounts: Mount[] = [{ host: path.join(full, \"tests\"), container: \"/tests\", mode: \"ro\" }];\n if (validation.files.solution) mounts.push({ host: path.join(full, \"solution\"), container: \"/solution\", mode: \"ro\" });\n mounts.push({ host: logsDir, container: \"/logs\", mode: \"rw\" });\n const steps: HarborPlan[\"steps\"] = [];\n if (validation.files.solution)\n steps.push({ name: \"solve\", command: \"bash /solution/solve.sh\", note: \"the reference solution stands in for the agent (harbor's `oracle` agent runs the same file)\" });\n else steps.push({ name: \"solve\", command: \"(no solution/solve.sh: the container is graded untouched, so the reward should be 0)\", note: \"add solution/solve.sh to prove the grader passes\" });\n steps.push({ name: \"verify\", command: \"bash /tests/test.sh\", note: `the task's own grader; it writes ${REWARD_JSON}` });\n const bin = dockerBin();\n const image = validation.image.dockerfile ? tag : validation.image.ref;\n const script = steps\n .filter((s) => !s.command.startsWith(\"(\"))\n .map((s) => s.command)\n .join(\" && \");\n const run = [bin, \"run\", \"--rm\", \"--network\", \"none\", \"-w\", \"/app\"];\n for (const mount of mounts) run.push(\"-v\", `${mount.host}:${mount.container}${mount.mode === \"ro\" ? \":ro\" : \"\"}`);\n run.push(image ?? \"<no image>\", \"bash\", \"-lc\", `mkdir -p /logs/verifier && ${script}`);\n const commands: HarborPlan[\"commands\"] = { run };\n if (validation.image.dockerfile) {\n const dockerfile = path.resolve(dir, validation.image.dockerfile);\n commands.build = [bin, \"build\", \"-t\", tag, \"-f\", dockerfile, path.dirname(dockerfile)];\n } else if (validation.image.ref) commands.pull = [bin, \"pull\", \"--quiet\", validation.image.ref];\n return {\n kind: \"harbor\",\n task: validation.id,\n taskDir,\n image: { ref: validation.image.ref, dockerfile: validation.image.dockerfile, tag },\n workdir: \"/app\",\n mounts,\n env: {},\n steps,\n commands,\n reward: { file: REWARD_JSON, fallback: REWARD_TXT },\n timeouts: { agent: validation.timeouts.agent ?? 300, verifier: validation.timeouts.verifier ?? 120 },\n runner: `harbor run -p ${path.join(dir, \"tasks\")} -a mini-swe-agent -m <provider/model> -e docker -o <jobs> -k <rollouts> -n <concurrency> -y -q`,\n validation,\n };\n}\n\nexport type DryRunResult = {\n executed: boolean;\n /** Why it did not execute, when it did not. */\n reason?: string;\n docker?: string;\n image?: string;\n exitCode?: number;\n reward?: number | null;\n rewards?: Record<string, number>;\n output?: string;\n commands: string[];\n};\n\nexport function dockerBin(): string {\n return process.env.GATEWAY_DOCKER || \"docker\";\n}\n\n/** The daemon's version, or null with the reason it could not be reached. */\nexport function probeDocker(): { version: string | null; reason: string } {\n const bin = dockerBin();\n const probe = spawnSync(bin, [\"version\", \"--format\", \"{{.Server.Version}}\"], { encoding: \"utf8\", timeout: DOCKER_PROBE_MS });\n if (probe.error) return { version: null, reason: (probe.error as NodeJS.ErrnoException).code === \"ENOENT\" ? `\\`${bin}\\` is not installed` : `\\`${bin}\\` failed: ${probe.error.message}` };\n if (probe.status !== 0) return { version: null, reason: `\\`${bin} version\\` exited ${probe.status}: ${(probe.stderr || probe.stdout || \"\").trim().slice(0, 200) || \"the daemon is not running\"}` };\n return { version: probe.stdout.trim(), reason: \"\" };\n}\n\nfunction tail(text: string, limit = 2000): string {\n return text.length > limit ? \"…\" + text.slice(-limit) : text;\n}\n\n/** `argv`, printed the way it was spawned. */\nexport function shellLine(argv: string[]): string {\n return argv.map((a) => (/[\\s\"'$&|;]/.test(a) ? JSON.stringify(a) : a)).join(\" \");\n}\n\n/** Run ONE harbor task the way the runner would: exactly the plan's argv — image, solution, tests, reward. */\nexport function dryRunHarbor(dir: string, plan: HarborPlan): DryRunResult {\n const docker = probeDocker();\n const commands: string[] = [];\n if (docker.version === null) return { executed: false, reason: `${docker.reason}; execution needs Docker — the plan is what would run`, commands };\n const logs = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-benchmarks-dryrun-\"));\n fs.mkdirSync(path.join(logs, \"verifier\"), { recursive: true });\n const outputs: string[] = [];\n const spawnArgv = (argv: string[], timeoutMs: number) => {\n commands.push(shellLine(argv));\n const ran = spawnSync(argv[0]!, argv.slice(1), { encoding: \"utf8\", timeout: timeoutMs });\n outputs.push(tail((ran.stdout ?? \"\") + (ran.stderr ?? \"\")));\n return ran.status ?? 1;\n };\n const image = plan.image.dockerfile ? plan.image.tag : plan.image.ref;\n if (!image) return { executed: false, reason: \"the task names no image\", commands };\n if (plan.commands.build && spawnArgv(plan.commands.build, 20 * 60_000) !== 0)\n return { executed: true, docker: docker.version, image, exitCode: 1, reward: null, output: outputs.join(\"\\n\"), commands, reason: \"the image build failed\" };\n if (plan.commands.pull && spawnArgv(plan.commands.pull, 20 * 60_000) !== 0)\n return { executed: true, docker: docker.version, image, exitCode: 1, reward: null, output: outputs.join(\"\\n\"), commands, reason: \"the image pull failed\" };\n // The one substitution: the scratch /logs directory exists only now.\n const run = plan.commands.run.map((a) => a.replace(`${LOGS_PLACEHOLDER}:/logs`, `${logs}:/logs`));\n const exitCode = spawnArgv(run, (plan.timeouts.agent + plan.timeouts.verifier) * 1000);\n const rewards = readReward(path.join(logs, \"verifier\"));\n return {\n executed: true,\n docker: docker.version,\n image,\n exitCode,\n reward: rewards === null ? null : \"reward\" in rewards ? rewards.reward! : (Object.values(rewards)[0] ?? null),\n rewards: rewards ?? undefined,\n output: outputs.join(\"\\n\"),\n commands,\n ...(rewards === null ? { reason: `${REWARD_JSON} was not written: the grader died before grading (a null score, never 0)` } : {}),\n };\n}\n\n/** The reward files as the runner's harvest reads them: reward.json first, reward.txt second, null when neither. */\nexport function readReward(verifierDir: string): Record<string, number> | null {\n const json = readText(path.join(verifierDir, \"reward.json\"));\n if (json !== null) {\n try {\n const parsed: unknown = JSON.parse(json);\n if (typeof parsed === \"number\") return { reward: parsed };\n if (parsed && typeof parsed === \"object\")\n return Object.fromEntries(Object.entries(parsed as Record<string, unknown>).filter((e): e is [string, number] => typeof e[1] === \"number\"));\n } catch {\n return null;\n }\n }\n const txt = readText(path.join(verifierDir, \"reward.txt\"));\n if (txt !== null && /^-?\\d+(\\.\\d+)?\\s*$/.test(txt)) return { reward: Number(txt.trim()) };\n return null;\n}\n\nexport const VERIFIERS_IMAGE = \"gateway-benchmarks-verifiers\";\nexport const VERIFIERS_DOCKERFILE = 'FROM python:3.11-slim\\nRUN pip install --no-cache-dir \"verifiers>=0.2\"\\n';\n\n/**\n * The runner's first pass, as a script: import the LIBRARY first, then put the\n * bundle on the path — so a `verifiers/` directory inside the tree can never\n * shadow `verifiers.v1` — then import the package and read what `__all__`\n * exports. Module-level code of the package runs: in Docker by default, on\n * this machine only behind `--here`.\n */\nexport function verifiersDiscoverScript(bundle: string, pkg: string): string {\n return [\n \"import importlib, json, sys\",\n \"out = {}\",\n \"try:\",\n \" import verifiers.v1 as vf\",\n \" out['verifiers_v1'] = True\",\n \"except Exception as e:\",\n \" out['verifiers_v1'] = False; out['verifiers_error'] = str(e)\",\n `sys.path.insert(0, ${JSON.stringify(bundle)})`,\n \"try:\",\n ` m = importlib.import_module(${JSON.stringify(pkg.replace(/-/g, \"_\"))})`,\n \" names = list(getattr(m, '__all__', []))\",\n \" out['exports'] = names\",\n \" out['taskset'] = next((n for n in names if isinstance(getattr(m, n, None), type)), None)\",\n \"except Exception as e:\",\n \" out['import_error'] = str(e)\",\n \"print(json.dumps(out))\",\n ].join(\"\\n\");\n}\n\nexport type VerifiersPlan = {\n kind: \"verifiers\";\n package: string;\n taskset: string | null;\n rewards: string[];\n steps: { name: string; command: string; note: string }[];\n image: { tag: string; dockerfile: string };\n /** The exact argv the dry-run spawns: the image build (Dockerfile on stdin), then the import with the tree read-only and no network. */\n commands: { build: string[]; run: string[] };\n /** `--here`: the same import in this machine's Python, as you. */\n here: string[];\n runner: string;\n};\n\nexport function verifiersRunPlan(dir: string, validation: TreeValidation, python: string | null = null): VerifiersPlan {\n const pkg = validation.package;\n const name = pkg?.name ?? path.basename(path.resolve(dir));\n const bin = dockerBin();\n const tree = path.resolve(dir);\n return {\n kind: \"verifiers\",\n package: name,\n taskset: pkg?.taskset ?? null,\n rewards: pkg?.rewards ?? [],\n steps: [\n { name: \"install\", command: `pip install -e ${dir}`, note: \"the runner installs the package into its Python\" },\n { name: \"discover\", command: `python -c \"import verifiers.v1; import ${name.replace(/-/g, \"_\")}; ${name.replace(/-/g, \"_\")}.__all__\"`, note: \"the Taskset exported through __all__ (verifiers.v1.loaders); the package's module-level code runs here\" },\n { name: \"eval\", command: \"verifiers.v1.cli.eval.runner.run_eval(Environment(EnvConfig(taskset, harness=null)), EvalConfig(model, rollouts))\", note: \"every task × k rollouts through the model; trace.rewards -> named sub-rewards, their sum the headline; an empty rewards dict stays null\" },\n ],\n image: { tag: VERIFIERS_IMAGE, dockerfile: VERIFIERS_DOCKERFILE },\n commands: {\n build: [bin, \"build\", \"-t\", VERIFIERS_IMAGE, \"-\"],\n run: [bin, \"run\", \"--rm\", \"--network\", \"none\", \"-v\", `${tree}:/bundle:ro`, VERIFIERS_IMAGE, \"python\", \"-c\", verifiersDiscoverScript(\"/bundle\", name)],\n },\n here: [python ?? \"python3\", \"-c\", verifiersDiscoverScript(tree, name)],\n runner: \"deploy/benchmark-runner/engines/verifiers_v1.py (in-process, no image); v0 packages: engines/verifiers_runner.py\",\n };\n}\n\nfunction readDiscover(stdout: string): Record<string, unknown> {\n try {\n return JSON.parse(stdout.trim().split(\"\\n\").pop() ?? \"{}\") as Record<string, unknown>;\n } catch {\n return {};\n }\n}\n\nfunction discoverResult(doc: Record<string, unknown>, where: string, stderr: string, commands: string[]): DryRunResult {\n if (doc.verifiers_v1 !== true)\n return {\n executed: false,\n reason: `verifiers.v1 is not importable in ${where} (${String(doc.verifiers_error ?? stderr.trim().slice(0, 200))}); \\`pip install \"verifiers>=0.2\"\\` there — the runner's image has it`,\n commands,\n output: tail(stderr),\n };\n if (doc.import_error) return { executed: true, exitCode: 1, reward: null, reason: `the package does not import: ${String(doc.import_error)}`, commands, output: tail(stderr) };\n return {\n executed: true,\n exitCode: 0,\n reward: null,\n reason: doc.taskset\n ? `Taskset ${String(doc.taskset)} discovered (exports ${(doc.exports as string[]).join(\", \")}); the rewards run over model completions in \\`benchmarks run\\``\n : `the package imports but exports no class through __all__ (${(doc.exports as string[] | undefined)?.join(\", \") || \"nothing\"})`,\n commands,\n output: tail(stderr),\n };\n}\n\n/**\n * The runner's first pass, locally. Default: inside Docker — the image built\n * from the plan's Dockerfile (network for pip), then the import with the tree\n * mounted read-only and `--network none`, so the package's module-level code\n * runs in a container, not as you. `--here`: the same import in this machine's\n * Python, which runs that code as you.\n */\nexport function dryRunVerifiers(dir: string, plan: VerifiersPlan, opts: { here?: boolean; python?: string | null }): DryRunResult {\n const commands: string[] = [];\n if (opts.here) {\n if (!opts.python) return { executed: false, reason: \"no python3 >= 3.11 found; set GATEWAY_PYTHON\", commands };\n const argv = [opts.python, ...plan.here.slice(1)];\n commands.push(shellLine(argv));\n const ran = spawnSync(argv[0]!, argv.slice(1), { encoding: \"utf8\", timeout: 60_000 });\n return discoverResult(readDiscover(ran.stdout ?? \"\"), opts.python, ran.stderr ?? \"\", commands);\n }\n const docker = probeDocker();\n if (docker.version === null)\n return {\n executed: false,\n reason: `${docker.reason}; execution needs Docker (the package's module-level code runs in a container) — the plan is what would run. \\`--here\\` runs it in this machine's Python instead, as you`,\n commands,\n };\n commands.push(`${shellLine(plan.commands.build)} # Dockerfile on stdin: ${JSON.stringify(plan.image.dockerfile)}`);\n const built = spawnSync(plan.commands.build[0]!, plan.commands.build.slice(1), { encoding: \"utf8\", timeout: 20 * 60_000, input: plan.image.dockerfile });\n if (built.status !== 0) return { executed: true, exitCode: built.status ?? 1, reward: null, reason: \"the image build failed\", commands, output: tail((built.stdout ?? \"\") + (built.stderr ?? \"\")) };\n commands.push(shellLine(plan.commands.run));\n const ran = spawnSync(plan.commands.run[0]!, plan.commands.run.slice(1), { encoding: \"utf8\", timeout: 5 * 60_000 });\n return { ...discoverResult(readDiscover(ran.stdout ?? \"\"), `${plan.image.tag} (Docker ${docker.version})`, ran.stderr ?? \"\", commands), docker: docker.version, image: plan.image.tag };\n}\n","import * as fs from \"node:fs\";\n\nimport { api, printJson, type Credentials } from \"../config\";\nimport { arg, CliError, type CommandContext, type CommandGroup } from \"../router\";\nimport { credentials, HOST_FLAG, query, sleep } from \"./shared\";\n\nconst ENV = \"/api/public/environments\";\nconst cid = (id: string) => `${ENV}/${encodeURIComponent(id)}`;\n\ntype EnvRun = {\n status: string;\n avgReward?: number | null;\n settled: boolean;\n rollouts?: { task?: string; reward?: unknown; verifiers?: unknown }[];\n};\n\n/** Accept a container id OR a slug everywhere an environment is named. */\nexport async function resolveEnvironmentId(creds: Credentials, ref: string): Promise<string> {\n const listing = await api<{ environments?: { id: string; slug?: string }[] }>(\n creds,\n \"GET\",\n `${ENV}${query({ slug: ref, limit: 5 })}`,\n );\n return listing.environments?.find((env) => env.slug === ref)?.id ?? ref;\n}\n\nasync function getRun(creds: Credentials, runId: string, waitSeconds: number): Promise<EnvRun> {\n const wait = Math.max(0, Math.min(waitSeconds, 50));\n return api<EnvRun>(creds, \"GET\", `${ENV}/runs/${encodeURIComponent(runId)}${wait ? `?waitSeconds=${wait}` : \"\"}`);\n}\n\nexport type EnvironmentRunOptions = {\n models: string[];\n versionId?: string;\n numExamples?: number;\n rollouts?: number;\n /** Block until every run settles and print verdicts (the default). */\n wait: boolean;\n waitTimeoutSeconds: number;\n};\n\n/**\n * Dispatch hosted rollouts of an environment (one runner job per model) and,\n * when `wait`, poll each to its verdict. Shared by `gateway environment run`\n * and `gateway benchmarks run`: a benchmark on a world is run the same way.\n * Exit 0 when every run completed, 1 otherwise.\n */\nexport async function runEnvironment(\n creds: Credentials,\n ref: string,\n ctx: CommandContext,\n opts: EnvironmentRunOptions,\n): Promise<number> {\n const id = await resolveEnvironmentId(creds, ref);\n const dispatch = await api<{ runs: { model: string; runId?: string; ok: boolean; error?: string }[] }>(\n creds,\n \"POST\",\n `${cid(id)}/run`,\n {\n models: opts.models,\n ...(opts.versionId ? { versionId: opts.versionId } : {}),\n ...(opts.numExamples !== undefined ? { numExamples: opts.numExamples } : {}),\n ...(opts.rollouts !== undefined ? { rolloutsPerExample: opts.rollouts } : {}),\n },\n );\n printJson(ctx, dispatch);\n const dispatched = dispatch.runs.filter((r) => r.ok && r.runId);\n for (const r of dispatch.runs) if (!r.ok) ctx.stderr(`# ${r.model}: ${r.error}`);\n if (!opts.wait || dispatched.length === 0) return dispatched.length ? 0 : 1;\n\n const waitTimeout = opts.waitTimeoutSeconds;\n const deadline = Date.now() + waitTimeout * 1000;\n let failed = false;\n for (const r of dispatched) {\n for (;;) {\n const budget = Math.floor(Math.min(45, Math.max(0, (deadline - Date.now()) / 1000)));\n const verdict = await getRun(creds, r.runId!, budget);\n if (verdict.settled) {\n ctx.stdout(`${r.model}: ${verdict.status} avgReward=${verdict.avgReward ?? null}`);\n for (const rollout of verdict.rollouts ?? [])\n ctx.stdout(` ${rollout.task}: ${rollout.reward} ${JSON.stringify(rollout.verifiers ?? {})}`);\n failed = failed || ![\"COMPLETED\", \"SUCCEEDED\"].includes(verdict.status.toUpperCase());\n break;\n }\n if (Date.now() >= deadline) {\n ctx.stderr(`${r.model}: still running after ${waitTimeout}s (runId=${r.runId})`);\n failed = true;\n break;\n }\n if (budget === 0) await sleep(1000);\n }\n }\n return failed ? 1 : 0;\n}\n\n/** `gateway environment …` — the environments public API. */\nexport function registerEnvironmentCommands(root: CommandGroup): void {\n const environment = root.group(\n \"environment\",\n \"Environment hub — inspect environments, task sets, rollouts, and the Environment Agent.\",\n );\n const containerId = { name: \"container_id\", help: \"Environment (container) id.\" };\n\n environment.command({\n name: \"list\",\n help: \"List the project's environments (id, slug, latest version, task-set link).\",\n flags: [\n { name: \"slug\", help: \"Filter to one environment slug.\" },\n { name: \"limit\", short: \"n\", help: \"Max environments to list.\", default: \"50\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n printJson(\n ctx,\n await api(credentials(args), \"GET\", `${ENV}${query({ limit: arg.int(args, \"limit\") ?? 50, slug: arg.str(args, \"slug\") })}`),\n );\n },\n });\n\n environment.command({\n name: \"get\",\n help: \"Show one environment with its version history and rollout count.\",\n positionals: [containerId],\n flags: [HOST_FLAG],\n run: async (args, ctx) => printJson(ctx, await api(credentials(args), \"GET\", cid(args.positionals[0]!))),\n });\n\n environment.command({\n name: \"tasks\",\n help: \"Show the environment's linked task set and its tasks.\",\n positionals: [containerId],\n flags: [HOST_FLAG],\n run: async (args, ctx) => printJson(ctx, await api(credentials(args), \"GET\", `${cid(args.positionals[0]!)}/task-set`)),\n });\n\n environment.command({\n name: \"run\",\n help: \"Dispatch hosted rollouts — one runner job per model — and (by default) wait for the verdicts.\",\n positionals: [{ name: \"environment\", help: \"Environment slug or container id.\" }],\n flags: [\n {\n name: \"model\",\n short: \"m\",\n help: \"Model to run, repeatable, provider-prefixed: anthropic/..., openrouter/vendor/model, gateway/vendor/model, bedrock/...\",\n repeat: true,\n },\n { name: \"version-id\", help: \"Pin a READY version (default: newest).\" },\n { name: \"num-examples\", short: \"n\", help: \"Cap scenarios (default: all).\" },\n { name: \"rollouts\", short: \"k\", help: \"Rollouts per scenario (default 1).\" },\n { name: \"no-wait\", help: \"Return after dispatch instead of blocking until every run settles.\", boolean: true },\n { name: \"wait\", help: \"Block until every run settles and print verdicts (the default).\", boolean: true },\n { name: \"wait-timeout\", help: \"Seconds to wait before giving up (with --wait).\", default: \"1200\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const models = arg.list(args, \"model\");\n if (models.length === 0) throw new CliError(\"environment run needs at least one --model\");\n return runEnvironment(credentials(args), args.positionals[0]!, ctx, {\n models,\n versionId: arg.str(args, \"version-id\"),\n numExamples: arg.int(args, \"num-examples\"),\n rollouts: arg.int(args, \"rollouts\"),\n wait: !arg.bool(args, \"no-wait\"),\n waitTimeoutSeconds: arg.int(args, \"wait-timeout\") ?? 1200,\n });\n },\n });\n\n environment.command({\n name: \"run-status\",\n help: \"One run's verdict: status, avgReward, settled, per-task rollouts.\",\n positionals: [{ name: \"run_id\", help: \"Run id from `environment run` / dispatch.\" }],\n flags: [{ name: \"wait\", short: \"w\", help: \"Block server-side up to N seconds (max 50) for it to settle.\", default: \"0\" }, HOST_FLAG],\n notes: \"`settled: false` after a wait means keep polling — it is not failure.\",\n run: async (args, ctx) => printJson(ctx, await getRun(credentials(args), args.positionals[0]!, arg.int(args, \"wait\") ?? 0)),\n });\n\n environment.command({\n name: \"link-task-set\",\n help: \"Create/fill a scenario set and attach it — idempotent: reuses the linked set, skips existing names.\",\n positionals: [{ name: \"environment\", help: \"Environment slug or container id.\" }],\n flags: [\n { name: \"tasks\", help: \"tasks.jsonl to fill the set from (rows: id, prompt, metadata, worlds).\" },\n { name: \"name\", help: \"Task-set name (default: '<slug> scenarios').\" },\n { name: \"description\", help: \"Task-set description.\" },\n { name: \"fresh\", help: \"Always create a new set instead of reusing the linked one.\", boolean: true },\n { name: \"detach\", help: \"Unlink the environment's task set and exit.\", boolean: true },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const creds = credentials(args);\n const ref = args.positionals[0]!;\n const id = await resolveEnvironmentId(creds, ref);\n if (arg.bool(args, \"detach\")) {\n printJson(ctx, await api(creds, \"POST\", `${cid(id)}/task-set`, { taskSetDatasetId: null }));\n return;\n }\n let datasetId: string | undefined;\n const existing = new Set<string>();\n if (!arg.bool(args, \"fresh\")) {\n try {\n const current = await api<{ datasetId: string; tasks?: { name: string }[] }>(creds, \"GET\", `${cid(id)}/task-set`);\n datasetId = current.datasetId;\n for (const t of current.tasks ?? []) existing.add(t.name);\n ctx.stderr(`# reusing linked task set ${datasetId}`);\n } catch {\n datasetId = undefined;\n }\n }\n if (!datasetId) {\n const setName = arg.str(args, \"name\") ?? `${ref} scenarios`;\n const description = arg.str(args, \"description\");\n const created = await api<{ datasetId: string }>(creds, \"POST\", \"/api/public/task-sets\", {\n name: setName,\n ...(description ? { description } : {}),\n });\n datasetId = created.datasetId;\n ctx.stderr(`# created task set ${datasetId} (${setName})`);\n }\n const tasks = arg.str(args, \"tasks\");\n if (tasks) {\n for (const line of fs.readFileSync(tasks, \"utf8\").split(/\\r?\\n/)) {\n if (!line.trim()) continue;\n const row = JSON.parse(line) as Record<string, unknown>;\n const taskName = String(row.id ?? row.task ?? \"\");\n if (!taskName || existing.has(taskName)) continue;\n const metadata: Record<string, unknown> = { ...((row.metadata as Record<string, unknown>) ?? {}) };\n if (row.worlds !== undefined) metadata.worlds = row.worlds;\n await api(creds, \"POST\", `/api/public/task-sets/${encodeURIComponent(datasetId)}/tasks`, {\n name: taskName,\n prompt: String(row.prompt ?? \"\"),\n ...(Object.keys(metadata).length ? { metadata } : {}),\n });\n ctx.stderr(`# task ${taskName} created`);\n }\n }\n printJson(ctx, await api(creds, \"POST\", `${cid(id)}/task-set`, { taskSetDatasetId: datasetId }));\n },\n });\n\n environment.command({\n name: \"performance\",\n help: \"Show per-task performance across rollouts (nulls kept as their own category).\",\n positionals: [containerId],\n flags: [HOST_FLAG],\n run: async (args, ctx) => printJson(ctx, await api(credentials(args), \"GET\", `${cid(args.positionals[0]!)}/performance`)),\n });\n\n environment.command({\n name: \"rollouts\",\n help: \"List the environment's rollouts (evaluations), newest first.\",\n positionals: [containerId],\n flags: [HOST_FLAG],\n run: async (args, ctx) => printJson(ctx, await api(credentials(args), \"GET\", `${cid(args.positionals[0]!)}/rollouts`)),\n });\n\n environment.command({\n name: \"samples\",\n help: \"Show the scored samples of one rollout (reward/score/correct + sub-rewards).\",\n positionals: [containerId, { name: \"evaluation_id\", help: \"Rollout (evaluation) id.\" }],\n flags: [{ name: \"limit\", short: \"n\", help: \"Max samples to return.\", default: \"200\" }, HOST_FLAG],\n run: async (args, ctx) => {\n const [container, evaluation] = args.positionals;\n printJson(\n ctx,\n await api(\n credentials(args),\n \"GET\",\n `${cid(container!)}/rollouts/${encodeURIComponent(evaluation!)}/samples${query({ limit: arg.int(args, \"limit\") ?? 200 })}`,\n ),\n );\n },\n });\n\n environment.command({\n name: \"create-task\",\n help: \"Create a task in a task set (a kind='tasks' dataset item). Requires a secret key.\",\n positionals: [{ name: \"dataset_id\", help: \"Task set dataset id (kind='tasks').\" }],\n flags: [\n { name: \"name\", help: \"Task name.\" },\n { name: \"prompt\", help: \"Task prompt.\" },\n { name: \"expected-output\", help: \"Optional expected output.\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const name = arg.str(args, \"name\");\n const prompt = arg.str(args, \"prompt\");\n if (!name || !prompt) throw new CliError(\"environment create-task needs --name and --prompt\");\n const expected = arg.str(args, \"expected-output\");\n printJson(\n ctx,\n await api(credentials(args), \"POST\", `/api/public/task-sets/${encodeURIComponent(args.positionals[0]!)}/tasks`, {\n name,\n prompt,\n ...(expected !== undefined ? { expectedOutput: expected } : {}),\n }),\n );\n },\n });\n\n environment.command({\n name: \"agent-status\",\n help: \"Show the project's Environment Agent config and recent runs.\",\n flags: [HOST_FLAG],\n run: async (args, ctx) => printJson(ctx, await api(credentials(args), \"GET\", \"/api/public/environment-agent\")),\n });\n\n environment.command({\n name: \"agent-trigger\",\n help: \"Enqueue a manual Environment Agent run. Requires a saved config and a secret key.\",\n flags: [HOST_FLAG],\n run: async (args, ctx) => printJson(ctx, await api(credentials(args), \"POST\", \"/api/public/environment-agent/trigger\", {})),\n });\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { api, printJson, type Credentials } from \"../config\";\nimport {\n arg,\n CliError,\n type CommandContext,\n type CommandGroup,\n type Parsed,\n} from \"../router\";\nimport { describeWorld } from \"../../worlds/describe\";\nimport {\n migrateProjectWorlds,\n migrateWorld,\n type WorldMigrationReport,\n} from \"../../worlds/migrate\";\nimport { walk } from \"./connector\";\nimport { parseRows } from \"./rows\";\nimport { credentials, HOST_FLAG, printDeprecations, worldsOptions } from \"./shared\";\n\nexport const WORLDS = \"/api/public/worlds\";\n\ntype FileInput = { path: string; content: string; encoding?: \"base64\" };\n\n/** Every file under a directory, text as UTF-8 and anything else base64, in the route's shape. */\nexport function collectFiles(directory: string): FileInput[] {\n if (!fs.existsSync(directory) || !fs.statSync(directory).isDirectory())\n throw new CliError(`${directory}: not a directory`, 1);\n return walk(directory).map((relative) => {\n const bytes = fs.readFileSync(path.join(directory, relative));\n const text = bytes.toString(\"utf8\");\n return Buffer.from(text, \"utf8\").equals(bytes) && !text.includes(\"\\uFFFD\")\n ? { path: relative, content: text }\n : {\n path: relative,\n content: bytes.toString(\"base64\"),\n encoding: \"base64\" as const,\n };\n });\n}\n\nconst isDirectory = (p: string) => fs.existsSync(p) && fs.statSync(p).isDirectory();\n\n/**\n * `gateway worlds describe` on a directory: the schema runtime's `describe`\n * (fields stamped with their `[redact]` policy, the connection's `redact`\n * table) plus its `counts`, merged as `rowCount` per entity. The runtime\n * modules load lazily so a slug-only call never touches them.\n */\nasync function describeLocalDirectory(dir: string, hostFlag: string | undefined): Promise<Record<string, unknown>> {\n const { describeLocalWorld, withRowCounts } = await import(\"../runtime/schema\");\n const { showLocalWorldData } = await import(\"../runtime/data\");\n const { credentialsForRuntime } = await import(\"../runtime/local\");\n const creds = credentialsForRuntime(hostFlag);\n const description = await describeLocalWorld(dir, creds);\n const counts = await showLocalWorldData(dir, undefined, creds);\n return withRowCounts(description, counts.entity_counts ?? {});\n}\n\n/** A world path names a template slug, `workspace:<slug>`, or a directory holding a tree. */\nfunction source(from: string): Record<string, unknown> {\n if (fs.existsSync(from) && fs.statSync(from).isDirectory())\n return { files: collectFiles(from) };\n if (from.includes(\"/\") || from.includes(\".\"))\n throw new CliError(\n `${from}: neither a directory nor a template slug (a shipped template, or workspace:<slug>)`,\n 1,\n );\n return { connector: from };\n}\n\nexport type CreateWorldRequest = {\n slug: string;\n name?: string;\n description?: string;\n from: Record<string, unknown>;\n overlay?: { files: FileInput[] };\n data?: { rows: Record<string, Record<string, unknown>[]> };\n message?: string;\n /** schema (default): the tree as it is; api-bundle: packaged (deprecated). */\n layout?: \"schema\" | \"api-bundle\";\n};\n\nexport type CreatedWorld = {\n slug: string;\n name: string;\n containerId: string;\n /** The platform's engine kind: `mock-tools` for a schema tree, `api` for\n * an api bundle. The summary prints the world shape instead. */\n kind: string;\n version: { id: string; contentHash: string; semanticVersion: string | null };\n source: {\n connector: string;\n packageVersion: string;\n domainVersion: string;\n } | null;\n entityCounts: Record<string, number>;\n tools: string[];\n url: string;\n /** Empty for a schema world; the api-bundle notice under --layout api-bundle. */\n deprecations?: { code: string; message: string; replacement: string }[];\n};\n\nfunction requestFrom(args: Parsed, slug: string): CreateWorldRequest {\n const from = arg.str(args, \"from\");\n if (!from)\n throw new CliError(\n \"worlds create needs --from <template|workspace:slug|directory>\",\n );\n const overlay = arg.str(args, \"overlay\");\n const rows = arg.list(args, \"rows\");\n const body: CreateWorldRequest = { slug, from: source(from) };\n const name = arg.str(args, \"name\");\n if (name) body.name = name;\n const description = arg.str(args, \"description\");\n if (description) body.description = description;\n if (overlay) body.overlay = { files: collectFiles(overlay) };\n if (rows.length)\n body.data = { rows: parseRows(rows, arg.str(args, \"entity\")) };\n const message = arg.str(args, \"message\");\n if (message) body.message = message;\n const layout = arg.str(args, \"layout\");\n if (layout) {\n if (layout !== \"schema\" && layout !== \"api-bundle\")\n throw new CliError(`--layout is schema or api-bundle (got ${layout})`, 1);\n body.layout = layout;\n }\n return body;\n}\n\n/** The platform stores a schema world under its runtime engine's kind; the CLI\n * names the shape the author built. */\nexport function worldShape(kind: string): string {\n if (kind === \"mock-tools\") return \"schema\";\n if (kind === \"api\") return \"api-bundle\";\n return kind;\n}\n\nfunction summary(world: CreatedWorld): string {\n const counts = Object.entries(world.entityCounts)\n .filter(([, n]) => n > 0)\n .map(([entity, n]) => `${entity}=${n}`)\n .join(\" \");\n const from = world.source\n ? ` from ${world.source.connector}@${world.source.packageVersion}`\n : \"\";\n return `created ${world.slug} (${worldShape(world.kind)})${from} ${world.version.contentHash.slice(0, 12)}${counts ? ` [${counts}]` : \"\"} ${world.url}`;\n}\n\n/** One line of `--batch`: the request body as the route takes it, or `{slug, from}` shorthand with a string `from`. */\nfunction batchLine(line: string, index: number): CreateWorldRequest {\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n throw new CliError(`batch line ${index + 1}: not JSON`, 1);\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed))\n throw new CliError(`batch line ${index + 1}: expected an object`, 1);\n const record = parsed as Record<string, unknown>;\n if (typeof record.slug !== \"string\")\n throw new CliError(`batch line ${index + 1}: needs a \"slug\"`, 1);\n if (typeof record.from === \"string\")\n return { ...record, from: source(record.from) } as CreateWorldRequest;\n if (typeof record.from !== \"object\" || record.from === null)\n throw new CliError(\n `batch line ${index + 1}: needs \"from\" (a template slug, or {connector} / {files})`,\n 1,\n );\n return record as CreateWorldRequest;\n}\n\nasync function createOne(\n creds: Credentials,\n body: CreateWorldRequest,\n): Promise<CreatedWorld> {\n return api<CreatedWorld>(creds, \"POST\", WORLDS, body, { timeoutMs: 600_000 });\n}\n\nasync function runBatch(\n file: string,\n args: Parsed,\n ctx: CommandContext,\n): Promise<number> {\n const text =\n file === \"-\" ? fs.readFileSync(0, \"utf8\") : fs.readFileSync(file, \"utf8\");\n const requests = text\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter(Boolean)\n .map(batchLine);\n if (requests.length === 0)\n throw new CliError(\"batch file holds no worlds\", 1);\n const creds = credentials(args);\n let failed = 0;\n for (const body of requests) {\n try {\n const world = await createOne(creds, body);\n printDeprecations(ctx, world.deprecations);\n ctx.stdout(\n JSON.stringify({\n slug: world.slug,\n status: \"created\",\n containerId: world.containerId,\n version: world.version,\n url: world.url,\n }),\n );\n } catch (error) {\n failed += 1;\n const message = error instanceof Error ? error.message : String(error);\n ctx.stdout(\n JSON.stringify({ slug: body.slug, status: \"failed\", error: message }),\n );\n }\n }\n ctx.stderr(`# ${requests.length - failed}/${requests.length} created`);\n return failed === 0 ? 0 : 2;\n}\n\n/** `gateway worlds create`: a world on the platform from a template, a workspace connector or a tree (twin: MCP `create_world`). */\nexport function registerWorldCommands(root: CommandGroup): void {\n const worlds = root.group(\"worlds\", \"Build, seed, serve and run worlds.\");\n\n worlds.command({\n name: \"list\",\n help: \"List the project's worlds (id, slug, latest version, task-set link).\",\n flags: [\n { name: \"slug\", help: \"Filter to one world slug.\" },\n { name: \"limit\", short: \"n\", help: \"Max worlds to list.\", default: \"50\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const q = new URLSearchParams({\n limit: String(arg.int(args, \"limit\") ?? 50),\n });\n const slug = arg.str(args, \"slug\");\n if (slug) q.set(\"slug\", slug);\n printJson(\n ctx,\n await api(credentials(args), \"GET\", `/api/public/environments?${q}`),\n );\n },\n });\n\n worlds.command({\n name: \"describe\",\n help: \"What a world holds and how each field is stored: entities, keys, relationships, row counts, the [redact] policy per field, tools.\",\n positionals: [\n { name: \"world\", help: \"World directory, or a platform world slug.\" },\n ],\n flags: [\n { name: \"json\", help: \"Print the description document as JSON.\", boolean: true },\n HOST_FLAG,\n ],\n notes:\n \"Every field says how the store holds it: no tag means the plaintext as given, [hash] the slug-salted\\n\" +\n \"sha256 (`storedForms` in @withgateway/sdk/worlds computes it), [preserve] the shape-keeping digest,\\n\" +\n \"[round:N] fewer decimals, [drop] not on disk at all. A directory is described by the schema runtime\\n\" +\n \"and counted from its data; a slug by GET /api/public/worlds/{slug} (its head version; no @ref).\",\n run: async (args, ctx) => {\n const world = args.positionals[0]!;\n const description = isDirectory(world)\n ? await describeLocalDirectory(path.resolve(world), arg.str(args, \"host\"))\n : await describeWorld(world, worldsOptions(credentials(args)));\n if (arg.bool(args, \"json\")) printJson(ctx, description);\n else {\n const { renderDescription } = await import(\"../runtime/schema\");\n ctx.stdout(renderDescription(description as Record<string, unknown>));\n }\n },\n });\n\n worlds.command({\n name: \"create\",\n help: \"Create a world in the project from a connector template, a workspace connector or a directory.\",\n positionals: [\n {\n name: \"slug\",\n help: \"URL-safe slug, unique in the project (omit with --batch).\",\n optional: true,\n },\n ],\n flags: [\n {\n name: \"from\",\n help: \"Shipped template (slack, github, …), workspace:<slug>, or a world directory.\",\n },\n {\n name: \"overlay\",\n help: \"Directory of files laid over the source before the tree is compiled.\",\n },\n {\n name: \"rows\",\n help: \"Rows file seeded into the first version ({entity: [rows]} JSON or JSONL); repeatable.\",\n repeat: true,\n },\n { name: \"entity\", help: \"The entity bare-row files hold.\" },\n { name: \"name\", help: \"Display name (default: the slug).\" },\n { name: \"description\", help: \"One-line description.\" },\n {\n name: \"message\",\n short: \"m\",\n help: \"Change reason recorded on the first version.\",\n },\n {\n name: \"batch\",\n help: \"JSONL file (or -) of {slug, from, overlay?, data?, name?, layout?} lines; one result line each.\",\n },\n {\n name: \"layout\",\n help: \"How the world is stored: schema (default, the tree as it is) or api-bundle (packaged; deprecated).\",\n },\n { name: \"json\", help: \"Print the created world as JSON.\", boolean: true },\n HOST_FLAG,\n ],\n notes:\n \"The same request as POST /api/public/worlds and the MCP tool create_world. A shipped template or\\n\" +\n \"workspace connector is pinned on the world; an overlay or a directory is compiled by the schema\\n\" +\n \"runtime (lock/runtime/db regenerated) and refused, with the path, when the contract does not hold.\\n\" +\n \"The world is stored as its schema tree, the supported shape: one session serves its tools and, when\\n\" +\n \"the tree carries connector.toml, its HTTP routes. --layout api-bundle packages it as a\\n\" +\n \"gateway-api-world.toml bundle instead (deprecated; the notice prints on stderr). A legacy tools\\n\" +\n \"bundle (db/schema.sql), a harbor tree or a verifiers package is refused: world_kind_retired.\\n\" +\n \"The first version is READY and attributed to the key; the world is not owned by a person.\\n\" +\n \"Exit 0 created, 2 when any batch line failed, 1 on error.\",\n run: async (args, ctx) => {\n const batch = arg.str(args, \"batch\");\n if (batch) {\n if (args.positionals.length)\n throw new CliError(\n \"--batch takes the slugs from the file; drop the positional\",\n );\n return runBatch(batch, args, ctx);\n }\n const slug = args.positionals[0];\n if (!slug) throw new CliError(\"worlds create needs a slug (or --batch)\");\n const body = requestFrom(args, slug);\n const world = await createOne(credentials(args), body);\n printDeprecations(ctx, world.deprecations);\n if (arg.bool(args, \"json\")) printJson(ctx, world);\n else ctx.stdout(summary(world));\n return 0;\n },\n });\n\n worlds.command({\n name: \"migrate\",\n help: \"Convert a stored world into a schema world; dry run unless --apply.\",\n positionals: [\n {\n name: \"slug\",\n help: \"The world to migrate (omit with --all).\",\n optional: true,\n },\n ],\n flags: [\n {\n name: \"all\",\n help: \"Every connector world in the project (the Connectors page's worlds).\",\n boolean: true,\n },\n {\n name: \"dry-run\",\n help: \"Report the plan and change nothing (the default).\",\n boolean: true,\n },\n {\n name: \"apply\",\n help: \"Commit the migrated tree as the next version (\\\"Migrated to a schema world\\\").\",\n boolean: true,\n },\n {\n name: \"force\",\n help: \"Migrate a world that was not created from a connector template (hand-built worlds are refused otherwise).\",\n boolean: true,\n },\n { name: \"json\", help: \"Print the report(s) as JSON.\", boolean: true },\n HOST_FLAG,\n ],\n notes:\n \"Schema worlds are the supported shape. An api bundle (gateway-api-world.toml over server/world/) is\\n\" +\n \"restored to the schema tree it was packaged from; the bundle's own scenarios are carried, its derived\\n\" +\n \"files dropped. A legacy tools world (gateway-env.toml + db/schema.sql) has no contract to derive and is\\n\" +\n \"refused with the authoring steps; a harbor or verifiers package likewise. The targets are the\\n\" +\n \"platform's connector worlds (containers created from a template, the ones the Connectors page lists);\\n\" +\n \"--force migrates another. Twins: POST /api/public/worlds/{slug}/migrate, MCP migrate_world.\\n\" +\n \"Exit 0 when every report has a plan, 2 when any was refused (or on a usage error), 1 on a platform error.\",\n run: async (args, ctx) => {\n const slug = args.positionals[0];\n const all = arg.bool(args, \"all\");\n if (!slug && !all)\n throw new CliError(\"worlds migrate needs a slug (or --all)\");\n if (slug && all)\n throw new CliError(\"--all takes every connector world; drop the slug\");\n if (arg.bool(args, \"dry-run\") && arg.bool(args, \"apply\"))\n throw new CliError(\"--dry-run and --apply are opposites; pick one\");\n const apply = arg.bool(args, \"apply\");\n const options = worldsOptions(credentials(args));\n const reports: WorldMigrationReport[] = slug\n ? [await migrateWorld(slug, { apply, force: arg.bool(args, \"force\") || undefined }, options)]\n : (await migrateProjectWorlds({ apply }, options)).worlds;\n if (arg.bool(args, \"json\")) printJson(ctx, slug ? reports[0] : { worlds: reports, applied: apply });\n else for (const report of reports) ctx.stdout(migrationLine(report, apply));\n if (!apply && reports.some((r) => !r.refusal && !r.unchanged))\n ctx.stderr(\"dry run; add --apply to commit\");\n return reports.some((r) => r.refusal) ? 2 : 0;\n },\n });\n}\n\nfunction migrationLine(report: WorldMigrationReport, apply: boolean): string {\n if (report.refusal)\n return `${report.slug}: ${report.shape} -> refused (${report.refusal.code}): ${report.refusal.message}`;\n if (report.unchanged) return `${report.slug}: schema world already; nothing to migrate`;\n const head = `${report.slug}: ${report.shape} -> schema (${report.files} files)`;\n if (report.applied && report.version)\n return `${head} migrated as ${report.version.contentHash.slice(0, 12)}`;\n const plan = report.actions.map((a) => `\\n - ${a}`).join(\"\");\n return apply ? `${head} unchanged (identical tree already the head)${plan}` : `${head} would:${plan}`;\n}\n","import * as fs from \"node:fs\";\n\nimport { CliError } from \"../router\";\n\n/** `{entity: [row, …]}` — the shape every rows file resolves to. */\nexport type Rows = Record<string, Record<string, unknown>[]>;\n\n/**\n * Read rows from files into `{entity: [row, …]}` — a port of the Python\n * `gatewaysdk.environment.schema.data.parse_rows`, so both CLIs accept the\n * same files and refuse the same ones with the same words.\n *\n * Each file is one of: a JSON object `{\"<entity>\": [row, …]}`; JSONL where\n * every line is `{\"entity\": \"<name>\", \"row\": {…}}`; or — only with `entity` —\n * a JSON array or JSONL of bare rows. Several files merge in order. A file\n * that fits none of these is refused, naming the file.\n */\nexport function parseRows(paths: string[], entity?: string): Rows {\n const rows: Rows = {};\n for (const path of paths) {\n let text: string;\n try {\n text = fs.readFileSync(path, \"utf8\");\n } catch {\n throw refuse(`Cannot read ${path} as UTF-8 text`);\n }\n for (const [name, listed] of Object.entries(rowsIn(text, path, entity))) {\n (rows[name] ??= []).push(...listed);\n }\n }\n return rows;\n}\n\nfunction refuse(message: string): CliError {\n return new CliError(message, 1);\n}\n\nfunction rowsIn(text: string, path: string, entity: string | undefined): Rows {\n const stripped = text.trim();\n if (!stripped) return {};\n let document: unknown;\n try {\n document = JSON.parse(stripped);\n } catch {\n return jsonlRows(stripped, path, entity);\n }\n if (isObject(document)) {\n if (entity !== undefined) {\n const keys = Object.keys(document);\n if (keys.length === 1 && keys[0] === entity && Array.isArray(document[entity])) {\n return {\n [entity]: (document[entity] as unknown[]).map((row, i) =>\n rowObject(row, `${path}:${entity}[${i}]`),\n ),\n };\n }\n // One bare row on one line is a JSON object too; --entity says that is what it is.\n return jsonlRows(stripped, path, entity);\n }\n const out: Rows = {};\n for (const [name, listed] of Object.entries(document)) {\n if (!Array.isArray(listed))\n throw refuse(`${path}: ${name} must map to an array of rows (JSONL lines are {\"entity\", \"row\"})`);\n out[name] = listed.map((row, index) => rowObject(row, `${path}:${name}[${index}]`));\n }\n return out;\n }\n if (Array.isArray(document)) {\n if (entity === undefined)\n throw refuse(`${path} is a bare array; say which entity it holds with --entity`);\n return { [entity]: document.map((row, index) => rowObject(row, `${path}[${index}]`)) };\n }\n throw refuse(`${path} is neither a JSON object of entity -> rows nor an array of rows`);\n}\n\nfunction jsonlRows(text: string, path: string, entity: string | undefined): Rows {\n const out: Rows = {};\n const lines = text.split(/\\r?\\n/);\n for (let index = 0; index < lines.length; index++) {\n const line = lines[index]!;\n if (!line.trim()) continue;\n const number = index + 1;\n let item: unknown;\n try {\n item = JSON.parse(line);\n } catch {\n throw refuse(`${path}:${number} is not JSON`);\n }\n const where = `${path}:${number}`;\n if (entity !== undefined) {\n (out[entity] ??= []).push(rowObject(item, where));\n continue;\n }\n if (\n !isObject(item) ||\n Object.keys(item).length !== 2 ||\n !(\"entity\" in item) ||\n !(\"row\" in item) ||\n typeof item.entity !== \"string\"\n )\n throw refuse(`${where}: expected {\"entity\": name, \"row\": {…}} (or pass --entity for bare rows)`);\n (out[item.entity] ??= []).push(rowObject(item.row, where));\n }\n return out;\n}\n\nfunction rowObject(row: unknown, where: string): Record<string, unknown> {\n if (!isObject(row)) throw refuse(`${where}: a row must be a JSON object`);\n return row;\n}\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/** `append` (upsert by primary key) or `replace` (the named entities wholesale). */\nexport type RowsMode = \"append\" | \"replace\";\n\nexport function rowsMode(value: string | undefined): RowsMode {\n const mode = value ?? \"append\";\n if (mode !== \"append\" && mode !== \"replace\") throw new CliError(\"--mode must be append or replace\");\n return mode;\n}\n\nexport type RowsRedact = \"off\" | \"apply\" | \"refuse\";\n\n/** `--redact off|apply|refuse` (default off): redaction on the way in, per the world's [redact] policy. */\nexport function rowsRedact(value: string | undefined): RowsRedact {\n const redact = value ?? \"off\";\n if (redact !== \"off\" && redact !== \"apply\" && redact !== \"refuse\") throw new CliError(\"--redact must be off, apply or refuse\");\n return redact;\n}\n\nexport const REDACT_FLAG = {\n name: \"redact\",\n help: \"off (default) | apply: run the world's [redact] policy over the rows first | refuse: reject plaintext in a redacted field.\",\n default: \"off\",\n} as const;\n","import type { CommandGroup } from \"../router\";\nimport { registerAgentCommands } from \"./agent\";\nimport { registerAuthCommands } from \"./auth\";\nimport { registerBenchCommands } from \"./bench\";\nimport { registerBenchmarksCommands } from \"./benchmarks\";\nimport { registerConnectorCommands } from \"./connector\";\nimport { registerDataCommands } from \"./data\";\nimport { registerDatasetCommands } from \"./dataset\";\nimport { registerEnvironmentCommands } from \"./environment\";\nimport { registerFilesCommands } from \"./files\";\nimport { registerPythonOnlyCommands } from \"./pythonOnly\";\nimport { registerReleaseCommands } from \"./release\";\nimport { registerRunCommands } from \"./run\";\nimport { registerSecretCommands } from \"./secret\";\nimport { registerSessionCommands } from \"./session\";\nimport { registerSkillCommands } from \"./skill\";\nimport { registerTaskCommands } from \"./task\";\nimport { registerTracesCommands } from \"./traces\";\nimport { registerWorldCommands } from \"./worlds\";\n\n/** Platform-backed groups: auth, secret, agent, run, dataset, bench, benchmarks, worlds\n * session/task/connector/skill/data, environment, release — one file per group,\n * every command's name and flags mirroring the Python CLI. */\nexport function registerPlatformCommands(root: CommandGroup): void {\n registerAuthCommands(root);\n registerSecretCommands(root);\n registerAgentCommands(root);\n registerRunCommands(root);\n registerDatasetCommands(root);\n registerBenchCommands(root);\n registerBenchmarksCommands(root);\n registerWorldCommands(root);\n registerSessionCommands(root);\n registerTaskCommands(root);\n registerConnectorCommands(root);\n registerSkillCommands(root);\n registerDataCommands(root);\n registerEnvironmentCommands(root);\n registerReleaseCommands(root);\n registerTracesCommands(root);\n registerFilesCommands(root);\n registerPythonOnlyCommands(root);\n}\n\nexport { parseRows, rowsMode, type Rows, type RowsMode } from \"./rows\";\n","import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { Readable } from \"node:stream\";\n\nimport { api, printJson, type Credentials } from \"../config\";\nimport { arg, CliError, type CommandContext, type CommandGroup, type FlagSpec, type Parsed } from \"../router\";\nimport { pull, readLocalMeta } from \"../../worlds/hub\";\nimport type { WorldQueryAcrossResult } from \"../../worlds/query\";\nimport { parseRows, rowsMode, rowsRedact, REDACT_FLAG, type Rows, type RowsRedact } from \"./rows\";\nimport { credentials, HOST_FLAG, query, showProgress, worldsOptions } from \"./shared\";\nimport { forEachLimited, waitForBatch, WorldDataApi, writeRefusalReport, type BatchStatus } from \"./worldData/batches\";\nimport { buildChunks, DEFAULT_CHUNK_BYTES, parseSize } from \"./worldData/chunker\";\nimport { fetchSessionCalls, parseClickhouseText, PULL_FROM, printLines, recordsFromClickhouse, recordsFromSessionCalls, renderSummary, summarizeRecords, type PullFrom } from \"./worldData/callsPull\";\nimport { extractRows, pyDumpsPlain, SHAPES, type Merge, type Shape } from \"./worldData/extract\";\nimport { MAP_FILE, MAP_KINDS, readMapping, skeleton, worldMapping, type MapKind } from \"./worldData/ingestMap\";\nimport { FROM, readFileText, readInputRecords, type From } from \"./worldData/records\";\nimport { DEFAULT_TRANSFORM_TIMEOUT_MS, runTransform } from \"./worldData/transform\";\nimport { findResumable, manifestDir, MANIFEST_DIR, newManifest, readManifest, recordChunk, uploadedEntry, writeManifest, type Manifest, type ManifestFlags } from \"./worldData/manifest\";\nimport { fileInput, readRows, type RowInput } from \"./worldData/rowSource\";\nimport { loadWorldConfig } from \"./worldData/worldConfig\";\nimport { inputLabels, inputsField, landInDrive, scratchFile, stageDriveInputs, TO_FLAG, type StagedInputs } from \"./worldData/driveIo\";\nimport { isDriveRef } from \"../../files/index\";\n\n// A local directory goes through the runtime track's bridge; the import is\n// lazy so a slug-only invocation never loads it.\nconst runtimeData = () => import(\"../runtime/data\");\ntype LocalIngestRefusal = import(\"../runtime/data\").LocalIngestRefusal;\ntype LocalIngestSource = import(\"../runtime/data\").LocalIngestSource;\n\nconst isDirectory = (p: string) => fs.existsSync(p) && fs.statSync(p).isDirectory();\nconst slugOf = (world: string) => world.split(\"@\", 1)[0]!;\nconst worldRoute = (world: string) => `/api/public/worlds/${encodeURIComponent(slugOf(world))}/data`;\n\n/** The inline gate for a local directory: the bridge takes the rows whole (the Python `INLINE_*`). */\nexport const INLINE_ROWS = 5000;\nexport const INLINE_BYTES = 4 * 1024 * 1024;\n\nconst WORLD_HELP = \"World directory, or a platform world slug (optionally slug@ref).\";\nconst ENTITY_FLAG: FlagSpec = { name: \"entity\", help: \"The entity bare-row files hold.\" };\nconst REPORT_FLAG: FlagSpec = { name: \"report\", help: \"Write the refusals as JSONL here.\" };\nconst MESSAGE_FLAG: FlagSpec = { name: \"message\", short: \"m\", help: \"Change reason for the version.\" };\n\n/**\n * `gateway worlds data …`, the same surface as the Python CLI (contract §11):\n * rows into a world and out of the shapes agents have. A platform slug\n * streams chunks into a data batch (§7, §10); a local directory keeps the\n * small inline import through the runtime bridge. `extract` runs here,\n * natively, on files of any size.\n */\nexport function registerDataCommands(root: CommandGroup): void {\n const data = root\n .group(\"worlds\", \"Build, seed, serve and run worlds.\")\n .group(\"data\", \"Put rows into a world, or see what it holds — local directory or platform slug\");\n\n data.command({\n name: \"import\",\n help: \"Put rows into a world through its own gate.\",\n positionals: [\n { name: \"world\", help: WORLD_HELP },\n { name: \"rows\", help: \"Rows files ({entity: [rows]} JSON, {entity,row} JSONL, bare rows), - for stdin, or drive:<path>.\", variadic: true },\n ],\n flags: [\n ENTITY_FLAG,\n { name: \"mode\", help: \"append (upsert by primary key) | replace (named entities).\", default: \"append\" },\n { name: \"merge\", help: \"Inside the batch, by key: upsert (last wins) | fill (first wins, later add fields).\", default: \"upsert\" },\n REDACT_FLAG,\n { name: \"chunk-rows\", help: \"Rows per uploaded chunk (instead of --chunk-bytes).\" },\n { name: \"chunk-bytes\", help: \"JSONL bytes per uploaded chunk before gzip (default 64MiB).\" },\n { name: \"parallel\", help: \"Chunk uploads in flight.\", default: \"4\" },\n { name: \"resume\", help: \"Pick up the newest incomplete upload of this world and these files.\", boolean: true },\n { name: \"atomic\", help: \"One refusal refuses the batch (default).\", boolean: true },\n { name: \"per-chunk\", help: \"One refusal refuses only its chunk.\", boolean: true },\n { name: \"publish\", help: \"now: a version per batch | later: fold with `data publish`.\", default: \"now\" },\n { name: \"wait\", help: \"Wait for the batch to apply (default).\", boolean: true },\n { name: \"no-wait\", help: \"Print {batchId, state} once the batch is queued.\", boolean: true },\n REPORT_FLAG,\n { name: \"dry-run\", help: \"Validate against the contract; upload nothing to the world, write nothing.\", boolean: true },\n MESSAGE_FLAG,\n HOST_FLAG,\n ],\n notes:\n \"A directory: the rows go into the schema world's tree as data/initial.json, small inputs only.\\n\" +\n \"A slug: the rows stream up as gzipped chunks into a data batch\\n\" +\n \"the platform validates, applies onto the world's snapshot and (with --publish now) turns into a\\n\" +\n \"data-only version. Exit 0 applied or published, 2 refused (report written), 1 error.\",\n run: async (args, ctx) => {\n const [world, ...files] = args.positionals;\n if (files.length === 0) throw new CliError(\"worlds data import needs at least one rows file\");\n const dryRun = arg.bool(args, \"dry-run\");\n const staged = await stageDriveInputs(files, () => credentials(args));\n try {\n if (isDirectory(world!))\n return await (dryRun ? checkLocalDirectory(world!, staged.files, args, ctx, staged.labels) : importLocalDirectory(world!, staged.files, args, ctx, staged.labels));\n return await importBatch(world!, staged.files, args, ctx, dryRun ? \"check\" : \"import\", undefined, staged.labels);\n } finally {\n staged.cleanup();\n }\n },\n });\n\n data.command({\n name: \"check\",\n help: \"Dry run: every row checked against the world's contract; nothing uploaded to the world, nothing written.\",\n positionals: [\n { name: \"world\", help: \"World directory, or a platform world slug (its contract is pulled).\" },\n { name: \"rows\", help: \"Rows files, - for stdin, or drive:<path>.\", variadic: true },\n ],\n flags: [\n ENTITY_FLAG,\n { name: \"mode\", help: \"append | replace, as the import would run.\", default: \"append\" },\n { name: \"merge\", help: \"upsert | fill, as the import would run.\", default: \"upsert\" },\n REDACT_FLAG,\n REPORT_FLAG,\n HOST_FLAG,\n ],\n notes:\n \"A slug: a dry-run batch on the platform (every chunk validated, nothing applied). A directory: the\\n\" +\n \"runtime bridge's import over a scratch copy, nothing written back. Exit 2 when any row is refused.\",\n run: async (args, ctx) => {\n const [world, ...files] = args.positionals;\n if (files.length === 0) throw new CliError(\"worlds data check needs at least one rows file\");\n const staged = await stageDriveInputs(files, () => credentials(args));\n try {\n if (isDirectory(world!)) return await checkLocalDirectory(world!, staged.files, args, ctx, staged.labels);\n return await importBatch(world!, staged.files, args, ctx, \"check\", undefined, staged.labels);\n } finally {\n staged.cleanup();\n }\n },\n });\n\n data.command({\n name: \"extract\",\n help: \"Rows out of a tool-results export, a vendor response or a session export, shaped for `data import`.\",\n positionals: [\n { name: \"world\", help: \"World directory, or a platform world slug (its contract is pulled).\" },\n { name: \"source\", help: \"Input file, - for stdin, or drive:<path>.\" },\n ],\n flags: [\n { name: \"shape\", help: \"tool-results | vendor-envelope | session-export.\" },\n { name: \"entity\", help: \"The entity the rows belong to.\" },\n { name: \"out\", help: \"Write tagged JSONL here (default stdout, also -).\" },\n TO_FLAG,\n { name: \"merge\", help: \"Dedupe by primary key: fill (first wins) | upsert (last wins).\", default: \"fill\" },\n { name: \"no-redact\", help: \"Skip the world's [redact] policy.\", boolean: true },\n HOST_FLAG,\n ],\n notes:\n \"Null and empty fields dropped, undeclared fields stripped (and counted on stderr), deduped by\\n\" +\n \"primary key, the world's [redact] policy applied. Summary on stderr:\\n\" +\n '{\"read\": N, \"rows\": M, \"unknownFields\": {...}, \"redacted\": {\"dropped\": n, \"hashed\": n}}.',\n run: async (args, ctx) => {\n const [world, source] = args.positionals;\n const shape = arg.str(args, \"shape\");\n if (!shape || !SHAPES.includes(shape as Shape)) throw new CliError(`shape must be one of ${SHAPES.join(\", \")}`, 1);\n const entity = arg.str(args, \"entity\");\n if (!entity) throw new CliError(\"extract needs --entity\");\n const merge = arg.str(args, \"merge\") ?? \"fill\";\n if (merge !== \"fill\" && merge !== \"upsert\") throw new CliError(\"merge must be one of fill, upsert\", 1);\n const dir = isDirectory(world!) ? world! : await pullWorld(world!, credentials(args));\n const config = loadWorldConfig(dir);\n const staged = await stageDriveInputs([source!], () => credentials(args));\n const to = arg.str(args, \"to\");\n const out = arg.str(args, \"out\");\n const local = out && out !== \"-\" ? out : null;\n const scratch = to && !local ? scratchFile(\"extract.jsonl\") : null;\n const file = local ?? scratch?.file ?? null;\n try {\n const input = source === \"-\" ? stdinInput(ctx) : fileInput(staged.files[0]!);\n const sink = file ? fs.createWriteStream(file) : null;\n const write = sink ? (line: string) => void sink.write(line + \"\\n\") : (line: string) => ctx.stdout(line);\n const summary: Record<string, unknown> = await extractRows(input, config, { shape: shape as Shape, entity, merge: merge as Merge, redact: !arg.bool(args, \"no-redact\") }, write);\n if (sink) await new Promise<void>((resolve, reject) => sink.end((error?: Error | null) => (error ? reject(error) : resolve())));\n if (Object.keys(staged.labels).length) summary.source = inputLabels(staged.files, staged.labels)[0];\n if (to) {\n const landed = await landInDrive(file!, to, credentials(args));\n summary.to = `drive:${landed.path}`;\n }\n ctx.stderr(pyDumpsPlain(summary));\n } finally {\n staged.cleanup();\n scratch?.cleanup();\n }\n },\n });\n\n data\n .group(\"calls\", \"Raw tool-call records out of the platform, untouched — what an agent looks at before it writes a transform.\")\n .command({\n name: \"pull\",\n help: \"Write tool-call records ({tool, args, result, at, source} JSONL) from traces, a world session, or a saved ClickHouse result; print what they hold.\",\n positionals: [\n { name: \"out\", help: \"Where the JSONL goes, or - for stdout (may be omitted with --to when there are no input files).\", optional: true },\n { name: \"inputs\", help: \"With --from clickhouse-result: the saved result files ({rows|results: [...]}; text before the JSON is skipped), local or drive:<path>.\", variadic: true },\n ],\n flags: [\n { name: \"from\", help: \"traces (the observations API) | session (a world session's call log) | clickhouse-result (saved files) | drive:<path> (a saved result in the drive).\" },\n TO_FLAG,\n { name: \"trace\", help: \"With --from traces: a trace id; repeat for more.\", repeat: true },\n { name: \"session\", help: \"With --from traces: every trace of this trace session. With --from session: the world session id.\" },\n { name: \"since\", help: \"With --from traces: only calls that started at or after this ISO time.\" },\n { name: \"until\", help: \"With --from traces: only calls that started before this ISO time.\" },\n { name: \"tool\", help: \"Keep only calls of this tool; repeat for more.\", repeat: true },\n { name: \"json\", help: \"Print the summary as one JSON document instead of lines.\", boolean: true },\n HOST_FLAG,\n ],\n notes:\n \"Nothing is shaped: every TOOL observation becomes one record (name = tool, input = args, output =\\n\" +\n \"result, startTime = at, trace:<trace>/<observation> = source; an ERROR-level one carries `error`),\\n\" +\n \"whatever tool it names. The summary — records per tool, and each distinct result shape (an\\n\" +\n \"object's top-level keys, an array's item keys) with its count — goes to stdout when the records go\\n\" +\n \"to a file, to stderr when they go to stdout. Then look, write the transform, and run\\n\" +\n \"`gateway worlds data ingest <world> <out> --transform <script> --dry-run`.\",\n run: async (args, ctx) => {\n const [out, ...inputs] = args.positionals;\n return pullCallsCommand(out, inputs, args, ctx);\n },\n });\n\n data.command({\n name: \"ingest\",\n help: \"Records into rows through the route you declare — your transform, an ingest.toml mapping, or the operations' projection — then the world's gate. Redaction optional, off by default.\",\n positionals: [\n { name: \"world\", help: WORLD_HELP + \" Or `map init <world> <sample>` to start an ingest.toml.\" },\n { name: \"inputs\", help: \"Records: tool-call JSONL / JSON array (or a session export), rows JSON/JSONL, or CSV, per --from; - for stdin; drive:<path> for a file in the drive.\", variadic: true },\n ],\n flags: [\n { name: \"from\", help: \"tool-calls (default) | traces (pull TOOL observations) | rows (JSON objects; a saved result selects rows[*]) | csv (header row) | drive:<path> (tool-call records in the drive).\", default: \"tool-calls\" },\n { name: \"transform\", help: \"Your script (.py, .ts, .mjs): transform(records) -> {entity: [rows]}, or stdin JSONL -> stdout rows.\" },\n { name: \"map\", help: `An ingest.toml mapping (default: the world's own ${MAP_FILE} when it has one).` },\n { name: \"timeout\", help: \"Seconds a --transform script may run.\", default: String(DEFAULT_TRANSFORM_TIMEOUT_MS / 1000) },\n { name: \"trace\", help: \"With --from traces: a trace id; repeat for more.\", repeat: true },\n { name: \"session\", help: \"With --from traces: every trace of this session (GET /api/public/sessions/{id}?includeIO=true).\" },\n { name: \"since\", help: \"With --from traces: only calls that started at or after this ISO time.\" },\n { name: \"tool\", help: \"Keep only calls of this tool; repeat for more.\", repeat: true },\n { name: \"entity\", help: \"With --from rows and no map: the entity bare-row files hold. With map init: the entity to fill in.\" },\n { name: \"out\", help: \"With map init: where the skeleton goes (default ingest.toml in the world, or stdout for a slug).\" },\n { name: \"mode\", help: \"append (upsert by primary key) | replace (named entities).\", default: \"append\" },\n REDACT_FLAG,\n { name: \"dry-run\", help: \"Produce and prove the rows against the contract; write and upload nothing.\", boolean: true },\n REPORT_FLAG,\n { name: \"json\", help: \"Print the whole report as one JSON document.\", boolean: true },\n MESSAGE_FLAG,\n HOST_FLAG,\n ],\n notes:\n \"The route: --transform runs your code in a subprocess (time limit, sockets disabled, stderr shown)\\n\" +\n \"over the records and takes the {entity: [rows]} it returns; --map (or the world's ingest.toml)\\n\" +\n \"applies a declared mapping, and the dry run reports per source the records seen, rows per\\n\" +\n \"entity, source fields nothing reads (with a sample) and entity fields never set; with neither,\\n\" +\n \"--from rows is a plain `data import` of rows files, and tool calls go through each tool's\\n\" +\n \"[[operations]] projection in connector.toml (the report says so: that is the operation's own\\n\" +\n \"shape, not a mapping; an unknown tool is a refusal). Every route ends at the same gate as `data\\n\" +\n \"import`: a directory is written in place, a slug is proven locally then pushed through the batch\\n\" +\n \"lane. Redaction is OPTIONAL and OFF by default (--redact apply | refuse). Exit 0, 2 refused, 1 error.\\n\" +\n \"`ingest map init <world> <sample> [--from …] [--entity …] [--out …]` writes an ingest.toml skeleton:\\n\" +\n \"every source field on one side, every entity field on the other, only exact-name matches filled\\n\" +\n \"in (marked to confirm), nothing guessed.\",\n run: async (args, ctx) => {\n const [world, ...inputs] = args.positionals;\n if (world === \"map\") {\n const [verb, target, ...samples] = inputs;\n if (verb !== \"init\" || !target) throw new CliError(\"ingest map takes: init <world> <sample...>\");\n return mapInitCommand(target, samples, args, ctx);\n }\n const fromDrive = driveFrom(args);\n const staged = await stageDriveInputs(fromDrive ? [fromDrive, ...inputs] : inputs, () => credentials(args));\n try {\n return await ingestCommand(world!, staged.files, args, ctx, staged.labels);\n } finally {\n staged.cleanup();\n }\n },\n });\n\n data.command({\n name: \"status\",\n help: \"One batch's state, progress, counts and first refusals.\",\n positionals: [{ name: \"batchId\", help: \"The batch id `data import` printed or recorded in .gateway/imports/.\" }],\n flags: [{ name: \"world\", help: \"The world slug, when no manifest names it.\" }, HOST_FLAG],\n run: async (args, ctx) => {\n const batchId = args.positionals[0]!;\n const slug = arg.str(args, \"world\") ?? readManifest(batchId)?.slug;\n if (!slug) throw new CliError(`no manifest for ${batchId} under ${MANIFEST_DIR}; pass --world SLUG`, 1);\n printJson(ctx, await new WorldDataApi(credentials(args), slugOf(slug)).get(batchId));\n },\n });\n\n data.command({\n name: \"batches\",\n help: \"The world's data batches, newest first.\",\n positionals: [{ name: \"world\", help: \"World slug.\" }],\n flags: [{ name: \"limit\", help: \"At most this many, newest first.\" }, HOST_FLAG],\n run: async (args, ctx) => {\n printJson(ctx, await new WorldDataApi(credentials(args), slugOf(args.positionals[0]!)).list(arg.int(args, \"limit\")));\n },\n });\n\n data.command({\n name: \"publish\",\n help: \"Fold every applied `--publish later` batch into one data-only version.\",\n positionals: [{ name: \"world\", help: \"World slug.\" }],\n flags: [MESSAGE_FLAG, HOST_FLAG],\n run: async (args, ctx) => {\n printJson(ctx, await new WorldDataApi(credentials(args), slugOf(args.positionals[0]!)).publish(arg.str(args, \"message\")));\n },\n });\n\n data.command({\n name: \"show\",\n help: \"What a world seeds with: every entity's row count, or one entity's rows.\",\n positionals: [{ name: \"world\", help: WORLD_HELP }],\n flags: [{ name: \"entity\", help: \"Print this entity's rows instead of counts.\" }, HOST_FLAG],\n run: async (args, ctx) => {\n const world = args.positionals[0]!;\n const entity = arg.str(args, \"entity\");\n if (isDirectory(world)) {\n const { showLocalWorldData } = await runtimeData();\n const { credentialsForRuntime } = await import(\"../runtime/local\");\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n printJson(ctx, { world, ...(await showLocalWorldData(world, entity, creds)) });\n return;\n }\n const creds = credentials(args);\n const result = await api<Record<string, unknown>>(creds, \"GET\", `${worldRoute(world)}${query({ entity })}`);\n printJson(ctx, { world, ...(entity ? { entity } : {}), ...result });\n },\n });\n\n data.command({\n name: \"query\",\n help: \"One entity's rows matching a predicate — by stored value, or by plaintext with --resolve.\",\n positionals: [\n { name: \"world\", help: WORLD_HELP },\n { name: \"entity\", help: \"The entity to query (`worlds describe` lists them).\" },\n ],\n flags: [\n { name: \"where\", help: \"field=value; repeat for more fields, repeat a field for any-of.\", repeat: true },\n { name: \"resolve\", help: \"The values are plaintext: match their stored forms per the world's [redact] policy.\", boolean: true },\n { name: \"limit\", help: \"At most this many rows.\" },\n { name: \"offset\", help: \"Skip this many matching rows first.\" },\n {\n name: \"scenario\",\n help: \"Directory: the rows a session opened in scenarios/<name>/ starts from (template + that seed overlay).\",\n },\n { name: \"across\", help: \"Also query every linked world whose entity mapping covers a --where field.\", boolean: true },\n { name: \"compare\", help: \"With --across: the parity table (matched / no match / unmapped per field per world) on stderr.\", boolean: true },\n { name: \"json\", help: \"Print the whole result as one JSON document.\", boolean: true },\n HOST_FLAG,\n ],\n notes:\n \"Without --resolve a value matches the store as given (a digest you already hold works). With it, a\\n\" +\n \"[hash] field matches the slug-salted sha256 of the value, [preserve] its shaped digest, and a [drop]\\n\" +\n \"field resolves to nothing and matches no row — the `resolved <field> -> …` lines on stderr say which.\\n\" +\n \"One row per line on stdout (compact JSON), then `<n> of <total> (offset <o>)` on stderr. A directory\\n\" +\n \"is queried by the schema runtime; a slug by GET /api/public/worlds/{slug}/data (its head; no @ref).\\n\" +\n \"--across takes the plaintext into every linked world ([dependencies.<alias>.entities]) whose mapping\\n\" +\n \"covers a --where field, each resolving its own stored form after the mapping's transform: one\\n\" +\n \"`== <slug> (<alias>) <n> of <total>` header per world on stdout, then its rows. --compare adds the\\n\" +\n \"parity table on stderr, one `compare <field>: <world> <status>` line per world, with the mapped field\\n\" +\n \"and the transform applied. A directory reads each linked world at the `path` beside its pin (bundled\\n\" +\n \"runtime), in the scenario its `task` names — what a linked session opens it in; a slug reads them at\\n\" +\n \"the versions the platform pinned. A template that keeps its rows in scenarios/<name>/seed/ over an\\n\" +\n \"empty base (the shipped Slack template does) shows nothing without --scenario.\",\n run: async (args, ctx) => {\n const [world, entity] = args.positionals as [string, string];\n const where = parseWhere(arg.list(args, \"where\"));\n const across = arg.bool(args, \"across\");\n const compare = arg.bool(args, \"compare\");\n if (compare && !across) throw new CliError(\"--compare needs --across\");\n const opts = {\n resolve: arg.bool(args, \"resolve\"),\n limit: positiveInt(args, \"limit\", 1),\n offset: positiveInt(args, \"offset\", 0),\n };\n const scenario = arg.str(args, \"scenario\");\n if (isDirectory(world)) {\n const { queryLocalWorldData, queryLocalWorldDataAcross } = await runtimeData();\n const local = { ...opts, ...(scenario ? { scenario } : {}) };\n if (across) {\n const result = await queryLocalWorldDataAcross(world, entity, where, { ...local, compare });\n if (arg.bool(args, \"json\")) printJson(ctx, { world, ...result });\n else renderAcross(result, ctx);\n return;\n }\n const { credentialsForRuntime } = await import(\"../runtime/local\");\n const result = await queryLocalWorldData(world, entity, where, local, credentialsForRuntime(arg.str(args, \"host\")));\n if (arg.bool(args, \"json\")) printJson(ctx, { world, ...result });\n else renderPage(result, ctx);\n return;\n }\n if (scenario) throw new CliError(\"--scenario reads a directory's scenarios/<name>/; a slug's data is its head\");\n const { queryRows } = await import(\"../../worlds/query\");\n const options = worldsOptions(credentials(args));\n if (across) {\n const result = await queryRows(world, entity, { where, ...opts, across: true, compare }, options);\n if (arg.bool(args, \"json\")) printJson(ctx, { world, ...result });\n else renderAcross(result, ctx);\n return;\n }\n const result = await queryRows(world, entity, { where, ...opts }, options);\n if (arg.bool(args, \"json\")) printJson(ctx, { world, ...result });\n else renderPage(result, ctx);\n },\n });\n}\n\n/** What the two `query` callers agree on, whichever fields travel beside it. */\ntype QueryPage = {\n rows: Record<string, unknown>[];\n count: number;\n total: number | null;\n offset: number;\n resolved?: Record<string, (string | number)[]>;\n};\n\n/** One page: `resolved` lines on stderr, a row per stdout line, the footer on stderr. */\nfunction renderPage(result: QueryPage, ctx: CommandContext): void {\n for (const line of resolvedLines(result.resolved)) ctx.stderr(line);\n for (const row of result.rows) ctx.stdout(JSON.stringify(row));\n ctx.stderr(`${result.count} of ${result.total ?? \"?\"} (offset ${result.offset})`);\n}\n\nfunction resolvedLines(resolved: QueryPage[\"resolved\"], prefix = \"\"): string[] {\n return Object.entries(resolved ?? {}).map(([field, forms]) =>\n forms.length\n ? `resolved ${prefix}${field} -> ${forms.map(String).join(\", \")}`\n : `resolved ${prefix}${field} -> nothing (the field is not stored; no row can match)`,\n );\n}\n\n/** What a group renders from, whichever side (platform or local runtime) answered it. */\ntype AcrossGroup = Omit<WorldQueryAcrossResult[\"groups\"][number], \"world\"> & { world: { slug: string; alias: string | null } };\n\n/** `<slug>` for the root, `<slug> (<alias>)` for a linked world. */\nconst worldLabel = (slug: string, alias: string | null) => (alias ? `${slug} (${alias})` : slug);\n\n/**\n * The groups, each under its `== <world> <n> of <total>` header on stdout,\n * its `resolved` lines on stderr; then, when asked, the parity table on\n * stderr — a line per field per world, the mapped field and the transform\n * beside a mapped world, and the present/absent summary.\n */\nfunction renderAcross(result: Pick<WorldQueryAcrossResult, \"compare\"> & { groups: AcrossGroup[] }, ctx: CommandContext): void {\n for (const group of result.groups) {\n const label = worldLabel(group.world.slug, group.world.alias);\n ctx.stdout(`== ${label} ${group.count} of ${group.total ?? \"?\"}`);\n for (const line of resolvedLines(group.resolved, `${label} `)) ctx.stderr(line);\n for (const row of group.rows) ctx.stdout(JSON.stringify(row));\n }\n const compare = result.compare;\n if (!compare) return;\n for (const { field, worlds } of compare.perField) {\n for (const entry of worlds) {\n const via = entry.depField ? ` <- ${entry.depField}${entry.transform?.length ? ` via ${entry.transform.join(\", \")}` : \"\"}` : \"\";\n ctx.stderr(`compare ${field}: ${worldLabel(entry.world, entry.alias)} ${entry.status}${via}`);\n }\n }\n ctx.stderr(`compare present: ${compare.present.length ? compare.present.join(\", \") : \"(none)\"}`);\n ctx.stderr(`compare absent: ${compare.absent.length ? compare.absent.join(\", \") : \"(none)\"}`);\n}\n\n/** `--where k=v` lines → field → value; the same field twice → a list (any of). */\nexport function parseWhere(clauses: string[]): Record<string, string | string[]> {\n const where: Record<string, string | string[]> = {};\n for (const clause of clauses) {\n const eq = clause.indexOf(\"=\");\n const field = eq === -1 ? \"\" : clause.slice(0, eq).trim();\n if (!field) throw new CliError(`--where takes field=value, got '${clause}'`);\n const value = clause.slice(eq + 1);\n const held = where[field];\n where[field] = held === undefined ? value : [...(Array.isArray(held) ? held : [held]), value];\n }\n return where;\n}\n\nfunction positiveInt(args: Parsed, name: string, least: number): number | undefined {\n const value = arg.int(args, name);\n if (value !== undefined && value < least) throw new CliError(`--${name} must be at least ${least}`);\n return value;\n}\n\n// ------------------------------------------------------------ the batch door\n\ntype ImportFlags = ManifestFlags & { parallel: number; wait: boolean; resume: boolean; message?: string; report?: string };\n\n/** `check` is a dry-run batch: atomic, waited for, never published. */\ntype Purpose = \"import\" | \"check\";\n\nfunction importFlags(args: Parsed, purpose: Purpose): ImportFlags {\n const mode = arg.str(args, \"mode\") ?? \"append\";\n const merge = arg.str(args, \"merge\") ?? \"upsert\";\n const publish = purpose === \"check\" ? \"now\" : (arg.str(args, \"publish\") ?? \"now\");\n if (![\"append\", \"replace\"].includes(mode) || ![\"upsert\", \"fill\"].includes(merge) || ![\"now\", \"later\"].includes(publish))\n throw new CliError(\"--mode is append|replace, --merge is upsert|fill, --publish is now|later\", 1);\n if (arg.bool(args, \"atomic\") && arg.bool(args, \"per-chunk\")) throw new CliError(\"--atomic and --per-chunk exclude each other\");\n if (arg.bool(args, \"wait\") && arg.bool(args, \"no-wait\")) throw new CliError(\"--wait and --no-wait exclude each other\");\n const chunkRows = arg.int(args, \"chunk-rows\") ?? null;\n if (chunkRows !== null && chunkRows < 1) throw new CliError(\"chunk bounds must be positive\", 1);\n const sizeText = arg.str(args, \"chunk-bytes\");\n let chunkBytes = DEFAULT_CHUNK_BYTES;\n if (sizeText !== undefined) {\n try {\n chunkBytes = parseSize(sizeText);\n } catch (error) {\n throw new CliError((error as Error).message, 1);\n }\n }\n return {\n mode: mode as ManifestFlags[\"mode\"],\n merge: merge as ManifestFlags[\"merge\"],\n redact: rowsRedact(arg.str(args, \"redact\")),\n atomic: purpose === \"check\" ? true : !arg.bool(args, \"per-chunk\"),\n publish: publish as ManifestFlags[\"publish\"],\n dryRun: purpose === \"check\",\n chunkBytes,\n chunkRows,\n entity: arg.str(args, \"entity\") ?? null,\n parallel: Math.max(1, arg.int(args, \"parallel\") ?? 4),\n wait: purpose === \"check\" ? true : !arg.bool(args, \"no-wait\"),\n resume: purpose === \"check\" ? false : arg.bool(args, \"resume\"),\n message: arg.str(args, \"message\"),\n report: arg.str(args, \"report\"),\n };\n}\n\nfunction rowInputs(files: string[], ctx: CommandContext): RowInput[] {\n if (files.filter((f) => f === \"-\").length > 1) throw new CliError(\"stdin (-) can be read once\");\n for (const file of files) {\n // Refuse before a batch is opened for nothing.\n if (file !== \"-\" && !(fs.existsSync(file) && fs.statSync(file).isFile())) throw new CliError(`Cannot read ${file}`, 1);\n }\n return files.map((f) => (f === \"-\" ? stdinInput(ctx) : fileInput(f)));\n}\n\nfunction stdinInput(ctx: CommandContext): RowInput {\n return {\n name: \"-\",\n open: () =>\n ctx.stdinStream\n ? (ctx.stdinStream() as Readable)\n : Readable.from(\n (async function* () {\n yield Buffer.from(await ctx.stdin(), \"utf8\");\n })(),\n ),\n };\n}\n\n/** The first pause between status polls; CI and tests shorten it. */\nfunction pollMs(): number {\n const raw = Number(process.env.GATEWAY_WORLD_DATA_POLL_MS ?? 1000);\n return Number.isFinite(raw) && raw >= 0 ? raw : 1000;\n}\n\n/**\n * Stream, chunk, upload, complete, then follow the job — the Python\n * `world_data.import_rows` + `wait`, request for request. Shared by\n * `import` and `check` (a dry-run batch).\n */\nasync function importBatch(\n world: string,\n files: string[],\n args: Parsed,\n ctx: CommandContext,\n purpose: Purpose,\n /** Take the batch's outcome instead of printing it (`data ingest` folds it into its own report). */\n onStatus?: (status: Record<string, unknown>) => void,\n /** Scratch path → `drive:<path>` for inputs staged from the drive; the report and manifest keep that spelling. */\n labels: Record<string, string> = {},\n): Promise<number> {\n const slug = slugOf(world);\n const named = inputLabels(files, labels);\n const creds = credentials(args);\n const flags = importFlags(args, purpose);\n const client = new WorldDataApi(creds, slug);\n const progress = (line: string) => {\n if (showProgress()) ctx.stderr(line);\n };\n\n // An unfinished import is resumed with the flags it was started with: the\n // chunk boundaries (and so the digests the server holds) depend on them.\n const resumable = flags.resume ? findResumable(slug, named) : null;\n if (flags.resume && !resumable) throw new CliError(`nothing to resume: no incomplete manifest for ${slug} under ${manifestDir()}`, 1);\n const plan: ManifestFlags = resumable\n ? resumable.flags\n : { mode: flags.mode, merge: flags.merge, redact: flags.redact, atomic: flags.atomic, publish: flags.publish, dryRun: flags.dryRun, chunkBytes: flags.chunkBytes, chunkRows: flags.chunkRows, entity: flags.entity };\n\n // Read the first row before anything is opened on the platform: a file\n // that fits no shape is refused with no request made.\n const source = readRows(rowInputs(files, ctx), plan.entity ?? undefined);\n const first = await source.next();\n if (first.done) throw new CliError(`no rows in ${files.join(\" \")}; nothing to import`, 1);\n const rows = (async function* () {\n yield first.value;\n yield* source;\n })();\n\n let manifest: Manifest;\n if (resumable) {\n const status = await client.get(resumable.batchId);\n if (status.state !== \"open\" && status.state !== \"uploading\") throw new CliError(`batch ${resumable.batchId} is ${status.state}; only an open or uploading batch resumes`, 1);\n manifest = resumable;\n progress(`resuming batch ${manifest.batchId} (${manifest.chunks.length} chunks recorded)`);\n } else {\n const opened = await client.open({\n mode: plan.mode,\n merge: plan.merge,\n ...(plan.redact && plan.redact !== \"off\" ? { redact: plan.redact } : {}),\n atomic: plan.atomic,\n dryRun: plan.dryRun,\n publish: plan.publish,\n ...(flags.message ? { message: flags.message } : {}),\n });\n if (!opened.batchId) throw new CliError(\"the platform opened no batch (no batchId in the answer)\", 1);\n const limit = opened.limits?.chunkBytes;\n if (typeof limit === \"number\" && plan.chunkBytes > limit) throw new CliError(`--chunk-bytes ${plan.chunkBytes} exceeds the platform's chunk limit ${limit}`, 1);\n manifest = newManifest({ batchId: opened.batchId, slug, host: creds.host, flags: plan, inputs: named });\n writeManifest(manifest);\n progress(`batch ${manifest.batchId} open`);\n }\n const batchId = manifest.batchId;\n\n const chunks = buildChunks(rows, { chunkBytes: plan.chunkBytes, chunkRows: plan.chunkRows, entity: plan.entity });\n await forEachLimited(chunks, flags.parallel, async (chunk) => {\n if (uploadedEntry(manifest, chunk.ordinal, chunk.digest)) {\n progress(`chunk ${chunk.ordinal}: already uploaded (${chunk.rows} rows)`);\n return;\n }\n const entry = await client.upload(batchId, chunk);\n recordChunk(manifest, entry);\n writeManifest(manifest);\n progress(`chunk ${chunk.ordinal}: uploaded ${chunk.rows} rows, ${chunk.bytes} bytes (${entry.chunkId})`);\n });\n\n await client.complete(batchId);\n manifest.completed = true;\n writeManifest(manifest);\n progress(`batch ${batchId} complete: ${manifest.chunks.length} chunks`);\n\n if (!flags.wait) {\n if (onStatus) onStatus({ batchId, state: \"queued\" });\n else ctx.stdout(JSON.stringify({ batchId, state: \"queued\" }));\n return 0;\n }\n const status = await waitForBatch(client, batchId, {\n onPhase: (line) => progress(line),\n initialDelayMs: pollMs(),\n });\n if (flags.report !== undefined) {\n const written = await writeRefusalReport(status, flags.report);\n progress(`${written} refusal${written === 1 ? \"\" : \"s\"} written to ${flags.report}`);\n }\n if (purpose === \"check\") {\n printJson(ctx, { world, ...inputsField(files, labels), dryRun: true, rows: status.rows ?? 0, refusalCount: status.refusalCount ?? 0, refusals: (status.refusals ?? []).slice(0, 200), entityCounts: status.entityCounts ?? {} });\n if (status.state === \"failed\") {\n ctx.stderr(`batch ${batchId} failed: ${status.error ?? \"unknown error\"}`);\n return 1;\n }\n return status.refusalCount ? 2 : 0;\n }\n if (onStatus) onStatus(status as unknown as Record<string, unknown>);\n else printJson(ctx, { world, ...inputsField(files, labels), ...status });\n if (status.state === \"applied\" || status.state === \"published\") return 0;\n if (status.state === \"refused\") return 2;\n ctx.stderr(`batch ${batchId} ${status.state}: ${status.error ?? \"unknown error\"}`);\n return 1;\n}\n\n// ---------------------------------------------------------- calls pull\n\nasync function pullCallsCommand(out: string | undefined, inputs: string[], args: Parsed, ctx: CommandContext): Promise<number> {\n const fromDrive = driveFrom(args);\n const from = fromDrive ? \"clickhouse-result\" : arg.str(args, \"from\");\n if (!from || !PULL_FROM.includes(from as PullFrom)) throw new CliError(`--from must be one of ${PULL_FROM.join(\", \")}, or drive:<path>`);\n const to = arg.str(args, \"to\");\n if (!out && !to) throw new CliError(\"worlds data calls pull needs <out> (or - for stdout), or --to <drive path>\");\n const staged = await stageDriveInputs(fromDrive ? [fromDrive, ...inputs] : inputs, () => credentials(args));\n try {\n return await pullCalls(out, to, from as PullFrom, staged, args, ctx);\n } finally {\n staged.cleanup();\n }\n}\n\n/** Records from the platform or the staged files, filtered, written locally and/or to the drive, then summarized. */\nasync function pullCalls(out: string | undefined, to: string | undefined, from: PullFrom, staged: StagedInputs, args: Parsed, ctx: CommandContext): Promise<number> {\n const only = new Set(arg.list(args, \"tool\"));\n const { toolCallsFromObservations } = await import(\"../../worlds/ingest\");\n let records: unknown[];\n const skipped: Record<string, number> = {};\n if (from === \"clickhouse-result\") {\n if (!staged.files.length) throw new CliError(\"--from clickhouse-result needs the saved result file(s) after <out>\");\n records = [];\n for (const file of staged.files) {\n const label = staged.labels[file] ?? file;\n records.push(...recordsFromClickhouse(parseClickhouseText(file === \"-\" ? await ctx.stdin() : readFileText(file), label), label));\n }\n } else {\n if (staged.files.length) throw new CliError(`--from ${from} reads the platform; drop the input files`);\n const creds = credentials(args);\n if (from === \"session\") {\n const sessionId = arg.str(args, \"session\");\n if (!sessionId) throw new CliError(\"--from session needs --session <world session id>\");\n const converted = recordsFromSessionCalls(await fetchSessionCalls(creds, sessionId), sessionId);\n records = converted.records;\n Object.assign(skipped, converted.skipped);\n } else {\n const { fetchToolObservations } = await import(\"./worldData/traceCalls\");\n const observations = await fetchToolObservations(creds, { traceIds: arg.list(args, \"trace\"), sessionId: arg.str(args, \"session\"), since: arg.str(args, \"since\"), until: arg.str(args, \"until\") });\n const converted = toolCallsFromObservations(observations, { session: arg.str(args, \"session\"), since: arg.str(args, \"since\") });\n records = converted.records;\n Object.assign(skipped, converted.skipped);\n }\n }\n let filtered = 0;\n if (only.size) {\n const kept = records.filter((r) => typeof r === \"object\" && r !== null && only.has(String((r as { tool?: unknown }).tool)));\n filtered = records.length - kept.length;\n records = kept;\n }\n const text = records.map((record) => JSON.stringify(record) + \"\\n\").join(\"\");\n const toStdout = out === \"-\";\n if (toStdout) {\n if (text) process.stdout.write(text);\n } else if (out) fs.writeFileSync(out, text);\n let landed: string | undefined;\n if (to) {\n const scratch = out && !toStdout ? null : scratchFile(\"calls.jsonl\");\n if (scratch) fs.writeFileSync(scratch.file, text);\n try {\n landed = `drive:${(await landInDrive(scratch?.file ?? out!, to, credentials(args))).path}`;\n } finally {\n scratch?.cleanup();\n }\n }\n const summary = summarizeRecords(records);\n const print = printLines(ctx, toStdout);\n if (arg.bool(args, \"json\")) {\n print(JSON.stringify({ ...(out ? { out } : {}), ...(landed ? { to: landed } : {}), from, ...inputsField(staged.files, staged.labels), ...summary, skipped, filtered }));\n return 0;\n }\n if (out && !toStdout) print(`wrote ${records.length} records to ${out}`);\n if (landed) print(`wrote ${records.length} records to ${landed}`);\n renderSummary(summary, print);\n const pairs = Object.entries(skipped).sort().map(([k, n]) => `${k} ${n}`);\n if (pairs.length) print(` not converted: ${pairs.join(\", \")}`);\n if (filtered) print(` dropped by --tool: ${filtered}`);\n return 0;\n}\n\n/** The scratch path behind a drive label, or the name itself for a local file. */\nfunction localFor(name: string, files: string[], labels: Record<string, string>): string {\n for (const file of files) if (labels[file] === name) return file;\n return name;\n}\n\n/** `--from drive:<path>`: the record file lives in the drive; the kind is the command's default. */\nfunction driveFrom(args: Parsed): string | null {\n const from = arg.str(args, \"from\");\n return from && isDriveRef(from) ? from : null;\n}\n\n// ---------------------------------------------------------- map init\n\nasync function mapInitCommand(world: string, samples: string[], args: Parsed, ctx: CommandContext): Promise<number> {\n if (!samples.length) throw new CliError(\"ingest map init needs a sample input after the world\");\n const from = (arg.str(args, \"from\") ?? \"tool-calls\") as From;\n if (!FROM.includes(from)) throw new CliError(`--from must be one of ${FROM.join(\", \")}`);\n const kind: MapKind = from === \"rows\" ? \"rows\" : from === \"csv\" ? \"csv\" : \"tool-call\";\n if (!MAP_KINDS.includes(kind)) throw new CliError(`--from ${from}: a mapping reads tool-call, rows or csv records`);\n const local = isDirectory(world);\n const dir = local ? world : await pullWorld(world, credentials(args));\n const config = loadWorldConfig(dir);\n const records = readInputRecords(samples, from, readFileText);\n const text = skeleton(records, config.entities, kind, { sampleName: samples.map((f) => path.basename(f)).join(\", \"), entity: arg.str(args, \"entity\") });\n const out = arg.str(args, \"out\") ?? (local ? path.join(world, MAP_FILE) : \"-\");\n if (out === \"-\") {\n ctx.stdout(text.replace(/\\n$/, \"\"));\n return 0;\n }\n if (fs.existsSync(out) && !arg.bool(args, \"dry-run\")) throw new CliError(`${out} exists; pass --out for another path, or move it first`, 1);\n fs.writeFileSync(out, text);\n ctx.stderr(`wrote ${out}: fill in the entity and fields, then run \\`gateway worlds data ingest ${world} ${samples[0]} --map ${out} --dry-run\\``);\n return 0;\n}\n\n// ---------------------------------------------------------- ingest\n\ntype IngestReport = {\n world: string;\n from: From;\n /** Inputs as named, when any came from the drive. */\n inputs?: string[];\n via?: \"transform\" | \"map\" | \"operations\" | \"rows\";\n records: number;\n ingested: number;\n skipped: Record<string, number>;\n refusals: LocalIngestRefusal[];\n rows: Record<string, number>;\n /** via map: each source's accounting. */\n sources?: LocalIngestSource[];\n /** via map with unmatched = \"skip\": records no source claimed, by tool. */\n unmatched?: Record<string, number>;\n /** via operations: that this was the operation projection, not a mapping. */\n note?: string;\n /** via transform: the script's stderr. */\n stderr?: string;\n /** --from traces through the operation projection: TOOL observations for tools the world does not declare, by name. */\n unknownTools?: Record<string, number>;\n /** --from traces: observations not converted, by reason. */\n notConverted?: Record<string, number>;\n /** --tool: records dropped by the filter. */\n filtered?: number;\n dryRun: boolean;\n redact: RowsRedact;\n changed: boolean;\n kind?: string;\n entityCounts?: Record<string, number>;\n batch?: Record<string, unknown>;\n};\n\nasync function ingestCommand(world: string, inputs: string[], args: Parsed, ctx: CommandContext, labels: Record<string, string> = {}): Promise<number> {\n const from = (driveFrom(args) ? \"tool-calls\" : (arg.str(args, \"from\") ?? \"tool-calls\")) as From;\n if (!FROM.includes(from)) throw new CliError(`--from must be one of ${FROM.join(\", \")}`);\n const transform = arg.str(args, \"transform\");\n const mapFile = arg.str(args, \"map\");\n if (transform !== undefined && mapFile !== undefined) throw new CliError(\"records go through one of --transform, --map\");\n const timeoutSeconds = Number(arg.str(args, \"timeout\") ?? DEFAULT_TRANSFORM_TIMEOUT_MS / 1000);\n if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) throw new CliError(\"--timeout is a positive number of seconds\");\n const redact = rowsRedact(arg.str(args, \"redact\"));\n const mode = rowsMode(arg.str(args, \"mode\"));\n const dryRun = arg.bool(args, \"dry-run\");\n const reportFile = arg.str(args, \"report\");\n const only = new Set(arg.list(args, \"tool\"));\n const local = isDirectory(world);\n if (from !== \"traces\") {\n for (const flag of [\"trace\", \"session\", \"since\"]) if (args.flags[flag] !== undefined) throw new CliError(`--${flag} belongs to --from traces`);\n if (!inputs.length) throw new CliError(\"worlds data ingest needs at least one input file, or --from traces\");\n if (inputs.filter((f) => f === \"-\").length > 1) throw new CliError(\"stdin (-) can be read once\");\n } else if (inputs.length) throw new CliError(\"--from traces reads the platform; drop the input files\");\n\n // Rows already shaped, with nothing declared: the plain import (or check).\n if (from === \"rows\" && transform === undefined && mapFile === undefined && !(local && worldMapping(world))) {\n if (local) return dryRun ? checkLocalDirectory(world, inputs, args, ctx, labels) : importLocalDirectory(world, inputs, args, ctx, labels);\n return importBatch(world, inputs, args, ctx, dryRun ? \"check\" : \"import\", undefined, labels);\n }\n if (from === \"csv\" && transform === undefined && mapFile === undefined && !(local && worldMapping(world))) throw new CliError(\"--from csv needs --transform or --map: a CSV says nothing about which entity or fields its columns are\");\n\n const mapText = mapFile !== undefined ? readMapping(mapFile) : undefined;\n const { toolCallsFromObservations } = await import(\"../../worlds/ingest\");\n const dir = local ? world : await pullWorld(world, credentials(args));\n const declared = transform !== undefined || mapText !== undefined || worldMapping(dir) !== null;\n\n let records: unknown[];\n const out: Partial<IngestReport> = { world, from, ...inputsField(inputs, labels) };\n if (from === \"traces\") {\n const { fetchToolObservations } = await import(\"./worldData/traceCalls\");\n const observations = await fetchToolObservations(credentials(args), { traceIds: arg.list(args, \"trace\"), sessionId: arg.str(args, \"session\"), since: arg.str(args, \"since\") });\n // With a transform or a mapping every tool's calls are the input; the\n // operation projection alone keeps the world's operations and reports the rest.\n const converted = toolCallsFromObservations(observations, {\n tools: declared ? null : Object.keys(loadWorldConfig(dir).operations),\n session: arg.str(args, \"session\"),\n since: arg.str(args, \"since\"),\n });\n records = converted.records;\n if (!declared) out.unknownTools = converted.unknownTools;\n out.notConverted = converted.skipped;\n } else {\n const stdinText = inputs.includes(\"-\") ? await ctx.stdin() : \"\";\n try {\n records = readInputRecords(inputLabels(inputs, labels), from, (name) => (name === \"-\" ? stdinText : readFileText(localFor(name, inputs, labels))));\n } catch (error) {\n if (error instanceof CliError) throw error;\n throw new CliError((error as Error).message, 1);\n }\n }\n if (only.size) {\n const kept = records.filter((r) => typeof r === \"object\" && r !== null && only.has(String((r as { tool?: unknown }).tool)));\n out.filtered = records.length - kept.length;\n records = kept;\n }\n\n const { ingestLocalToolCalls, importLocalWorldData, checkLocalWorldData } = await runtimeData();\n const { credentialsForRuntime } = await import(\"../runtime/local\");\n const { BridgeRejected } = await import(\"../runtime/client\");\n const runtimeCreds = credentialsForRuntime(arg.str(args, \"host\"));\n let projected: Rows = {};\n try {\n if (transform !== undefined) {\n const ran = await runTransform(transform, records, { timeoutMs: timeoutSeconds * 1000 });\n for (const line of ran.stderr.split(\"\\n\")) if (line.trim()) ctx.stderr(`transform: ${line}`);\n projected = ran.rows;\n // A slug is proven locally with redaction off: the batch lane checks\n // every row again on the platform and redacts there.\n const landed =\n local && !dryRun ? await importLocalWorldData(dir, projected, { mode, redact }, runtimeCreds) : await checkLocalWorldData(dir, projected, runtimeCreds, local ? { redact } : {});\n Object.assign(out, {\n via: \"transform\",\n ...(ran.stderr ? { stderr: ran.stderr } : {}),\n records: records.length,\n ingested: records.length,\n skipped: {},\n refusals: [],\n rows: Object.fromEntries(Object.entries(projected).map(([entity, listed]) => [entity, listed.length])),\n dryRun,\n redact,\n changed: local && !dryRun ? landed.changed : false,\n kind: landed.kind,\n entityCounts: landed.entity_counts,\n });\n } else {\n const result = await ingestLocalToolCalls(dir, records, local ? { redact, dryRun, mode, map: mapText } : { redact: \"off\", dryRun: true, mode, map: mapText }, runtimeCreds);\n projected = result.projected ?? {};\n Object.assign(out, {\n ...(result.via ? { via: result.via } : {}),\n ...(result.sources ? { sources: result.sources } : {}),\n ...(result.unmatched ? { unmatched: result.unmatched } : {}),\n ...(result.note ? { note: result.note } : {}),\n records: result.records,\n ingested: result.ingested,\n skipped: result.skipped,\n refusals: result.refusals,\n rows: result.rows,\n dryRun,\n redact,\n changed: result.changed,\n ...(result.kind ? { kind: result.kind } : {}),\n ...(result.entity_counts ? { entityCounts: result.entity_counts } : {}),\n });\n }\n } catch (error) {\n if (!(error instanceof BridgeRejected)) throw error;\n // The contract's own refusal of a produced row: one record, the pointer it names.\n const detail = error.detail;\n Object.assign(out, {\n ...(transform !== undefined ? { via: \"transform\" } : {}),\n records: records.length,\n ingested: 0,\n skipped: {},\n refusals: [{ index: null, tool: null, reason: detail.message, pointer: detail.path ?? detail.schema_path ?? \"/\" }],\n rows: {},\n dryRun,\n redact,\n changed: false,\n });\n }\n const full = out as IngestReport;\n\n let code = full.refusals.length ? 2 : 0;\n if (!local && !dryRun && !full.refusals.length && Object.keys(projected).length) {\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-ingest-rows-\"));\n try {\n const rowsFile = path.join(scratch, \"rows.json\");\n fs.writeFileSync(rowsFile, JSON.stringify(projected));\n code = await importBatch(world, [rowsFile], args, ctx, \"import\", (status) => {\n full.batch = status;\n full.changed = status.state === \"applied\" || status.state === \"published\";\n if (status.entityCounts && typeof status.entityCounts === \"object\") full.entityCounts = status.entityCounts as Record<string, number>;\n });\n } finally {\n fs.rmSync(scratch, { recursive: true, force: true });\n }\n }\n if (reportFile !== undefined) fs.writeFileSync(reportFile, full.refusals.map((r) => JSON.stringify(r) + \"\\n\").join(\"\"));\n if (arg.bool(args, \"json\")) printJson(ctx, full);\n else renderIngest(full, ctx);\n if (dryRun) ctx.stderr(\"dry run: nothing written; drop --dry-run to ingest\");\n return code;\n}\n\nconst pairs = (table: Record<string, number>) =>\n Object.entries(table)\n .sort()\n .map(([key, count]) => `${key} ${count}`)\n .join(\", \");\n\nfunction renderIngest(report: IngestReport, ctx: CommandContext): void {\n const skipped = Object.values(report.skipped).reduce((n, c) => n + c, 0);\n ctx.stdout(`${report.records} records, ${report.ingested} ingested, ${skipped} skipped, ${report.refusals.length} refused` + (report.dryRun ? \" (dry run)\" : \"\") + (report.via ? ` — via ${report.via}` : \"\"));\n for (const [entity, count] of Object.entries(report.rows).sort()) ctx.stdout(` ${entity}: ${count} rows`);\n if (report.note) ctx.stdout(` note: ${report.note}`);\n if (skipped) ctx.stdout(` skipped: ${pairs(report.skipped)}`);\n if (report.unmatched && Object.keys(report.unmatched).length) ctx.stdout(` unmatched (no [[sources]] claimed them, skipped): ${pairs(report.unmatched)}`);\n if (report.unknownTools && Object.keys(report.unknownTools).length) ctx.stdout(` not the world's operations (not converted): ${pairs(report.unknownTools)}`);\n if (report.notConverted && Object.keys(report.notConverted).length) ctx.stdout(` observations not converted: ${pairs(report.notConverted)}`);\n if (report.filtered) ctx.stdout(` dropped by --tool: ${report.filtered}`);\n for (const source of report.sources ?? []) renderSource(source, ctx);\n for (const refusal of report.refusals) ctx.stdout(` refused [${refusal.index ?? \"-\"}] ${refusal.tool ?? refusal.pointer ?? \"-\"}: ${refusal.reason}`);\n if (report.batch) ctx.stdout(` batch ${String(report.batch.batchId ?? \"?\")} ${String(report.batch.state ?? \"?\")}` + (report.batch.versionId ? ` -> version ${String(report.batch.versionId)}` : \"\"));\n if (report.entityCounts) ctx.stdout(` entity counts: ${pairs(report.entityCounts)}`);\n if (report.redact !== \"off\") ctx.stdout(` redact: ${report.redact}`);\n}\n\n/** One mapping source in the dry-run view: what it saw, what it landed, what it left untouched on both sides. */\nfunction renderSource(source: LocalIngestSource, ctx: CommandContext): void {\n ctx.stdout(` source ${source.name} (${source.kind}, select ${source.select}) -> ${source.entity}: ${source.records} records, ${source.items} items` + (Object.keys(source.rows).length ? `, rows ${pairs(source.rows)}` : \", no rows\"));\n const unmapped = Object.entries(source.unmapped_fields);\n if (unmapped.length) ctx.stdout(` unmapped source fields: ${unmapped.map(([name, sample]) => `${name} (${sample})`).join(\", \")}`);\n for (const [entity, fields] of Object.entries(source.unset_fields)) if (fields.length) ctx.stdout(` ${entity} fields never set: ${fields.join(\", \")}`);\n}\n\n// ---------------------------------------------------------- local directories\n\n/** The platform slug a local world would import into: its pulled metadata, else its name. */\nfunction worldSlug(dir: string): string {\n const slug = readLocalMeta(dir)?.slug;\n return typeof slug === \"string\" && slug ? slug : path.basename(path.resolve(dir));\n}\n\n/** The rows for a directory, whole, within the inline cap — or a pointer to the platform world. */\nasync function inlineRows(dir: string, files: string[], args: Parsed, ctx: CommandContext): Promise<Rows> {\n const entity = arg.str(args, \"entity\");\n const tooLarge = () =>\n new CliError(\n `${files.length} file(s) exceed the inline cap (${INLINE_ROWS} rows / ${INLINE_BYTES} bytes) for a directory; ` +\n `import into the platform world \\`${worldSlug(dir)}\\``,\n 1,\n );\n const paths: string[] = [];\n let scratch: string | null = null;\n try {\n let size = 0;\n for (const file of files) {\n if (file === \"-\") {\n scratch ??= fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-stdin-\"));\n const stdin = path.join(scratch, \"stdin.rows\");\n fs.writeFileSync(stdin, await ctx.stdin());\n paths.push(stdin);\n continue;\n }\n if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw new CliError(`Cannot read ${file}`, 1);\n size += fs.statSync(file).size;\n paths.push(file);\n }\n if (size > INLINE_BYTES) throw tooLarge();\n let count = 0;\n for await (const _ of readRows(paths.map(fileInput), entity)) if (++count > INLINE_ROWS) throw tooLarge();\n return parseRows(paths, entity);\n } finally {\n if (scratch) fs.rmSync(scratch, { recursive: true, force: true });\n }\n}\n\nasync function importLocalDirectory(dir: string, files: string[], args: Parsed, ctx: CommandContext, labels: Record<string, string> = {}): Promise<number> {\n const mode = rowsMode(arg.str(args, \"mode\"));\n const redact = rowsRedact(arg.str(args, \"redact\"));\n const rows = await inlineRows(dir, files, args, ctx);\n const { importLocalWorldData } = await runtimeData();\n const { credentialsForRuntime } = await import(\"../runtime/local\");\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n printJson(ctx, { world: dir, ...inputsField(files, labels), ...(await importLocalWorldData(dir, rows, { mode, redact }, creds)) });\n return 0;\n}\n\n/** The bridge's import over the tree, files not written back: a dry run by construction. */\nasync function checkLocalDirectory(dir: string, files: string[], args: Parsed, ctx: CommandContext, labels: Record<string, string> = {}): Promise<number> {\n const rows = await inlineRows(dir, files, args, ctx);\n const count = Object.values(rows).reduce((n, listed) => n + listed.length, 0);\n const { checkLocalWorldData } = await runtimeData();\n const { credentialsForRuntime } = await import(\"../runtime/local\");\n const { BridgeRejected } = await import(\"../runtime/client\");\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const report = arg.str(args, \"report\");\n try {\n const checked = await checkLocalWorldData(dir, rows, creds, { redact: rowsRedact(arg.str(args, \"redact\")) });\n if (report !== undefined) fs.writeFileSync(report, \"\");\n printJson(ctx, { world: dir, ...inputsField(files, labels), dryRun: true, rows: count, refusalCount: 0, refusals: [], entityCounts: checked.entity_counts });\n return 0;\n } catch (error) {\n if (!(error instanceof BridgeRejected)) throw error;\n const refusal = refusalFromBridge(error.detail);\n if (report !== undefined) fs.writeFileSync(report, JSON.stringify(refusal) + \"\\n\");\n printJson(ctx, { world: dir, ...inputsField(files, labels), dryRun: true, rows: count, refusalCount: 1, refusals: [refusal], entityCounts: {} });\n return 2;\n }\n}\n\n/** One refusal record (contract §2) from the bridge's ContractError detail. */\nfunction refusalFromBridge(detail: { code: string; message: string; path?: string }): Record<string, unknown> {\n const pointer = detail.path ?? \"/\";\n const [, entity, index, field] = /^\\/([^/]+)(?:\\/(\\d+))?(?:\\/(.+))?$/.exec(pointer) ?? [];\n return {\n chunk: 0,\n index: index !== undefined ? Number(index) : 0,\n entity: entity ?? null,\n primaryKey: null,\n field: field ?? null,\n pointer,\n detail: detail.message,\n };\n}\n\n/** A slug's tree in a temp dir, for `extract` to read its contract and connector.toml. */\nasync function pullWorld(slugRef: string, creds: Credentials): Promise<string> {\n const target = path.join(fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-world-data-\")), slugOf(slugRef));\n const pulled = await pull(slugRef, target, worldsOptions(creds));\n return pulled.dir;\n}\n\nexport type { BatchStatus };\n","import { api, type Credentials } from \"../../config\";\nimport { CliError, type CommandContext } from \"../../router\";\nimport type { ToolCallRecord } from \"../../../worlds/ingest\";\n\n/**\n * `gateway worlds data calls pull`: raw tool-call records out, untouched, in\n * the record contract `{tool, args, result, at, source}` — and what the agent\n * has before it writes code: records per tool and the distinct result shapes\n * per tool. Traces come through the observations API (`traceCalls.ts`), a\n * world session through its call log, a saved ClickHouse result of TOOL\n * observations through {@link recordsFromClickhouse}.\n */\n\nexport const PULL_FROM = [\"traces\", \"session\", \"clickhouse-result\"] as const;\nexport type PullFrom = (typeof PULL_FROM)[number];\nexport const CLICKHOUSE_COLUMNS = [\"id\", \"trace_id\", \"name\", \"input\", \"output\", \"start_time\"];\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** A saved MCP answer may start with text before the JSON; the document starts at the first `{` or `[`. */\nexport function parseClickhouseText(text: string, where: string): unknown {\n const start = Math.min(...[\"{\", \"[\"].map((c) => text.indexOf(c)).filter((i) => i >= 0));\n if (!Number.isFinite(start)) throw new CliError(`${where}: no JSON document found`, 1);\n try {\n return JSON.parse(text.slice(start));\n } catch {\n throw new CliError(`${where}: not a JSON document from its first { or [`, 1);\n }\n}\n\nfunction decoded(value: unknown, asObject: boolean): unknown {\n if (value === null || value === undefined || value === \"\") return asObject ? {} : null;\n let parsed = value;\n if (typeof value === \"string\") {\n try {\n parsed = JSON.parse(value);\n } catch {\n return { _raw: value };\n }\n }\n if (asObject && !isObject(parsed)) return { _raw: parsed };\n return parsed;\n}\n\nfunction iso(value: unknown): string | undefined {\n if (typeof value !== \"string\" || !value) return undefined;\n const text = value.replace(\" \", \"T\");\n return text.endsWith(\"Z\") || text.slice(10).includes(\"+\") ? text : text + \"Z\";\n}\n\n/**\n * Tool-call records from a saved ClickHouse result of TOOL observations\n * (`{rows|results: [...]}` or the bare list): `name` is the tool, `input` the\n * args and `output` the result (decoded as JSON, or kept whole under `_raw`),\n * `start_time` the time, `trace:<trace_id>/<id>` the source; `level: \"ERROR\"`\n * becomes the record's `error` so ingest skips it, counted. The Python twin is\n * `ingest.records_from_clickhouse`.\n */\nexport function recordsFromClickhouse(document: unknown, where = \"clickhouse\"): ToolCallRecord[] {\n const listed = isObject(document) ? (document.rows ?? document.results) : document;\n if (!Array.isArray(listed)) throw new CliError(`${where}: expected {rows|results: [...]} or a list of observations`, 1);\n return listed.map((row, index) => {\n if (!isObject(row)) throw new CliError(`${where}[${index}] is not an object`, 1);\n if (typeof row.name !== \"string\") throw new CliError(`${where}[${index}] has no name; expected columns ${CLICKHOUSE_COLUMNS.join(\", \")}`, 1);\n const record: ToolCallRecord = { tool: row.name, args: decoded(row.input, true) as Record<string, unknown>, result: decoded(row.output, false) };\n const at = iso(row.start_time);\n if (at !== undefined) record.at = at;\n if (row.trace_id !== undefined && row.trace_id !== null && row.id !== undefined && row.id !== null) record.source = `trace:${String(row.trace_id)}/${String(row.id)}`;\n if (row.level === \"ERROR\") record.error = \"level ERROR\";\n return record;\n });\n}\n\nexport type ToolSummary = { records: number; failed: number; shapes: Record<string, number> };\nexport type CallsSummary = { records: number; tools: Record<string, ToolSummary> };\n\n/** An object's top-level keys, an array's item keys, or the scalar's kind — what a result looks like. */\nexport function resultShape(result: unknown): string {\n if (isObject(result)) return \"{\" + Object.keys(result).sort().join(\", \") + \"}\";\n if (Array.isArray(result)) {\n const keys = new Set<string>();\n for (const item of result) if (isObject(item)) for (const key of Object.keys(item)) keys.add(key);\n return keys.size ? \"[{\" + [...keys].sort().join(\", \") + \"}]\" : `[${result.length} items]`;\n }\n if (result === null || result === undefined) return \"null\";\n return typeof result === \"number\" ? (Number.isInteger(result) ? \"int\" : \"float\") : typeof result === \"boolean\" ? \"bool\" : typeof result === \"string\" ? \"str\" : typeof result;\n}\n\n/** Per tool: how many records, how many failed, and each distinct result shape with its count. */\nexport function summarizeRecords(records: unknown[]): CallsSummary {\n const tools: Record<string, ToolSummary> = {};\n for (const raw of records) {\n if (!isObject(raw) || typeof raw.tool !== \"string\" || !raw.tool) continue;\n const entry = (tools[raw.tool] ??= { records: 0, failed: 0, shapes: {} });\n entry.records += 1;\n if (raw.error !== undefined && raw.error !== null && raw.error !== \"\") entry.failed += 1;\n const shape = resultShape(raw.result);\n entry.shapes[shape] = (entry.shapes[shape] ?? 0) + 1;\n }\n const sorted = Object.fromEntries(Object.entries(tools).sort(([a], [b]) => a.localeCompare(b)));\n return { records: Object.values(tools).reduce((n, t) => n + t.records, 0), tools: sorted };\n}\n\nexport function renderSummary(summary: CallsSummary, print: (line: string) => void): void {\n const toolCount = Object.keys(summary.tools).length;\n print(`${summary.records} records, ${toolCount} tool${toolCount === 1 ? \"\" : \"s\"}`);\n for (const [tool, entry] of Object.entries(summary.tools)) {\n print(` ${tool}: ${entry.records} records` + (entry.failed ? `, ${entry.failed} failed` : \"\"));\n for (const [shape, count] of Object.entries(entry.shapes).sort(([, a], [, b]) => b - a)) print(` result ${shape} (${count})`);\n }\n}\n\nconst SESSION_PAGE = 500;\n\n/** A world session's call log, oldest first, every page (the `worlds session export` request). */\nexport async function fetchSessionCalls(creds: Credentials, sessionId: string): Promise<Record<string, unknown>[]> {\n const calls: Record<string, unknown>[] = [];\n let cursor: string | undefined;\n do {\n const params = new URLSearchParams({ limit: String(SESSION_PAGE) });\n if (cursor) params.set(\"cursor\", cursor);\n const page = await api<{ calls: Record<string, unknown>[]; nextCursor?: string | null }>(\n creds,\n \"GET\",\n `/api/public/world-sessions/${encodeURIComponent(sessionId)}/calls?${params.toString()}`,\n );\n calls.push(...page.calls);\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n return calls;\n}\n\n/** The world session's `call` lines as tool-call records: `completedAt` is the time, the session id the session. */\nexport function recordsFromSessionCalls(calls: Record<string, unknown>[], sessionId: string): { records: ToolCallRecord[]; skipped: Record<string, number> } {\n const records: ToolCallRecord[] = [];\n const skipped: Record<string, number> = {};\n for (const call of calls) {\n if (call.kind !== \"call\") {\n const reason = `kind ${String(call.kind ?? \"unknown\")}`;\n skipped[reason] = (skipped[reason] ?? 0) + 1;\n continue;\n }\n if (typeof call.tool !== \"string\" || !call.tool) {\n skipped[\"no tool\"] = (skipped[\"no tool\"] ?? 0) + 1;\n continue;\n }\n const record: ToolCallRecord = { tool: call.tool, args: isObject(call.args) ? call.args : {}, session: sessionId };\n if (call.error !== undefined && call.error !== null && call.error !== \"\") record.error = String(call.error);\n else record.result = call.result;\n if (typeof call.completedAt === \"string\") record.at = call.completedAt;\n record.source = `session:${sessionId}/${String(call.seq ?? \"?\")}`;\n records.push(record);\n }\n return { records, skipped };\n}\n\nexport function printLines(ctx: CommandContext, toStderr: boolean): (line: string) => void {\n return toStderr ? (line) => ctx.stderr(line) : (line) => ctx.stdout(line);\n}\n","import { CliError } from \"../../router\";\nimport { dumps, isObject, JsonNumber, parseJson, pyRound, pyStr, type JsonObject, type JsonValue } from \"./json\";\nimport { hashForm, shapeText } from \"../../../worlds/redaction\";\nimport { openInput, readLines, readWhole, refuse, rowObject, streamValues, type RowInput } from \"./rowSource\";\nimport type { RedactPolicy, WorldConfig } from \"./worldConfig\";\n\n/**\n * `gateway worlds data extract`: rows out of the shapes agents actually have\n * (contract §12), the same in both CLIs — this is a port of the Python\n * runtime's `extract.py`, decision for decision. An adapter finds candidate\n * rows; then every row loses its null and empty-string fields, loses the\n * fields the entity does not declare (counted, never silent), is skipped\n * when it lacks its primary key, is deduped by that key with `--merge`, and\n * passes through the world's `[redact]` policy. Rows are held for the\n * dedupe; the input is streamed.\n */\n\nexport type Shape = \"vendor-envelope\" | \"tool-results\" | \"session-export\";\nexport const SHAPES: Shape[] = [\"tool-results\", \"vendor-envelope\", \"session-export\"];\n\nexport type Merge = \"fill\" | \"upsert\";\n\nexport type ExtractOptions = {\n shape: Shape;\n entity: string;\n merge: Merge;\n redact: boolean;\n};\n\nexport type ExtractSummary = {\n read: number;\n rows: number;\n unknownFields: Record<string, number>;\n redacted: { dropped: number; hashed: number };\n};\n\nexport async function extractRows(input: RowInput, config: WorldConfig, opts: ExtractOptions, out: (line: string) => void): Promise<ExtractSummary> {\n const entity = config.entities[opts.entity];\n if (!entity) throw new CliError(`Unknown entity ${opts.entity}; the world has ${Object.keys(config.entities).sort().join(\", \")}`, 1);\n const keys = entity.primaryKey;\n const summary: ExtractSummary = { read: 0, rows: 0, unknownFields: {}, redacted: { dropped: 0, hashed: 0 } };\n const held = new Map<string, JsonObject>();\n\n const take = (raw: JsonObject): void => {\n summary.read++;\n const row = clean(raw, entity.fields, summary);\n if (!keys.every((name) => row.has(name))) return;\n const key = dumps(keys.map((name) => row.get(name)!));\n const existing = held.get(key);\n if (!existing) held.set(key, row);\n else if (opts.merge === \"upsert\") held.set(key, row);\n else for (const [name, value] of row) if (!existing.has(name)) existing.set(name, value);\n };\n\n await adapters[opts.shape](input, config, keys, take);\n\n const policy = opts.redact ? config.redact : null;\n for (const row of held.values()) {\n let final = row;\n if (policy) {\n final = redact(row, policy, config.slug ?? \"\") as JsonObject;\n countRedaction(row, final, policy, summary);\n }\n const tagged: JsonObject = new Map();\n tagged.set(\"entity\", opts.entity);\n tagged.set(\"row\", final);\n out(dumps(tagged));\n summary.rows++;\n }\n summary.unknownFields = Object.fromEntries(Object.entries(summary.unknownFields).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));\n return summary;\n}\n\n/** Drop null and \"\" values; strip (and count) fields the entity does not declare. */\nfunction clean(row: JsonObject, declared: Set<string> | null, summary: ExtractSummary): JsonObject {\n const out: JsonObject = new Map();\n for (const [name, value] of row) {\n if (value === null || value === \"\") continue;\n if (declared && !declared.has(name)) {\n summary.unknownFields[name] = (summary.unknownFields[name] ?? 0) + 1;\n continue;\n }\n out.set(name, value);\n }\n return out;\n}\n\n/** The Python `_count_redaction`: top-level fields gone, top-level hash fields hashed. */\nfunction countRedaction(before: JsonObject, after: JsonObject, policy: RedactPolicy, summary: ExtractSummary): void {\n for (const [name, value] of before) {\n if (!after.has(name)) summary.redacted.dropped++;\n else if (policy.hash.includes(name) && value !== null) summary.redacted.hashed++;\n }\n}\n\ntype Take = (candidate: JsonObject) => void;\ntype Adapter = (input: RowInput, config: WorldConfig, keys: string[], take: Take) => Promise<void>;\n\n/** `{..., \"raw_output\": {...}}` per line; rows are `raw_output.results[]` (or `items[]`) carrying the key. */\nconst toolResults: Adapter = async (input, _config, keys, take) => {\n for await (const record of records(input)) {\n if (!isObject(record)) continue;\n const raw = record.get(\"raw_output\");\n if (!isObject(raw)) continue;\n let listed = raw.get(\"results\");\n if (listed === undefined || listed === null) listed = raw.get(\"items\");\n for (const item of objects(listed)) if (keys.every((name) => item.has(name))) take(item);\n }\n};\n\n/** Each line, or the one document, is the vendor's response; rows sit under `[api].envelope`. */\nconst vendorEnvelope: Adapter = async (input, config, _keys, take) => {\n const where = input.name;\n const envelope = config.envelope;\n const opened = await openInput(input, () => true);\n if (!opened) return;\n if (opened.kind === \"array\") {\n if (envelope) throw refuse(`${where} is a bare array but the world's envelope is '${envelope}'`);\n for await (const item of streamValues(opened.bytes, where)) take(rowObject(item.value, item.where));\n return;\n }\n if (opened.kind === \"other\") throw refuse(`${where} is neither a JSON object nor an array`);\n if (!envelope) throw refuse(`${where} is an object but the world's envelope is empty: expected a bare array`);\n if (opened.kind === \"lines\") {\n for await (const response of records(input, opened.lines)) for (const row of objects(dig(response, envelope))) take(row);\n return;\n }\n // One pretty-printed response. A top-level envelope key streams; a dotted one\n // is read whole, as the Python side reads every document of this shape.\n const parts = envelope.split(\".\").filter(Boolean);\n if (parts.length === 1) {\n const top = parts[0]!;\n const values = streamValues(opened.bytes, where, {\n other: (key, value) => {\n if (key === top) for (const row of objects(value)) take(row);\n },\n });\n for await (const item of values) if (item.key === top && isObject(item.value)) take(item.value);\n return;\n }\n const text = await readWhole(opened.bytes);\n let document: JsonValue;\n try {\n document = parseJson(text);\n } catch {\n throw refuse(`${where}: not valid JSON`);\n }\n for (const row of objects(dig(document, envelope))) take(row);\n};\n\n/** `calls.jsonl`: rows are `result.<envelope>[]` of successful `call` records. */\nconst sessionExport: Adapter = async (input, config, _keys, take) => {\n for await (const record of records(input)) {\n if (!isObject(record) || record.get(\"kind\") !== \"call\") continue;\n const error = record.get(\"error\");\n if (error !== null && error !== undefined) continue;\n const result = record.get(\"result\") ?? null;\n for (const row of objects(config.envelope ? dig(result, config.envelope) : result)) take(row);\n }\n};\n\nconst adapters: Record<Shape, Adapter> = {\n \"tool-results\": toolResults,\n \"vendor-envelope\": vendorEnvelope,\n \"session-export\": sessionExport,\n};\n\n/** The Python `_lines`: every non-blank line parsed, numbered from 1. */\nasync function* records(input: RowInput, lines: AsyncIterable<string> = readLines(input)): AsyncGenerator<JsonValue> {\n let number = 0;\n for await (const raw of lines) {\n number++;\n const line = raw.endsWith(\"\\r\") ? raw.slice(0, -1) : raw;\n if (!line.trim()) continue;\n try {\n yield parseJson(line);\n } catch {\n throw refuse(`${input.name}:${number} is not JSON`);\n }\n }\n}\n\n/** The Python `_objects`: the objects of a list, or the one object. */\nfunction objects(value: JsonValue | undefined): JsonObject[] {\n if (Array.isArray(value)) return value.filter(isObject);\n if (isObject(value)) return [value];\n return [];\n}\n\n/** The Python `_dig`: walk a dotted path through objects; null when it is not there. */\nexport function dig(value: JsonValue | undefined, path: string): JsonValue {\n let at: JsonValue | undefined = value;\n for (const part of path.split(\".\").filter(Boolean)) {\n if (!isObject(at) || !at.has(part)) return null;\n at = at.get(part);\n }\n return at ?? null;\n}\n\n// ---------------------------------------------------------------- redaction\n\nconst named = (key: string, here: string, names: string[]): boolean => names.includes(key) || names.includes(here);\n\n/** `\"sha256:\" + sha256(\"<slug>:\" + str(value))`; lists element-wise; objects and null untouched. */\nexport function digest(slug: string, item: JsonValue): JsonValue {\n if (Array.isArray(item)) return item.map((element) => digest(slug, element));\n if (isObject(item) || item === null) return item;\n return hashForm(slug, pyStr(item));\n}\n\n/** The Python `_shaped`: the format-preserving digest; lists element-wise; objects, booleans and null untouched. */\nexport function shaped(slug: string, item: JsonValue): JsonValue {\n if (Array.isArray(item)) return item.map((element) => shaped(slug, element));\n if (isObject(item) || item === null || typeof item === \"boolean\") return item;\n if (typeof item === \"string\") return shapeText(slug, item, \"str\");\n return new JsonNumber(shapeText(slug, pyStr(item), item.isFloat ? \"float\" : \"int\"));\n}\n\n/**\n * The Python runtime's `redact`: a bare name applies at any depth, a dotted\n * path at that place only (`*` for a list item). Hash, drop, preserve or round; the\n * rest recurses untouched.\n */\nexport function redact(value: JsonValue, policy: RedactPolicy, slug: string, path = \"\"): JsonValue {\n if (isObject(value)) {\n const out: JsonObject = new Map();\n for (const [key, item] of value) {\n const here = path ? `${path}.${key}` : key;\n if (named(key, here, policy.drop)) continue;\n if (named(key, here, policy.hash) && item !== null) out.set(key, digest(slug, item));\n else if (named(key, here, policy.preserve) && item !== null) out.set(key, shaped(slug, item));\n else if (key in policy.round && item instanceof JsonNumber) out.set(key, pyRound(item, policy.round[key]!));\n else out.set(key, redact(item, policy, slug, here));\n }\n return out;\n }\n if (Array.isArray(value)) return value.map((item) => redact(item, policy, slug, path ? `${path}.*` : \"*\"));\n return value;\n}\n\n/** `json.dumps(summary)` with Python's default separators and ASCII escaping, for the stderr line. */\nexport function pyDumpsPlain(value: unknown): string {\n if (value === null || value === undefined) return \"null\";\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (typeof value === \"number\") return Number.isInteger(value) ? String(value) : String(value);\n if (typeof value === \"string\") return JSON.stringify(value).replace(/[-￿]/g, (c) => \"\\\\u\" + c.charCodeAt(0).toString(16).padStart(4, \"0\"));\n if (Array.isArray(value)) return \"[\" + value.map(pyDumpsPlain).join(\", \") + \"]\";\n return \"{\" + Object.entries(value as Record<string, unknown>).map(([k, v]) => `${pyDumpsPlain(k)}: ${pyDumpsPlain(v)}`).join(\", \") + \"}\";\n}\n","import * as fs from \"node:fs\";\nimport { Readable } from \"node:stream\";\nimport { createGunzip } from \"node:zlib\";\n\nimport { CliError } from \"../../router\";\nimport { isObject, parseJson, type JsonObject, type JsonValue } from \"./json\";\nimport { ScanError, TopLevelScanner } from \"./scanner\";\n\n/**\n * Rows files as a stream, the way the Python runtime's `iter_file_rows`\n * reads them: the three shapes (a JSON object of entity -> rows, tagged\n * JSONL, bare rows with --entity), refused with the same words, never held\n * whole. The first byte decides between an array and an object; for an\n * object the first line decides between JSONL (it parses as a row) and a\n * document (it does not, or it is longer than `LINE_CAP`), which then\n * streams through the top-level scanner one element at a time. `-` is\n * stdin; a `.gz` path is gunzipped.\n */\n\nexport type TaggedRow = { entity: string; row: JsonObject; where: string };\n\nexport type RowInput = { name: string; open: () => Readable };\n\n/** A first line longer than this is a one-line document, never a JSONL row. */\nexport const LINE_CAP = 1024 * 1024;\n\nexport const refuse = (message: string): CliError => new CliError(message, 1);\n\nexport function fileInput(path: string): RowInput {\n return {\n name: path,\n open: () => {\n const raw = fs.createReadStream(path);\n return path.endsWith(\".gz\") ? raw.pipe(createGunzip()) : raw;\n },\n };\n}\n\nexport async function* readRows(inputs: RowInput[], entity?: string): AsyncGenerator<TaggedRow> {\n for (const input of inputs) yield* readOne(input, entity);\n}\n\n/** How an input reads, decided from its first byte and first line. */\nexport type InputShape =\n | { kind: \"array\"; bytes: AsyncIterable<Buffer> }\n | { kind: \"document\"; bytes: AsyncIterable<Buffer> }\n | { kind: \"lines\"; lines: AsyncIterable<string> }\n | { kind: \"other\" };\n\n/**\n * Open an input and decide its shape; null when it holds only whitespace.\n * `looksLikeRow` says whether a first line that parsed as an object is a\n * JSONL row (then the file is lines) or the start of a document.\n */\nexport async function openInput(input: RowInput, looksLikeRow: (first: JsonObject) => boolean): Promise<InputShape | null> {\n const bytes = openBytes(input);\n const first = await bytes.firstNonWhitespace();\n if (first === null) return null;\n if (first === 0x5b) return { kind: \"array\", bytes: bytes.remaining() };\n if (first !== 0x7b) return { kind: \"other\" };\n const line = await bytes.firstLine(LINE_CAP);\n if (line !== null) {\n let parsed: JsonValue | undefined;\n try {\n parsed = parseJson(line);\n } catch {\n parsed = undefined;\n }\n if (parsed !== undefined && isObject(parsed) && looksLikeRow(parsed)) return { kind: \"lines\", lines: bytes.lines() };\n }\n return { kind: \"document\", bytes: bytes.remaining() };\n}\n\n/** Every line of an input, whatever its first byte (the Python `_lines`). */\nexport function readLines(input: RowInput): AsyncIterable<string> {\n return openBytes(input).lines();\n}\n\n/** The whole input as text — for the one shape the Python side reads whole too. */\nexport async function readWhole(bytes: AsyncIterable<Buffer>): Promise<string> {\n const parts: Buffer[] = [];\n for await (const chunk of bytes) parts.push(chunk);\n return Buffer.concat(parts).toString(\"utf8\");\n}\n\nfunction openBytes(input: RowInput): ByteReader {\n let stream: Readable;\n try {\n stream = input.open();\n } catch {\n throw refuse(`Cannot read ${input.name}`);\n }\n return new ByteReader(stream, input.name);\n}\n\nasync function* readOne(input: RowInput, entity: string | undefined): AsyncGenerator<TaggedRow> {\n const path = input.name;\n const isRow = (parsed: JsonObject) => {\n const keys = [...parsed.keys()];\n if (entity === undefined) return keys.length === 2 && parsed.has(\"entity\") && parsed.has(\"row\");\n return !(keys.length === 1 && keys[0] === entity && Array.isArray(parsed.get(entity)));\n };\n const opened = await openInput(input, isRow);\n if (!opened) return; // blank file: no rows\n if (opened.kind === \"other\") throw refuse(`${path} is neither a JSON object of entity -> rows nor an array of rows`);\n if (opened.kind === \"array\") {\n if (entity === undefined) throw refuse(`${path} is a bare array; say which entity it holds with --entity`);\n for await (const { value, where } of streamValues(opened.bytes, path)) yield { entity, row: rowObject(value, where), where };\n return;\n }\n if (opened.kind === \"lines\") {\n yield* jsonlRows(opened.lines, path, entity);\n return;\n }\n const values = streamValues(opened.bytes, path, {\n key: (key, isArray) => {\n if (!isArray) throw refuse(`${path}: ${key} must map to an array of rows (JSONL lines are {\"entity\", \"row\"})`);\n if (entity !== undefined && key !== entity) throw refuse(`${path} maps entities; drop --entity or make the file a bare array`);\n },\n });\n for await (const { key, value, where } of values) yield { entity: key!, row: rowObject(value, where), where };\n}\n\nexport type StreamedValue = { key: string | null; value: JsonValue; index: number; where: string };\n\n/**\n * The elements of a document as the scanner finds them, parsed: the items of\n * an array document (`key` null), or of each array value of an object\n * document. `hooks.key` sees every object key with whether its value is an\n * array; a non-array value goes whole to `hooks.other`. Content after the\n * document's closing bracket is ignored, as the Python reader ignores it.\n */\nexport async function* streamValues(\n bytes: AsyncIterable<Buffer>,\n path: string,\n hooks: { key?: (key: string, isArray: boolean) => void; other?: (key: string, value: JsonValue) => void } = {},\n): AsyncGenerator<StreamedValue> {\n const queue: StreamedValue[] = [];\n const whereOf = (key: string | null, index: number) => (key === null ? `${path}[${index}]` : `${path}:${key}[${index}]`);\n const scanner = new TopLevelScanner({\n key: (key, isArray) => hooks.key?.(key, isArray),\n element: (key, text, index) => {\n const where = whereOf(key, index);\n queue.push({ key, value: parseElement(text, where), index, where });\n },\n other: (key, text) => hooks.other?.(key, parseElement(text, `${path}:${key}`)),\n });\n try {\n for await (const chunk of bytes) {\n scanner.feed(chunk);\n if (queue.length) yield* queue.splice(0);\n }\n scanner.end();\n } catch (error) {\n if (error instanceof ScanError) throw refuse(`${error.open ? whereOf(error.open.key, error.open.index) : path}: not valid JSON`);\n throw error;\n }\n if (queue.length) yield* queue.splice(0);\n}\n\nfunction parseElement(text: string, where: string): JsonValue {\n try {\n return parseJson(text);\n } catch {\n throw refuse(`${where}: not valid JSON`);\n }\n}\n\n/** JSONL, numbered from the first line as the Python reader numbers them\n * (a blank line counts; the first line is never blank). */\nasync function* jsonlRows(lines: AsyncIterable<string>, path: string, entity: string | undefined): AsyncGenerator<TaggedRow> {\n let number = 0;\n for await (const raw of lines) {\n number++;\n const line = raw.endsWith(\"\\r\") ? raw.slice(0, -1) : raw;\n if (!line.trim()) continue;\n let item: JsonValue;\n try {\n item = parseJson(line);\n } catch {\n throw refuse(`${path}:${number} is not JSON`);\n }\n const where = `${path}:${number}`;\n if (entity !== undefined) {\n yield { entity, row: rowObject(item, where), where };\n continue;\n }\n if (!isObject(item) || item.size !== 2 || !item.has(\"entity\") || !item.has(\"row\") || typeof item.get(\"entity\") !== \"string\")\n throw refuse(`${where}: expected {\"entity\": name, \"row\": {…}} (or pass --entity for bare rows)`);\n yield { entity: item.get(\"entity\") as string, row: rowObject(item.get(\"row\")!, where), where };\n }\n}\n\nexport function rowObject(row: JsonValue, where: string): JsonObject {\n if (!isObject(row)) throw refuse(`${where}: a row must be a JSON object`);\n return row;\n}\n\n// ------------------------------------------------------------ byte reading\n\nconst isWs = (c: number): boolean => c === 0x20 || c === 0x0a || c === 0x0d || c === 0x09;\nconst BOM = Buffer.from([0xef, 0xbb, 0xbf]);\n\n/** A readable's bytes with a re-readable prefix: what the probe consumed is\n * handed back to whichever reader (document scanner, line splitter) follows. */\nclass ByteReader {\n private held: Buffer[] = [];\n private readonly iterator: AsyncIterator<Buffer>;\n private done = false;\n private start = 0; // bytes of leading whitespace (and a BOM) already skipped\n\n constructor(\n stream: Readable,\n private readonly path: string,\n ) {\n this.iterator = stream[Symbol.asyncIterator]() as AsyncIterator<Buffer>;\n }\n\n private async next(): Promise<Buffer | null> {\n if (this.done) return null;\n let result: IteratorResult<Buffer>;\n try {\n result = await this.iterator.next();\n } catch (error) {\n const code = (error as { code?: string }).code;\n throw refuse(code === \"Z_DATA_ERROR\" ? `Cannot read ${this.path} as UTF-8 text` : `Cannot read ${this.path}`);\n }\n if (result.done) {\n this.done = true;\n return null;\n }\n const chunk = result.value;\n return Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as unknown as string, \"utf8\");\n }\n\n private all(): Buffer {\n if (this.held.length > 1) this.held = [Buffer.concat(this.held)];\n return this.held[0] ?? Buffer.alloc(0);\n }\n\n /** The first non-whitespace byte (a leading BOM is whitespace), keeping everything read. */\n async firstNonWhitespace(): Promise<number | null> {\n for (;;) {\n const buf = this.all();\n let i = this.start;\n if (i === 0 && buf.length >= 3 && buf.subarray(0, 3).equals(BOM)) i = 3;\n while (i < buf.length && isWs(buf[i]!)) i++;\n if (i < buf.length) {\n this.start = i;\n return buf[i]!;\n }\n const chunk = await this.next();\n if (chunk === null) return null;\n this.held.push(chunk);\n }\n }\n\n /** The first line from the first non-whitespace byte, without its newline;\n * null when no newline shows up within `cap` bytes (a one-line document). */\n async firstLine(cap: number): Promise<string | null> {\n for (;;) {\n const buf = this.all();\n const at = buf.indexOf(0x0a, this.start);\n if (at !== -1) return buf.subarray(this.start, at).toString(\"utf8\");\n if (buf.length - this.start > cap) return null;\n const chunk = await this.next();\n if (chunk === null) return buf.length > this.start ? buf.subarray(this.start).toString(\"utf8\") : null;\n this.held.push(chunk);\n }\n }\n\n /** Everything from the first non-whitespace byte: the held prefix, then the rest of the stream. */\n async *remaining(): AsyncGenerator<Buffer> {\n const prefix = this.all().subarray(this.start);\n this.held = [];\n this.start = 0;\n if (prefix.length) yield prefix;\n for (;;) {\n const chunk = await this.next();\n if (chunk === null) return;\n yield chunk;\n }\n }\n\n /** Lines split on `\\n` (a trailing `\\r` is the caller's to strip). */\n async *lines(): AsyncGenerator<string> {\n let carry = \"\";\n const decoder = new TextDecoder(\"utf-8\", { fatal: true });\n const decode = (chunk: Buffer | undefined): string => {\n try {\n return chunk ? decoder.decode(chunk, { stream: true }) : decoder.decode();\n } catch {\n throw refuse(`Cannot read ${this.path} as UTF-8 text`);\n }\n };\n for await (const chunk of this.remaining()) {\n const text = carry + decode(chunk);\n const parts = text.split(\"\\n\");\n carry = parts.pop()!;\n yield* parts;\n }\n carry += decode(undefined);\n if (carry) yield carry;\n }\n}\n","/**\n * A byte-level scanner over one top-level JSON document, so a rows file of\n * any size streams: `{\"<key>\": [row, row, …], …}` hands out each element's\n * text as it closes (and each non-array value whole), `[row, row, …]` hands\n * out its elements. Only the current value is ever held. Elements are parsed\n * by the caller (`parseJson`), never here — this only finds their bounds.\n *\n * Structural bytes are ASCII, so slicing on them never splits a UTF-8\n * sequence; strings and escapes are tracked so a `]` inside a string is text.\n */\n\nexport class ScanError extends Error {\n constructor(\n message: string,\n /** The array element that was open when the document ended, if any. */\n readonly open: { key: string | null; index: number } | null = null,\n ) {\n super(message);\n }\n}\n\nexport type ScanEvents = {\n /** The document's first byte decided its shape. */\n shape?: (shape: \"object\" | \"array\") => void;\n /** An object key, as soon as its value's first byte says whether it is an array. */\n key?: (key: string, isArray: boolean) => void;\n /** An element of a depth-1 array (`key` null for an array document). */\n element: (key: string | null, text: string, index: number) => void;\n /** A depth-1 object value that is not an array, whole. */\n other?: (key: string, text: string) => void;\n /** The top-level value closed; anything but whitespace after it is `trailing`. */\n end?: (trailing: boolean) => void;\n};\n\ntype Mode =\n | \"start\"\n | \"objKey\"\n | \"objColon\"\n | \"objValue\"\n | \"objAfterValue\"\n | \"arrElem\"\n | \"arrAfterElem\"\n | \"done\"\n | \"trailing\"\n | \"notDocument\";\n\ntype Capture = { kind: \"string\" | \"container\" | \"scalar\"; depth: number; inString: boolean; escape: boolean };\n\nconst WS = new Set([0x20, 0x0a, 0x0d, 0x09]);\n\nexport class TopLevelScanner {\n private mode: Mode = \"start\";\n private pending: Buffer = Buffer.alloc(0);\n private cursor = 0; // scan position inside pending\n private captureStart = -1;\n private capture: Capture | null = null;\n private key: string | null = null;\n private index = 0;\n private afterKey: \"objColon\" | null = null;\n /** True when the first byte said this is not an object or array document. */\n notDocument = false;\n\n constructor(private readonly events: ScanEvents) {}\n\n feed(chunk: Buffer): void {\n if (this.mode === \"notDocument\" || this.mode === \"trailing\") return;\n this.pending = this.pending.length ? Buffer.concat([this.pending, chunk]) : chunk;\n this.scan();\n }\n\n end(): void {\n if (this.mode === \"notDocument\" || this.mode === \"trailing\") return;\n this.scan();\n if (this.mode === \"start\") return; // blank input: no document at all\n if (this.mode !== \"done\")\n throw new ScanError(\"Unexpected end of document\", this.capture && (this.mode === \"arrElem\" || this.mode === \"arrAfterElem\") ? { key: this.key, index: this.index } : null);\n this.events.end?.(false);\n }\n\n private scan(): void {\n const buf = this.pending;\n while (this.cursor < buf.length) {\n if (this.capture) {\n if (!this.advanceCapture(buf)) return;\n continue;\n }\n const c = buf[this.cursor]!;\n if (WS.has(c) && this.mode !== \"trailing\") {\n this.cursor++;\n continue;\n }\n switch (this.mode) {\n case \"start\":\n if (c === 0x7b) {\n this.mode = \"objKey\";\n this.events.shape?.(\"object\");\n } else if (c === 0x5b) {\n this.mode = \"arrElem\";\n this.events.shape?.(\"array\");\n } else {\n this.mode = \"notDocument\";\n this.notDocument = true;\n return;\n }\n this.cursor++;\n break;\n case \"objKey\":\n if (c === 0x7d) {\n this.cursor++;\n this.finish();\n break;\n }\n if (c !== 0x22) throw new ScanError(\"Expecting property name enclosed in double quotes\");\n this.beginCapture(\"string\");\n this.afterKey = \"objColon\";\n break;\n case \"objColon\":\n if (c !== 0x3a) throw new ScanError(\"Expecting ':' delimiter\");\n this.cursor++;\n this.mode = \"objValue\";\n break;\n case \"objValue\":\n this.events.key?.(this.key!, c === 0x5b);\n if (c === 0x5b) {\n this.cursor++;\n this.index = 0;\n this.mode = \"arrElem\";\n } else this.beginCapture(c === 0x22 ? \"string\" : c === 0x7b ? \"container\" : \"scalar\");\n break;\n case \"objAfterValue\":\n if (c === 0x2c) {\n this.cursor++;\n this.mode = \"objKey\";\n } else if (c === 0x7d) {\n this.cursor++;\n this.finish();\n } else throw new ScanError(\"Expecting ',' delimiter\");\n break;\n case \"arrElem\":\n if (c === 0x5d) {\n this.cursor++;\n this.closeArray();\n } else this.beginCapture(c === 0x22 ? \"string\" : c === 0x7b || c === 0x5b ? \"container\" : \"scalar\");\n break;\n case \"arrAfterElem\":\n if (c === 0x2c) {\n this.cursor++;\n this.mode = \"arrElem\";\n } else if (c === 0x5d) {\n this.cursor++;\n this.closeArray();\n } else throw new ScanError(\"Expecting ',' delimiter\");\n break;\n case \"done\":\n this.mode = \"trailing\";\n this.events.end?.(true);\n return;\n default:\n return;\n }\n }\n // Everything before the capture start is consumed; keep only the open capture.\n if (this.capture) {\n this.pending = buf.subarray(this.captureStart);\n this.cursor -= this.captureStart;\n this.captureStart = 0;\n } else {\n this.pending = Buffer.alloc(0);\n this.cursor = 0;\n }\n }\n\n private beginCapture(kind: Capture[\"kind\"]): void {\n this.captureStart = this.cursor;\n this.capture = { kind, depth: 0, inString: kind === \"string\", escape: false };\n if (kind === \"string\") this.cursor++;\n }\n\n /** Advance the open capture; true when it closed. */\n private advanceCapture(buf: Buffer): boolean {\n const cap = this.capture!;\n while (this.cursor < buf.length) {\n const c = buf[this.cursor]!;\n if (cap.inString) {\n if (cap.escape) cap.escape = false;\n else if (c === 0x5c) cap.escape = true;\n else if (c === 0x22) {\n cap.inString = false;\n if (cap.kind === \"string\") {\n this.cursor++;\n this.closeCapture(buf);\n return true;\n }\n }\n this.cursor++;\n continue;\n }\n if (cap.kind === \"scalar\") {\n if (c === 0x2c || c === 0x5d || c === 0x7d || WS.has(c)) {\n this.closeCapture(buf);\n return true;\n }\n this.cursor++;\n continue;\n }\n // container\n if (c === 0x22) cap.inString = true;\n else if (c === 0x7b || c === 0x5b) cap.depth++;\n else if (c === 0x7d || c === 0x5d) {\n cap.depth--;\n if (cap.depth === 0) {\n this.cursor++;\n this.closeCapture(buf);\n return true;\n }\n }\n this.cursor++;\n }\n return false;\n }\n\n private closeCapture(buf: Buffer): void {\n const text = buf.subarray(this.captureStart, this.cursor);\n this.capture = null;\n this.captureStart = -1;\n if (this.afterKey) {\n this.key = decodeKey(text);\n this.afterKey = null;\n this.mode = \"objColon\";\n return;\n }\n if (this.mode === \"objValue\") {\n this.events.other?.(this.key!, text.toString(\"utf8\"));\n this.mode = \"objAfterValue\";\n return;\n }\n // an array element\n this.events.element(this.key, text.toString(\"utf8\"), this.index++);\n this.mode = \"arrAfterElem\";\n }\n\n private closeArray(): void {\n if (this.key === null) this.finish();\n else this.mode = \"objAfterValue\";\n }\n\n private finish(): void {\n this.mode = \"done\";\n this.key = null;\n }\n}\n\nfunction decodeKey(text: Buffer): string {\n const raw = text.toString(\"utf8\");\n try {\n return JSON.parse(raw) as string;\n } catch {\n throw new ScanError(\"Invalid property name\");\n }\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../../router\";\nimport { pyDumpsPlain } from \"./extract\";\nimport { parseToml, TomlError } from \"./toml\";\nimport type { EntityInfo } from \"./worldConfig\";\n\n/**\n * `ingest.toml` on the CLI side: the file is read and checked to be TOML here\n * and interpreted by the schema runtime (the Python `schema.mapping`, where\n * the grammar and the checks against the contract live). `skeleton` is the\n * twin of the Python `mapping.skeleton`, line for line: what `map init`\n * writes.\n */\n\nexport const MAP_FILE = \"ingest.toml\";\nexport const MAP_KINDS = [\"tool-call\", \"rows\", \"csv\"] as const;\nexport type MapKind = (typeof MAP_KINDS)[number];\nconst SAMPLE_WIDTH = 48;\n\n/** The mapping file's text, refused when it is not TOML; the runtime judges the rest. */\nexport function readMapping(file: string): string {\n if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw new CliError(`no mapping file at ${file}`, 1);\n const text = fs.readFileSync(file, \"utf8\");\n try {\n parseToml(text);\n } catch (error) {\n if (error instanceof TomlError) throw new CliError(`${file}: ${error.message}`, 1);\n throw error;\n }\n return text;\n}\n\n/** The world's own `ingest.toml`, when it has one. */\nexport function worldMapping(dir: string): string | null {\n const file = path.join(dir, MAP_FILE);\n return fs.existsSync(file) ? fs.readFileSync(file, \"utf8\") : null;\n}\n\nconst isObject = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** A value as a short string for the report: JSON, cut to `SAMPLE_WIDTH`; a list by its length. */\nexport function sample(value: unknown): string {\n if (Array.isArray(value)) return `[${value.length} items]`;\n const text = pyDumpsPlain(value);\n return text.length <= SAMPLE_WIDTH ? text : text.slice(0, SAMPLE_WIDTH - 1) + \"…\";\n}\n\ntype Observed = Record<string, { sample: string; nested: Observed; list: boolean }>;\n\n/** Top-level fields with a first sample each; a nested object, or a list of objects, is described one level down. */\nfunction observe(shapes: Observed, value: unknown): void {\n const items = Array.isArray(value) ? value : [value];\n for (const item of items) {\n if (!isObject(item)) continue;\n for (const [key, inner] of Object.entries(item)) {\n shapes[key] ??= { sample: sample(inner), nested: {}, list: Array.isArray(inner) };\n if (isObject(inner) || (Array.isArray(inner) && inner.length && inner.every(isObject))) observe(shapes[key].nested, inner);\n }\n }\n}\n\nfunction shapeOf(value: unknown): string {\n if (isObject(value)) return \"an object\";\n if (Array.isArray(value)) return value.length && value.every(isObject) ? \"an array of objects\" : \"an array\";\n if (value === null || value === undefined) return \"null\";\n return typeof value === \"number\" ? (Number.isInteger(value) ? \"int\" : \"float\") : typeof value === \"boolean\" ? \"bool\" : typeof value === \"string\" ? \"str\" : typeof value;\n}\n\nfunction describe(lines: string[], fields: Observed, title: string, indent: string): void {\n if (!Object.keys(fields).length) return;\n lines.push(`# ${indent}${title}:`);\n for (const [name, info] of Object.entries(fields)) {\n lines.push(`# ${indent}${name} = ${info.sample}`);\n if (Object.keys(info.nested).length) describe(lines, info.nested, `${name}${info.list ? \"[*]\" : \"\"} fields`, indent + \" \");\n }\n}\n\nconst sortedFields = (entity: EntityInfo): string[] => [...(entity.fields ?? [])].sort();\n\n/**\n * The `ingest.toml` `map init` writes: one `[[sources]]` per source shape in\n * the sample (per tool for tool-call records; the one `*` shape otherwise),\n * every source field with a sample value on one side, every entity field on\n * the other. A field is written only for an exact-name match, marked to\n * confirm; every other entity field is a commented line. Nothing else is\n * guessed.\n */\nexport function skeleton(\n records: unknown[],\n entities: Record<string, EntityInfo>,\n kind: MapKind,\n opts: { sampleName?: string; entity?: string } = {},\n): string {\n const names = Object.keys(entities).sort();\n if (opts.entity !== undefined && !(opts.entity in entities)) throw new CliError(`unknown entity ${opts.entity}; the world has ${names.join(\", \")}`, 1);\n const chosen = opts.entity ?? (names.length === 1 ? names[0] : undefined);\n type Group = { count: number; shapes: Record<string, number>; fields: Observed; args: Observed };\n const groups = new Map<string, Group>();\n const groupFor = (name: string): Group => {\n let group = groups.get(name);\n if (!group) groups.set(name, (group = { count: 0, shapes: {}, fields: {}, args: {} }));\n return group;\n };\n for (const raw of records) {\n if (!isObject(raw)) continue;\n if (kind === \"tool-call\") {\n if (typeof raw.tool !== \"string\" || !raw.tool) continue;\n const group = groupFor(raw.tool);\n group.count += 1;\n const shape = shapeOf(raw.result);\n group.shapes[shape] = (group.shapes[shape] ?? 0) + 1;\n observe(group.fields, raw.result);\n observe(group.args, isObject(raw.args) ? raw.args : {});\n } else {\n const group = groupFor(\"*\");\n group.count += 1;\n observe(group.fields, raw);\n }\n }\n const lines = [\n `# ${MAP_FILE} — written by \\`gateway worlds data ingest map init\\` from ${opts.sampleName ?? \"the sample\"}.`,\n \"# Nothing here is inferred: a field is pre-filled only when a source field has exactly the\",\n \"# entity field's name, and each such line is marked to confirm. Fill the rest, delete what does\",\n \"# not apply, then run `gateway worlds data ingest <world> <input> --map ingest.toml --dry-run`.\",\n \"\",\n \"[ingest]\",\n 'on_conflict = \"latest\"',\n 'unmatched = \"refuse\"',\n ];\n for (const [name, group] of groups) {\n lines.push(\"\");\n const label = kind === \"tool-call\" ? `tool \"${name}\"` : `every ${kind} record`;\n lines.push(`# ── source shape: ${label} (${group.count} records)`);\n if (kind === \"tool-call\") {\n const shapes = Object.entries(group.shapes)\n .map(([shape, count]) => `${shape} (${count})`)\n .join(\", \");\n lines.push(`# result is ${shapes}`);\n }\n describe(lines, group.fields, \"source fields (sample value)\", \"\");\n if (kind === \"tool-call\" && Object.keys(group.args).length) describe(lines, group.args, 'args fields (select = \"args\" to map them)', \"\");\n let select = kind === \"tool-call\" ? \"result\" : \"$record\";\n const shapeNames = Object.keys(group.shapes);\n if (kind === \"tool-call\" && shapeNames.length && shapeNames.every((shape) => shape === \"an array of objects\")) select = \"result[*]\";\n lines.push(\"[[sources]]\", `name = \"${name}\"`, `kind = \"${kind}\"`, `select = \"${select}\"`);\n lines.push(chosen ? `entity = \"${chosen}\"` : `entity = \"\" # one of: ${names.join(\", \")}`);\n lines.push(\"[sources.fields]\");\n const sourceFields = new Set(Object.keys(group.fields));\n for (const target of chosen ? [chosen] : names) {\n if (!chosen) lines.push(`# ${target}:`);\n for (const field of sortedFields(entities[target]!)) {\n const prefix = chosen ? \"\" : `${target}.`;\n if (sourceFields.has(field)) {\n const line = `${prefix}${field} = \"${field}\" # exact-name match — confirm`;\n lines.push(chosen ? line : `# ${line}`);\n } else lines.push(`# ${prefix}${field} = \"\"`);\n }\n }\n }\n lines.push(\"\");\n return lines.join(\"\\n\");\n}\n","/**\n * A minimal TOML reader for what `data extract` needs from a world's\n * `connector.toml`: `[connector] slug`, the `[redact]` lists (`hash`, `drop`)\n * and map (`round`, inline or as `[redact.round]`), and `[api] envelope` /\n * `hits_key`. The package carries no TOML dependency (the Python side reads\n * the file with `tomllib`), so this covers: tables and dotted tables,\n * arrays of tables (their keys are kept under the array), key = value with\n * basic and literal strings, integers, floats, booleans, arrays (multi-line\n * too) and inline tables, and `#` comments. It does not cover multi-line\n * strings, dotted keys, dates, or exotic escapes; a connector.toml that uses\n * them keeps those values out of reach here, nothing more.\n */\n\nexport type TomlValue = string | number | boolean | TomlValue[] | TomlTable;\nexport type TomlTable = { [key: string]: TomlValue };\n\nexport class TomlError extends Error {}\n\nexport function parseToml(text: string): TomlTable {\n const root: TomlTable = {};\n let current: TomlTable = root;\n const lines = joinContinuations(text);\n for (const [number, rawLine] of lines.entries()) {\n const line = stripComment(rawLine).trim();\n if (!line) continue;\n const arrayTable = /^\\[\\[\\s*([^\\]]+?)\\s*\\]\\]$/.exec(line);\n if (arrayTable) {\n const parent = tableAt(root, keyPath(arrayTable[1]!).slice(0, -1));\n const name = keyPath(arrayTable[1]!).at(-1)!;\n const list = (parent[name] ??= []) as TomlValue[];\n if (!Array.isArray(list)) throw new TomlError(`line ${number + 1}: ${name} is not an array of tables`);\n current = {};\n list.push(current);\n continue;\n }\n const table = /^\\[\\s*([^\\]]+?)\\s*\\]$/.exec(line);\n if (table) {\n current = tableAt(root, keyPath(table[1]!));\n continue;\n }\n const eq = line.indexOf(\"=\");\n if (eq === -1) throw new TomlError(`line ${number + 1}: expected key = value`);\n const key = unquoteKey(line.slice(0, eq).trim());\n const [value, rest] = readValue(line.slice(eq + 1).trim(), number + 1);\n if (rest.trim()) throw new TomlError(`line ${number + 1}: unexpected text after value`);\n current[key] = value;\n }\n return root;\n}\n\n/** `[a.b]` -> [\"a\", \"b\"], quoted segments allowed. */\nfunction keyPath(header: string): string[] {\n return header.split(\".\").map((part) => unquoteKey(part.trim()));\n}\n\nfunction unquoteKey(key: string): string {\n if ((key.startsWith('\"') && key.endsWith('\"')) || (key.startsWith(\"'\") && key.endsWith(\"'\"))) return key.slice(1, -1);\n return key;\n}\n\nfunction tableAt(root: TomlTable, parts: string[]): TomlTable {\n let node: TomlTable = root;\n for (const part of parts) {\n const next = (node[part] ??= {});\n if (Array.isArray(next)) {\n // [a.b] after [[a]] addresses the latest a\n const last = next[next.length - 1];\n if (!last || typeof last !== \"object\" || Array.isArray(last)) throw new TomlError(`${part} is not a table`);\n node = last;\n } else if (typeof next !== \"object\") throw new TomlError(`${part} is not a table`);\n else node = next;\n }\n return node;\n}\n\n/** Arrays and inline tables may span lines: join until brackets balance outside strings. */\nfunction joinContinuations(text: string): string[] {\n const out: string[] = [];\n let pending = \"\";\n let depth = 0;\n for (const physical of text.split(/\\r?\\n/)) {\n const raw = stripComment(physical);\n const line = pending ? pending + \"\\n\" + raw : raw;\n depth = bracketDepth(line);\n if (depth > 0) {\n pending = line;\n continue;\n }\n pending = \"\";\n out.push(line);\n }\n if (pending) out.push(pending);\n return out;\n}\n\nfunction bracketDepth(line: string): number {\n let depth = 0;\n let quote: string | null = null;\n for (let i = 0; i < line.length; i++) {\n const c = line[i]!;\n if (quote) {\n if (c === \"\\\\\" && quote === '\"') i++;\n else if (c === quote) quote = null;\n continue;\n }\n if (c === '\"' || c === \"'\") quote = c;\n else if (c === \"[\" || c === \"{\") depth++;\n else if (c === \"]\" || c === \"}\") depth--;\n }\n return depth;\n}\n\nfunction stripComment(line: string): string {\n let quote: string | null = null;\n for (let i = 0; i < line.length; i++) {\n const c = line[i]!;\n if (quote) {\n if (c === \"\\\\\" && quote === '\"') i++;\n else if (c === quote) quote = null;\n continue;\n }\n if (c === '\"' || c === \"'\") quote = c;\n else if (c === \"#\") return line.slice(0, i);\n }\n return line;\n}\n\n/** Read one value at the start of `text`; returns it and what follows. */\nfunction readValue(text: string, line: number): [TomlValue, string] {\n const s = text.trimStart();\n if (s.startsWith('\"')) {\n let out = \"\";\n for (let i = 1; i < s.length; i++) {\n const c = s[i]!;\n if (c === \"\\\\\") {\n const e = s[++i];\n const map: Record<string, string> = { n: \"\\n\", t: \"\\t\", r: \"\\r\", '\"': '\"', \"\\\\\": \"\\\\\", b: \"\\b\", f: \"\\f\" };\n if (e === \"u\" || e === \"U\") {\n const width = e === \"u\" ? 4 : 8;\n out += String.fromCodePoint(parseInt(s.slice(i + 1, i + 1 + width), 16));\n i += width;\n } else if (e !== undefined && e in map) out += map[e];\n else throw new TomlError(`line ${line}: unsupported escape \\\\${e ?? \"\"}`);\n continue;\n }\n if (c === '\"') return [out, s.slice(i + 1)];\n out += c;\n }\n throw new TomlError(`line ${line}: unterminated string`);\n }\n if (s.startsWith(\"'\")) {\n const end = s.indexOf(\"'\", 1);\n if (end === -1) throw new TomlError(`line ${line}: unterminated string`);\n return [s.slice(1, end), s.slice(end + 1)];\n }\n if (s.startsWith(\"[\")) {\n const items: TomlValue[] = [];\n let rest = s.slice(1);\n for (;;) {\n rest = rest.replace(/^[\\s\\n]+/, \"\");\n if (rest.startsWith(\"]\")) return [items, rest.slice(1)];\n const [item, after] = readValue(rest, line);\n items.push(item);\n rest = after.replace(/^[\\s\\n]+/, \"\");\n if (rest.startsWith(\",\")) rest = rest.slice(1);\n else if (!rest.startsWith(\"]\")) throw new TomlError(`line ${line}: expected , or ] in array`);\n }\n }\n if (s.startsWith(\"{\")) {\n const table: TomlTable = {};\n let rest = s.slice(1);\n for (;;) {\n rest = rest.replace(/^[\\s\\n]+/, \"\");\n if (rest.startsWith(\"}\")) return [table, rest.slice(1)];\n const eq = rest.indexOf(\"=\");\n if (eq === -1) throw new TomlError(`line ${line}: expected key = value in inline table`);\n const key = unquoteKey(rest.slice(0, eq).trim());\n const [value, after] = readValue(rest.slice(eq + 1), line);\n table[key] = value;\n rest = after.replace(/^[\\s\\n]+/, \"\");\n if (rest.startsWith(\",\")) rest = rest.slice(1);\n else if (!rest.startsWith(\"}\")) throw new TomlError(`line ${line}: expected , or } in inline table`);\n }\n }\n const scalar = /^([^,\\]}\\s]+)/.exec(s);\n if (!scalar) throw new TomlError(`line ${line}: expected a value`);\n const token = scalar[1]!;\n const rest = s.slice(token.length);\n if (token === \"true\") return [true, rest];\n if (token === \"false\") return [false, rest];\n if (/^[+-]?\\d[\\d_]*$/.test(token)) return [Number(token.replace(/_/g, \"\")), rest];\n if (/^[+-]?(\\d[\\d_]*)?\\.?\\d[\\d_]*([eE][+-]?\\d+)?$/.test(token)) return [Number(token.replace(/_/g, \"\")), rest];\n throw new TomlError(`line ${line}: unsupported value ${token}`);\n}\n","import * as fs from \"node:fs\";\n\nimport { CliError } from \"../../router\";\nimport { toolCallRecordsIn } from \"../../../worlds/ingest\";\n\n/**\n * Records out of files, as `--from` says they are shaped (the Python\n * `ingest.read_input`): tool-call records (JSONL or a JSON array; a session\n * export line as it is), rows (JSON objects — a JSONL of objects, a JSON array,\n * or one JSON object, which stays one record: a saved query result selects\n * `rows[*]` in the mapping), or CSV (a header row names the fields; every\n * cell is text, an empty cell null, until a mapping's `type` says otherwise).\n */\n\nexport const FROM = [\"tool-calls\", \"traces\", \"rows\", \"csv\"] as const;\nexport type From = (typeof FROM)[number];\n\nexport function readInputRecords(files: string[], from: From, readText: (file: string) => string): unknown[] {\n const records: unknown[] = [];\n for (const file of files) {\n const text = readText(file);\n if (from === \"tool-calls\" || from === \"traces\") {\n records.push(...toolCallRecordsIn(text, file));\n continue;\n }\n if (from === \"csv\") {\n records.push(...parseCsv(text, file));\n continue;\n }\n const stripped = text.trim();\n if (!stripped) continue;\n if (stripped.startsWith(\"{\")) {\n try {\n records.push(JSON.parse(stripped));\n continue;\n } catch {\n // several objects, one per line\n }\n }\n records.push(...toolCallRecordsIn(text, file));\n }\n return records;\n}\n\nexport const readFileText = (file: string): string => {\n if (!fs.existsSync(file) || !fs.statSync(file).isFile()) throw new CliError(`Cannot read ${file}`, 1);\n return fs.readFileSync(file, \"utf8\");\n};\n\n/** RFC 4180: quoted cells, `\"\"` escapes, CRLF or LF; the first row names the columns. */\nexport function parseCsv(text: string, where: string): Record<string, string | null>[] {\n const rows = csvRows(text);\n if (!rows.length) return [];\n const header = rows[0]!;\n if (header.some((name) => !name.trim())) throw new CliError(`${where}: the first row must name every column`, 1);\n const out: Record<string, string | null>[] = [];\n rows.slice(1).forEach((cells, index) => {\n if (cells.length === 1 && cells[0] === \"\") return; // a blank line\n if (cells.length > header.length) throw new CliError(`${where}:${index + 2} has more cells than the header names`, 1);\n const record: Record<string, string | null> = {};\n header.forEach((name, position) => {\n const cell = cells[position];\n record[name] = cell === undefined || cell === \"\" ? null : cell;\n });\n out.push(record);\n });\n return out;\n}\n\nfunction csvRows(text: string): string[][] {\n const rows: string[][] = [];\n let row: string[] = [];\n let cell = \"\";\n let quoted = false;\n for (let i = 0; i < text.length; i++) {\n const c = text[i]!;\n if (quoted) {\n if (c === '\"') {\n if (text[i + 1] === '\"') {\n cell += '\"';\n i++;\n } else quoted = false;\n } else cell += c;\n continue;\n }\n if (c === '\"') quoted = true;\n else if (c === \",\") {\n row.push(cell);\n cell = \"\";\n } else if (c === \"\\n\" || c === \"\\r\") {\n if (c === \"\\r\" && text[i + 1] === \"\\n\") i++;\n row.push(cell);\n rows.push(row);\n row = [];\n cell = \"\";\n } else cell += c;\n }\n if (cell !== \"\" || row.length) {\n row.push(cell);\n rows.push(row);\n }\n return rows;\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../../router\";\n\n/**\n * The client manifest of an import, `.gateway/imports/<batchId>.json` in the\n * working directory: what was sent, chunk by chunk, so `--resume` after a\n * dropped connection re-opens the same batch and skips what was already\n * uploaded. The schema is shared with the Python CLI (contract §10) and so is\n * the layout: `.gateway/` carries its own `.gitignore` (`*`) so the manifests\n * never enter a repository, whichever CLI created the directory.\n */\n\nexport type ManifestFlags = {\n mode: \"append\" | \"replace\";\n merge: \"upsert\" | \"fill\";\n /** Absent on manifests written before the flag existed: off. */\n redact?: \"off\" | \"apply\" | \"refuse\";\n atomic: boolean;\n publish: \"now\" | \"later\";\n dryRun: boolean;\n chunkBytes: number;\n chunkRows: number | null;\n entity: string | null;\n};\n\nexport type ManifestChunk = {\n ordinal: number;\n digest: string;\n bytes: number;\n rows: number;\n entity: string | null;\n chunkId: string | null;\n uploaded: boolean;\n};\n\nexport type Manifest = {\n version: 1;\n batchId: string;\n slug: string;\n host: string;\n flags: ManifestFlags;\n inputs: string[];\n chunks: ManifestChunk[];\n completed: boolean;\n createdAt: string;\n updatedAt: string;\n};\n\nexport const MANIFEST_DIR = path.join(\".gateway\", \"imports\");\n\nexport function manifestDir(cwd = process.cwd()): string {\n return path.join(cwd, MANIFEST_DIR);\n}\n\nexport function manifestPath(batchId: string, cwd = process.cwd()): string {\n if (!/^[A-Za-z0-9_-]+$/.test(batchId)) throw new CliError(`Not a batch id: ${batchId}`);\n return path.join(manifestDir(cwd), `${batchId}.json`);\n}\n\n/** `2026-09-11T23:00:00Z`: seconds, UTC, as the Python CLI stamps it. */\nexport const stamp = (): string => new Date().toISOString().replace(/\\.\\d{3}Z$/, \"Z\");\n\nexport function newManifest(fields: Omit<Manifest, \"version\" | \"chunks\" | \"completed\" | \"createdAt\" | \"updatedAt\">): Manifest {\n const now = stamp();\n return { version: 1, ...fields, chunks: [], completed: false, createdAt: now, updatedAt: now };\n}\n\n/** Write atomically (rename over), stamping `updatedAt`; creates the directory and its gitignore. */\nexport function writeManifest(manifest: Manifest, cwd = process.cwd()): string {\n const file = manifestPath(manifest.batchId, cwd);\n fs.mkdirSync(path.dirname(file), { recursive: true });\n const ignore = path.join(cwd, \".gateway\", \".gitignore\");\n if (!fs.existsSync(ignore)) fs.writeFileSync(ignore, \"*\\n\");\n manifest.updatedAt = stamp();\n const tmp = `${file}.tmp`;\n fs.writeFileSync(tmp, JSON.stringify(manifest, null, 1) + \"\\n\");\n fs.renameSync(tmp, file);\n return file;\n}\n\nexport function readManifest(batchId: string, cwd = process.cwd()): Manifest | null {\n try {\n const parsed = JSON.parse(fs.readFileSync(manifestPath(batchId, cwd), \"utf8\")) as Manifest;\n return parsed && parsed.version === 1 && parsed.batchId === batchId ? parsed : null;\n } catch {\n return null;\n }\n}\n\n/** Record a chunk's registration/upload state by ordinal (replacing an earlier entry). */\nexport function recordChunk(manifest: Manifest, chunk: ManifestChunk): void {\n manifest.chunks = [...manifest.chunks.filter((c) => c.ordinal !== chunk.ordinal), chunk].sort((a, b) => a.ordinal - b.ordinal);\n}\n\n/** The manifest's entry for this chunk when it was already uploaded (same ordinal and digest). */\nexport function uploadedEntry(manifest: Manifest, ordinal: number, digest: string): ManifestChunk | null {\n return manifest.chunks.find((c) => c.ordinal === ordinal && c.digest === digest && c.uploaded) ?? null;\n}\n\n/** Every manifest in the working directory, newest first. */\nexport function listManifests(cwd = process.cwd()): Manifest[] {\n const dir = manifestDir(cwd);\n if (!fs.existsSync(dir)) return [];\n const out: Manifest[] = [];\n for (const name of fs.readdirSync(dir)) {\n if (!name.endsWith(\".json\")) continue;\n const manifest = readManifest(name.slice(0, -5), cwd);\n if (manifest) out.push(manifest);\n }\n return out.sort((a, b) => (a.updatedAt < b.updatedAt ? 1 : a.updatedAt > b.updatedAt ? -1 : 0));\n}\n\n/** The newest unfinished import of these inputs into this world, if one was started here. */\nexport function findResumable(slug: string, inputs: string[], cwd = process.cwd()): Manifest | null {\n const same = (a: string[], b: string[]) => a.length === b.length && a.every((x, i) => x === b[i]);\n return listManifests(cwd).find((m) => !m.completed && m.slug === slug && same(m.inputs, inputs)) ?? null;\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError } from \"../../router\";\nimport type { RedactPolicy } from \"../../../worlds/redaction\";\nimport { parseToml, TomlError, type TomlTable, type TomlValue } from \"./toml\";\n\n/**\n * What `data extract` needs to know about a world, read from its tree:\n * each entity's primary key and declared fields (`schema/world.json`,\n * `x-gateway.entities`), and from `connector.toml` the connector slug (the\n * digest salt), the `[redact]` policy and the `[api]` envelope. A tools-only\n * world has no connector.toml; its `[redact]` lives in `gateway-env.toml`,\n * salted with `[environment].name` (the Python runtime's `policy_for`).\n */\n\nexport type EntityInfo = {\n primaryKey: string[];\n /** The entity schema's declared properties; null when they cannot be resolved. */\n fields: Set<string> | null;\n};\n\n/** The `[redact]` table, the shape `describeWorld` reports and `storedForms` reads. */\nexport type { RedactPolicy };\n\n/** One `[[operations]]` entry: the tool name a call resolves to, and the entity its rows land in (null: none). */\nexport type OperationInfo = { entity: string | null };\n\nexport type WorldConfig = {\n dir: string;\n slug: string | null;\n entities: Record<string, EntityInfo>;\n redact: RedactPolicy;\n envelope: string;\n hitsKey: string;\n /** The world's operations by name — the tools `data ingest` knows. */\n operations: Record<string, OperationInfo>;\n};\n\nexport function loadWorldConfig(dir: string): WorldConfig {\n const worldFile = [\"schema/world.json\", \"world.json\"].map((p) => path.join(dir, p)).find((p) => fs.existsSync(p));\n if (!worldFile) throw new CliError(`${dir} has no schema/world.json; extract needs a schema world`, 1);\n let document: Record<string, unknown>;\n try {\n document = JSON.parse(fs.readFileSync(worldFile, \"utf8\")) as Record<string, unknown>;\n } catch {\n throw new CliError(`${worldFile} is not valid JSON`, 1);\n }\n const annotation = document[\"x-gateway\"] as { entities?: Record<string, Record<string, unknown>> } | undefined;\n if (!annotation || typeof annotation !== \"object\" || !annotation.entities || typeof annotation.entities !== \"object\")\n throw new CliError(`${worldFile} declares no x-gateway entities`, 1);\n const entities: Record<string, EntityInfo> = {};\n for (const [name, entity] of Object.entries(annotation.entities)) {\n const primaryKey = Array.isArray(entity.primary_key) ? (entity.primary_key as string[]) : [];\n entities[name] = { primaryKey, fields: declaredFields(document, entity.schema) };\n }\n const connectorFile = path.join(dir, \"connector.toml\");\n const spec = fs.existsSync(connectorFile) ? readSpec(connectorFile) : readEnvPolicy(path.join(dir, \"gateway-env.toml\"));\n return { dir, slug: spec.slug, entities, redact: spec.redact, envelope: spec.envelope, hitsKey: spec.hitsKey, operations: spec.operations };\n}\n\n/** Follow `$ref` pointers inside world.json to the entity's closed object; its property names. */\nfunction declaredFields(document: Record<string, unknown>, schema: unknown): Set<string> | null {\n let node = schema;\n for (let hops = 0; hops < 16 && node && typeof node === \"object\"; hops++) {\n const ref = (node as { $ref?: unknown }).$ref;\n if (typeof ref !== \"string\") break;\n if (!ref.startsWith(\"#/\")) return null; // another document (base.json): types, not entity roots\n node = ref\n .slice(2)\n .split(\"/\")\n .map((part) => part.replace(/~1/g, \"/\").replace(/~0/g, \"~\"))\n .reduce<unknown>((at, part) => (at && typeof at === \"object\" ? (at as Record<string, unknown>)[part] : undefined), document);\n }\n const properties = node && typeof node === \"object\" ? (node as { properties?: unknown }).properties : undefined;\n if (!properties || typeof properties !== \"object\") return null;\n return new Set(Object.keys(properties as Record<string, unknown>));\n}\n\ntype SpecConfig = { slug: string | null; redact: RedactPolicy; envelope: string; hitsKey: string; operations: Record<string, OperationInfo> };\n\nconst NO_SPEC: SpecConfig = { slug: null, redact: { hash: [], drop: [], preserve: [], round: {} }, envelope: \"\", hitsKey: \"hits\", operations: {} };\n\nfunction readToml(file: string): TomlTable {\n try {\n return parseToml(fs.readFileSync(file, \"utf8\"));\n } catch (error) {\n if (error instanceof TomlError) throw new CliError(`${file}: ${error.message}`, 1);\n throw error;\n }\n}\n\nfunction readSpec(file: string): SpecConfig {\n const raw = readToml(file);\n const connector = table(raw.connector);\n const apiTable = table(raw.api);\n const slug = typeof connector.slug === \"string\" ? connector.slug : null;\n return {\n slug,\n redact: redactPolicy(raw.redact, slug),\n envelope: typeof apiTable.envelope === \"string\" ? apiTable.envelope : \"\",\n hitsKey: typeof apiTable.hits_key === \"string\" ? apiTable.hits_key : \"hits\",\n operations: operationsOf(raw.operations),\n };\n}\n\n/** A tools-only world's `[redact]`, from gateway-env.toml; the salt is `[environment].name`. */\nfunction readEnvPolicy(file: string): SpecConfig {\n if (!fs.existsSync(file)) return NO_SPEC;\n const raw = readToml(file);\n if (raw.redact === undefined) return NO_SPEC;\n const name = table(raw.environment).name;\n if (typeof name !== \"string\" || !name.trim())\n throw new CliError(`${file}: [redact] salts its digests with [environment].name, which is missing`, 1);\n return { ...NO_SPEC, slug: name.trim(), redact: redactPolicy(raw.redact, name.trim()) };\n}\n\nfunction redactPolicy(value: TomlValue | undefined, slug: string | null): RedactPolicy {\n const redact = table(value);\n return {\n ...(slug ? { slug } : {}),\n hash: strings(redact.hash),\n drop: strings(redact.drop),\n preserve: strings(redact.preserve),\n round: rounding(redact.round),\n };\n}\n\nfunction operationsOf(value: TomlValue | undefined): Record<string, OperationInfo> {\n const out: Record<string, OperationInfo> = {};\n if (!Array.isArray(value)) return out;\n for (const entry of value) {\n const operation = table(entry as TomlValue);\n if (typeof operation.name !== \"string\" || !operation.name) continue;\n out[operation.name] = { entity: typeof operation.entity === \"string\" && operation.entity ? operation.entity : null };\n }\n return out;\n}\n\nconst table = (value: TomlValue | undefined): TomlTable => (value && typeof value === \"object\" && !Array.isArray(value) ? value : {});\nconst strings = (value: TomlValue | undefined): string[] => (Array.isArray(value) ? value.filter((v): v is string => typeof v === \"string\") : []);\nfunction rounding(value: TomlValue | undefined): Record<string, number> {\n const out: Record<string, number> = {};\n for (const [key, digits] of Object.entries(table(value))) if (typeof digits === \"number\" && Number.isInteger(digits)) out[key] = digits;\n return out;\n}\n","import * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport type { Credentials } from \"../../config\";\nimport { downloadFile, drivePath, isDriveRef, uploadFile, type UploadResult } from \"../../../files/index\";\nimport { worldsOptions } from \"../shared\";\n\n/**\n * The drive as an input or an output of a `worlds data` command. An input\n * `drive:<path>` is downloaded to a scratch file with the same name and the\n * command reads it as it would a local file; the report keeps the drive\n * spelling. An output `--to <path>` is written locally first (or to a scratch\n * file) and then uploaded, so a partial upload never leaves a half file\n * behind and nothing is streamed twice.\n */\n\nexport type StagedInputs = {\n /** Local paths in the caller's order; a drive ref replaced by its scratch copy. */\n files: string[];\n /** Scratch path → the `drive:<path>` it came from; empty when nothing came from the drive. */\n labels: Record<string, string>;\n cleanup: () => void;\n};\n\nexport async function stageDriveInputs(inputs: string[], creds: () => Credentials): Promise<StagedInputs> {\n if (!inputs.some(isDriveRef)) return { files: inputs, labels: {}, cleanup: () => undefined };\n const scratch = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-drive-in-\"));\n const cleanup = () => fs.rmSync(scratch, { recursive: true, force: true });\n const labels: Record<string, string> = {};\n const files: string[] = [];\n try {\n const options = worldsOptions(creds());\n for (const [index, input] of inputs.entries()) {\n if (!isDriveRef(input)) {\n files.push(input);\n continue;\n }\n const target = drivePath(input);\n const local = path.join(scratch, `${index}-${path.basename(target)}`);\n await downloadFile(options, target, local);\n labels[local] = `drive:${target}`;\n files.push(local);\n }\n } catch (error) {\n cleanup();\n throw error;\n }\n return { files, labels, cleanup };\n}\n\n/** The inputs as the person named them: the drive spelling for a staged copy, the path for the rest. */\nexport function inputLabels(files: string[], labels: Record<string, string>): string[] {\n return files.map((file) => labels[file] ?? file);\n}\n\n/** `{ inputs: [...] }` for a report, only when something came from the drive. */\nexport function inputsField(files: string[], labels: Record<string, string>): { inputs?: string[] } {\n return Object.keys(labels).length ? { inputs: inputLabels(files, labels) } : {};\n}\n\n/** Upload a finished local file to `drive:<path>`; the caller says what was written. */\nexport async function landInDrive(localFile: string, to: string, creds: Credentials): Promise<UploadResult> {\n return uploadFile(worldsOptions(creds), localFile, drivePath(to), { overwrite: true });\n}\n\n/** A scratch file for an output that only goes to the drive. */\nexport function scratchFile(name: string): { file: string; cleanup: () => void } {\n const dir = fs.mkdtempSync(path.join(os.tmpdir(), \"gateway-drive-out-\"));\n return { file: path.join(dir, name), cleanup: () => fs.rmSync(dir, { recursive: true, force: true }) };\n}\n\nexport const TO_FLAG = {\n name: \"to\",\n help: \"Also put the output in the drive at this path (drive:<path> or a bare path); overwrites.\",\n} as const;\n","/**\n * The project's file drive from code: the same routes the dashboard, the MCP\n * tools (list_files, get_file, request_file_upload, confirm_file_upload,\n * delete_file, move_file, create_folder) and `gateway files …` use.\n *\n * GET /api/public/files?prefix=&page=&limit= list a folder\n * POST /api/public/files presigned PUT, then\n * POST /api/public/files/confirm mark it ready\n * GET /api/public/files/download?path= presigned GET + metadata\n * DELETE /api/public/files?path= a file, or a folder subtree\n * POST /api/public/files/move { fromPath, toPath }\n * POST /api/public/files/folders { path }\n *\n * Bytes go straight to storage: an upload is a PUT to the presigned URL with\n * the SHA-256 S3 enforces, a download a GET from one. The app never proxies\n * them, so a file of any size the project allows moves at storage speed. Files\n * are addressed by PATH; the API returns a fileId on upload only to confirm it.\n */\n\nimport { createHash } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { Readable, Transform } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\n\nimport { apiRequest, type WorldsClientOptions } from \"../worlds/index\";\n\nexport type DriveFile = {\n path: string;\n name: string;\n sizeBytes: number | null;\n contentType: string | null;\n sha256: string | null;\n author: string | null;\n authorLabel: string;\n updatedAt: string;\n};\n\nexport type DriveFolder = { name: string; path: string };\n\nexport type DriveListing = {\n prefix: string;\n folders: DriveFolder[];\n files: DriveFile[];\n totalFiles: number;\n page: number;\n limit: number;\n};\n\n/** What `GET /files/download` answers: the file's metadata and a time-limited URL for its bytes. */\nexport type DriveDownload = {\n path: string;\n url: string;\n urlExpiry: string;\n sizeBytes: number | null;\n contentType: string | null;\n sha256: string | null;\n};\n\nexport type UploadResult = { path: string; fileId: string; sizeBytes: number; sha256: string; contentType: string };\n\nexport type UploadOptions = {\n contentType?: string;\n /** Replace a READY file at the same path. Default false: the platform refuses a taken path. */\n overwrite?: boolean;\n /** Bytes sent so far, called as the PUT streams. */\n onProgress?: (sent: number, total: number) => void;\n};\n\n/** The spelling that names a drive file where a local path would go: `drive:<path>`. */\nexport const DRIVE_PREFIX = \"drive:\";\n\nexport function isDriveRef(value: string): boolean {\n return value.startsWith(DRIVE_PREFIX);\n}\n\n/** `drive:corpora/x.jsonl` → `corpora/x.jsonl`; a leading slash is dropped, the platform keys paths without one. */\nexport function drivePath(ref: string): string {\n const raw = isDriveRef(ref) ? ref.slice(DRIVE_PREFIX.length) : ref;\n const trimmed = raw.replace(/^\\/+/, \"\");\n if (!trimmed) throw new Error(`${ref} names no file in the drive`);\n return trimmed;\n}\n\nconst PAGE_LIMIT = 200;\nconst BASE = \"/api/public/files\";\n\nfunction qs(params: Record<string, string | number | undefined>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) if (value !== undefined && value !== \"\") search.set(key, String(value));\n const text = search.toString();\n return text ? `?${text}` : \"\";\n}\n\nexport async function listFiles(\n options: WorldsClientOptions = {},\n params: { prefix?: string; page?: number; limit?: number } = {},\n): Promise<DriveListing> {\n return apiRequest<DriveListing>(options, \"GET\", `${BASE}${qs({ prefix: params.prefix, page: params.page, limit: params.limit })}`);\n}\n\n/** Every file directly under a folder, paging until the listing is exhausted. */\nexport async function* iterateFiles(options: WorldsClientOptions = {}, prefix?: string): AsyncGenerator<DriveFile> {\n for (let page = 0; ; page++) {\n const listing = await listFiles(options, { prefix, page, limit: PAGE_LIMIT });\n yield* listing.files;\n const seen = (page + 1) * listing.limit;\n if (!listing.files.length || seen >= listing.totalFiles) return;\n }\n}\n\n/** Metadata plus a presigned URL for one file; a 404 names the path. */\nexport async function getFile(options: WorldsClientOptions = {}, filePath: string): Promise<DriveDownload> {\n return apiRequest<DriveDownload>(options, \"GET\", `${BASE}/download${qs({ path: drivePath(filePath) })}`);\n}\n\nasync function openDownload(url: string): Promise<Response> {\n const res = await fetch(url);\n if (!res.ok || !res.body) throw new Error(`download failed: storage answered HTTP ${res.status}`);\n return res;\n}\n\n/** The whole file in memory — for text, configs, anything you would `cat`. */\nexport async function readFile(options: WorldsClientOptions = {}, filePath: string): Promise<Buffer> {\n const file = await getFile(options, filePath);\n const res = await openDownload(file.url);\n return Buffer.from(await res.arrayBuffer());\n}\n\n/** Stream one file to a local path; the parent directory is created. */\nexport async function downloadFile(\n options: WorldsClientOptions = {},\n filePath: string,\n outPath: string,\n onProgress?: (received: number, total: number | null) => void,\n): Promise<DriveDownload & { out: string }> {\n const file = await getFile(options, filePath);\n const res = await openDownload(file.url);\n fs.mkdirSync(path.dirname(path.resolve(outPath)), { recursive: true });\n const source = Readable.fromWeb(res.body as never);\n await pipeline(source, counting((n) => onProgress?.(n, file.sizeBytes)), fs.createWriteStream(outPath));\n return { ...file, out: outPath };\n}\n\nexport async function requestUpload(\n options: WorldsClientOptions = {},\n body: { path: string; contentLength: number; contentType: string; sha256: string; overwrite?: boolean },\n): Promise<{ fileId: string; uploadUrl: string; path: string }> {\n return apiRequest(options, \"POST\", BASE, body);\n}\n\nexport async function confirmUpload(options: WorldsClientOptions = {}, fileId: string, ok = true): Promise<{ path: string }> {\n return apiRequest(options, \"POST\", `${BASE}/confirm`, { fileId, ok });\n}\n\n/** The base64 SHA-256 the platform hands to S3 (`x-amz-checksum-sha256`), computed by streaming. */\nexport async function sha256Base64(localPath: string): Promise<string> {\n const hash = createHash(\"sha256\");\n for await (const chunk of fs.createReadStream(localPath)) hash.update(chunk as Buffer);\n return hash.digest(\"base64\");\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n \".json\": \"application/json\",\n \".jsonl\": \"application/x-ndjson\",\n \".ndjson\": \"application/x-ndjson\",\n \".csv\": \"text/csv\",\n \".tsv\": \"text/tab-separated-values\",\n \".txt\": \"text/plain\",\n \".md\": \"text/markdown\",\n \".toml\": \"application/toml\",\n \".yaml\": \"application/yaml\",\n \".yml\": \"application/yaml\",\n \".xml\": \"application/xml\",\n \".html\": \"text/html\",\n \".sql\": \"application/sql\",\n \".py\": \"text/x-python\",\n \".ts\": \"text/plain\",\n \".js\": \"text/javascript\",\n \".pdf\": \"application/pdf\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".svg\": \"image/svg+xml\",\n \".zip\": \"application/zip\",\n \".gz\": \"application/gzip\",\n \".tar\": \"application/x-tar\",\n \".parquet\": \"application/vnd.apache.parquet\",\n \".wav\": \"audio/wav\",\n \".mp3\": \"audio/mpeg\",\n \".mp4\": \"video/mp4\",\n};\n\n/** A MIME type from the extension; `application/octet-stream` when none is known. */\nexport function contentTypeFor(name: string): string {\n return CONTENT_TYPES[path.extname(name).toLowerCase()] ?? \"application/octet-stream\";\n}\n\n/** A transform that reports the bytes that passed through it. */\nfunction counting(report: (n: number) => void): Transform {\n let seen = 0;\n return new Transform({\n transform(chunk, _encoding, callback) {\n seen += (chunk as Buffer).length;\n report(seen);\n callback(null, chunk);\n },\n });\n}\n\nasync function putPresigned(\n uploadUrl: string,\n body: BodyInit,\n headers: { contentType: string; contentLength: number; sha256: string },\n): Promise<void> {\n const res = await fetch(uploadUrl, {\n method: \"PUT\",\n headers: {\n \"content-type\": headers.contentType,\n \"content-length\": String(headers.contentLength),\n \"x-amz-checksum-sha256\": headers.sha256,\n },\n body,\n // A streamed request body needs the half-duplex declaration (Node's fetch).\n duplex: \"half\",\n } as RequestInit);\n if (!res.ok) throw new Error(`upload failed: storage answered HTTP ${res.status}: ${(await res.text()).slice(0, 300)}`);\n}\n\n/**\n * Request, PUT, confirm — the three-step presigned upload as one call. The\n * bytes stream from disk; a failed PUT is confirmed with ok=false so no\n * PENDING placeholder is left behind, then the error is rethrown.\n */\nexport async function uploadFile(\n options: WorldsClientOptions = {},\n localPath: string,\n targetPath: string,\n upload: UploadOptions = {},\n): Promise<UploadResult> {\n const stat = fs.statSync(localPath);\n if (!stat.isFile()) throw new Error(`${localPath} is not a file`);\n if (stat.size === 0) throw new Error(`${localPath} is empty; the drive refuses zero-byte uploads`);\n const contentType = upload.contentType ?? contentTypeFor(localPath);\n const sha256 = await sha256Base64(localPath);\n const target = drivePath(targetPath);\n const granted = await requestUpload(options, { path: target, contentLength: stat.size, contentType, sha256, ...(upload.overwrite ? { overwrite: true } : {}) });\n try {\n const stream = fs.createReadStream(localPath).pipe(counting((n) => upload.onProgress?.(n, stat.size)));\n await putPresigned(granted.uploadUrl, Readable.toWeb(stream) as unknown as BodyInit, { contentType, contentLength: stat.size, sha256 });\n } catch (error) {\n await confirmUpload(options, granted.fileId, false).catch(() => undefined);\n throw error;\n }\n const confirmed = await confirmUpload(options, granted.fileId, true);\n return { path: confirmed.path, fileId: granted.fileId, sizeBytes: stat.size, sha256, contentType };\n}\n\n/** The same three steps for bytes already in memory (a fetched URL, a generated export). */\nexport async function uploadBytes(\n options: WorldsClientOptions = {},\n bytes: Buffer,\n targetPath: string,\n upload: Omit<UploadOptions, \"onProgress\"> = {},\n): Promise<UploadResult> {\n if (!bytes.length) throw new Error(\"nothing to upload: the content is empty\");\n const target = drivePath(targetPath);\n const contentType = upload.contentType ?? contentTypeFor(target);\n const sha256 = createHash(\"sha256\").update(bytes).digest(\"base64\");\n const granted = await requestUpload(options, { path: target, contentLength: bytes.length, contentType, sha256, ...(upload.overwrite ? { overwrite: true } : {}) });\n try {\n await putPresigned(granted.uploadUrl, new Uint8Array(bytes), { contentType, contentLength: bytes.length, sha256 });\n } catch (error) {\n await confirmUpload(options, granted.fileId, false).catch(() => undefined);\n throw error;\n }\n const confirmed = await confirmUpload(options, granted.fileId, true);\n return { path: confirmed.path, fileId: granted.fileId, sizeBytes: bytes.length, sha256, contentType };\n}\n\n/** Delete a file, or a folder and everything under it. Answers how many entries went. */\nexport async function deleteFile(options: WorldsClientOptions = {}, filePath: string): Promise<{ deleted: number }> {\n return apiRequest(options, \"DELETE\", `${BASE}${qs({ path: drivePath(filePath) })}`);\n}\n\n/** Rename or move a file or a whole folder; metadata only, no bytes re-copied. */\nexport async function moveFile(options: WorldsClientOptions = {}, fromPath: string, toPath: string): Promise<{ moved: number }> {\n return apiRequest(options, \"POST\", `${BASE}/move`, { fromPath: drivePath(fromPath), toPath: drivePath(toPath) });\n}\n\n/** Create an (empty) folder. Idempotent. */\nexport async function createFolder(options: WorldsClientOptions = {}, folderPath: string): Promise<{ path: string }> {\n return apiRequest(options, \"POST\", `${BASE}/folders`, { path: drivePath(folderPath) });\n}\n\nexport type FileConnector = {\n id: string;\n name: string;\n kind: string;\n connectionId: string | null;\n targetPrefix: string;\n lastSyncAt: string | null;\n lastStatus: string | null;\n};\n\n/** The connectors a human shared with agents — `GET /api/public/files/connectors`. */\nexport async function listFileConnectors(options: WorldsClientOptions = {}): Promise<{ connectors: FileConnector[] }> {\n return apiRequest(options, \"GET\", `${BASE}/connectors`);\n}\n\n/** Run one connector's sync now — `POST /api/public/files/connectors/sync`. */\nexport async function syncFileConnector(options: WorldsClientOptions = {}, connectorId: string): Promise<Record<string, unknown>> {\n return apiRequest(options, \"POST\", `${BASE}/connectors/sync`, { connectorId });\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { api } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\nimport type { AgentRow } from \"./agent\";\nimport { API_KEY_FLAG, credentials, HOST_FLAG, rawRequest } from \"./shared\";\n\n/** Items from a JSON (`[...]`, `{tasks: [...]}`, `{items: [...]}`) or JSONL file. */\nexport function readDatasetItems(file: string): unknown[] {\n const raw = fs.readFileSync(file, \"utf8\").trim();\n const looksJson = path.extname(file) === \".json\" || raw.startsWith(\"{\") || raw.startsWith(\"[\");\n if (looksJson) {\n let data: unknown;\n try {\n data = JSON.parse(raw);\n } catch (error) {\n // A .jsonl whose first line starts with \"{\" is JSONL, not one document\n // (the Python CLI trips here; the documented JSONL shape wins).\n if (path.extname(file) === \".json\") throw error;\n data = undefined;\n }\n if (data !== undefined) {\n if (Array.isArray(data)) return data;\n if (data && typeof data === \"object\") {\n const record = data as Record<string, unknown>;\n const listed = record.tasks ?? record.items;\n return Array.isArray(listed) ? listed : [];\n }\n return [];\n }\n }\n return raw\n .split(/\\r?\\n/)\n .filter((line) => line.trim())\n .map((line) => JSON.parse(line) as unknown);\n}\n\n/** `gateway dataset upload FILE --name ...` over /api/public/datasets/import. */\nexport function registerDatasetCommands(root: CommandGroup): void {\n const dataset = root.group(\"dataset\", \"Manage datasets.\");\n\n dataset.command({\n name: \"upload\",\n help: \"Upload a JSON or JSONL file as a dataset.\",\n positionals: [{ name: \"path\", help: \"Path to JSON or JSONL file\" }],\n flags: [\n { name: \"name\", help: \"Dataset name\" },\n { name: \"agent\", help: \"Validate items against this agent's task schema\" },\n { name: \"description\", help: \"Description\" },\n HOST_FLAG,\n API_KEY_FLAG,\n ],\n notes: [\n \"Supports:\",\n ' - JSON with {\"tasks\": [...]} or {\"items\": [...]} wrapper',\n \" - JSON bare array [item1, item2, ...]\",\n \" - JSONL (one JSON object per line)\",\n ].join(\"\\n\"),\n run: async (args, ctx) => {\n const file = args.positionals[0]!;\n const name = arg.str(args, \"name\");\n if (!name) throw new CliError(\"dataset upload needs --name\");\n if (!fs.existsSync(file)) throw new CliError(`Error: File not found: ${file}`, 1);\n const items = readDatasetItems(file);\n if (items.length === 0) throw new CliError(\"Error: No items found in file.\", 1);\n ctx.stdout(`Found ${items.length} items in ${path.basename(file)}`);\n\n const creds = credentials(args);\n const agent = arg.str(args, \"agent\");\n if (agent) {\n const listed = await rawRequest(creds, \"GET\", \"/api/public/agents\");\n if (!listed.ok) {\n ctx.stderr(`Warning: Could not fetch agents for validation: HTTP ${listed.status}`);\n } else {\n const agents = ((listed.json() as { agents?: AgentRow[] }).agents ?? []).filter((a) => a.name === agent);\n if (agents.length === 0) ctx.stderr(`Warning: Agent '${agent}' not found, skipping validation`);\n else if (!agents[0]!.taskInputSchema)\n ctx.stdout(`Agent '${agent}' has no taskInputSchema, skipping validation`);\n else\n // The Python CLI validates with the optional `jsonschema` package and\n // skips with this warning when it is absent; a dependency-free CLI\n // takes the same branch rather than half-implementing JSON Schema.\n ctx.stderr(\n \"Warning: JSON Schema validation is not available in the TypeScript CLI, skipping validation. \" +\n \"The platform validates items against the agent's schema on import.\",\n );\n }\n }\n\n ctx.stdout(`Uploading ${items.length} items as dataset '${name}'...`);\n const payload: Record<string, unknown> = { name, items: items.map((item) => ({ input: item })) };\n const description = arg.str(args, \"description\");\n if (description) payload.description = description;\n const data = await api<Record<string, unknown>>(creds, \"POST\", \"/api/public/datasets/import\", payload);\n ctx.stdout(\"Dataset created!\");\n ctx.stdout(` Dataset ID: ${data.datasetId}`);\n ctx.stdout(` Name: ${data.datasetName}`);\n ctx.stdout(` Items: ${data.itemCount}`);\n },\n });\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { printJson } from \"../config\";\nimport { arg, CliError, type CommandContext, type CommandGroup } from \"../router\";\nimport {\n contentTypeFor,\n createFolder,\n deleteFile,\n downloadFile,\n drivePath,\n getFile,\n listFileConnectors,\n listFiles,\n moveFile,\n readFile,\n syncFileConnector,\n uploadBytes,\n uploadFile,\n type DriveListing,\n type UploadResult,\n} from \"../../files/index\";\nimport { credentials, HOST_FLAG, showProgress, worldsOptions } from \"./shared\";\n\n/**\n * `gateway files …`: the project's drive, one command per REST route and MCP\n * tool. Files are addressed by path (`corpora/2026/train.jsonl`); `drive:` in\n * front is accepted and ignored, so a path copied from a `worlds data`\n * command works here unchanged.\n */\n\nconst PATH_HELP = \"Path in the drive, e.g. corpora/train.jsonl (a drive: prefix is accepted).\";\nconst JSON_FLAG = { name: \"json\", help: \"Print the platform's JSON instead of the summary.\", boolean: true } as const;\n\nexport function registerFilesCommands(root: CommandGroup): void {\n const files = root.group(\"files\", \"The project's file drive: upload, list, download, move, delete.\");\n files.notes =\n \"Bytes move straight between you and storage over presigned URLs; the platform keeps the index.\\n\" +\n \"Any `worlds data` command takes `drive:<path>` where it takes a local file, so `files upload rows.json`\\n\" +\n \"then `worlds data import <world> drive:rows.json` is the whole route from a laptop to a world.\";\n\n files.command({\n name: \"upload\",\n help: \"Upload files (a directory recurses) to the drive; the presigned PUT streams and is confirmed.\",\n positionals: [{ name: \"local-path\", help: \"Files or directories to upload.\", variadic: true }],\n flags: [\n { name: \"to\", help: \"Drive folder to put them under (default the root); one file may name its full path here.\" },\n { name: \"content-type\", help: \"MIME type for every uploaded file (default from the extension).\" },\n { name: \"overwrite\", help: \"Replace a file that already exists at the same path.\", boolean: true },\n JSON_FLAG,\n HOST_FLAG,\n ],\n notes:\n \"Each file lands at <to>/<name> (a directory keeps its own name and layout under <to>). With one file\\n\" +\n \"and a --to that ends in a file name, the file takes that exact path. A path already taken is refused\\n\" +\n \"unless --overwrite. Exit 0 when every file landed, 1 when any was refused (the rest still land).\",\n run: async (args, ctx) => {\n if (!args.positionals.length) throw new CliError(\"files upload needs at least one file or directory\");\n const options = worldsOptions(credentials(args));\n const to = arg.str(args, \"to\");\n const plan = planUploads(args.positionals, to);\n const contentType = arg.str(args, \"content-type\");\n const overwrite = arg.bool(args, \"overwrite\");\n const uploaded: UploadResult[] = [];\n const refused: { local: string; path: string; error: string }[] = [];\n for (const item of plan) {\n const progress = progressReporter(ctx, item.local);\n try {\n const result = await uploadFile(options, item.local, item.path, { contentType, overwrite, onProgress: progress });\n uploaded.push(result);\n if (!arg.bool(args, \"json\")) ctx.stdout(`${item.local} -> drive:${result.path} (${result.sizeBytes} bytes, ${result.contentType})`);\n } catch (error) {\n refused.push({ local: item.local, path: item.path, error: (error as Error).message });\n ctx.stderr(`${item.local} -> drive:${item.path}: ${(error as Error).message}`);\n }\n }\n if (arg.bool(args, \"json\")) printJson(ctx, { uploaded, refused });\n return refused.length ? 1 : 0;\n },\n });\n\n files.command({\n name: \"list\",\n help: \"A folder's sub-folders and files (name, size, type, who uploaded it, when).\",\n positionals: [{ name: \"path\", help: \"Folder to list (default the root).\", optional: true }],\n flags: [\n { name: \"path\", help: \"Folder to list, the same as the positional.\" },\n { name: \"page\", help: \"0-based page of files (200 per page).\", default: \"0\" },\n JSON_FLAG,\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const folder = args.positionals[0] ?? arg.str(args, \"path\");\n const prefix = folder ? drivePath(folder) : undefined;\n const listing = await listFiles(worldsOptions(credentials(args)), { prefix, page: arg.int(args, \"page\"), limit: 200 });\n if (arg.bool(args, \"json\")) printJson(ctx, listing);\n else renderListing(listing, ctx);\n },\n });\n\n files.command({\n name: \"get\",\n help: \"One file's metadata (size, type, sha256) and a time-limited download URL.\",\n positionals: [{ name: \"path\", help: PATH_HELP }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n printJson(ctx, await getFile(worldsOptions(credentials(args)), args.positionals[0]!));\n },\n });\n\n files.command({\n name: \"download\",\n help: \"Stream one file to disk.\",\n positionals: [{ name: \"path\", help: PATH_HELP }],\n flags: [{ name: \"out\", help: \"Local path to write (default the file's own name in the working directory).\" }, HOST_FLAG],\n run: async (args, ctx) => {\n const target = drivePath(args.positionals[0]!);\n const out = arg.str(args, \"out\") ?? path.basename(target);\n const result = await downloadFile(worldsOptions(credentials(args)), target, out, progressReporter(ctx, `drive:${target}`));\n ctx.stdout(`drive:${result.path} -> ${out} (${result.sizeBytes ?? \"?\"} bytes)`);\n },\n });\n\n files.command({\n name: \"cat\",\n help: \"Print one file's bytes to stdout.\",\n positionals: [{ name: \"path\", help: PATH_HELP }],\n flags: [HOST_FLAG],\n run: async (args) => {\n const bytes = await readFile(worldsOptions(credentials(args)), args.positionals[0]!);\n process.stdout.write(bytes);\n },\n });\n\n files.command({\n name: \"delete\",\n help: \"Delete a file, or a folder and everything under it.\",\n positionals: [{ name: \"path\", help: PATH_HELP }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const target = drivePath(args.positionals[0]!);\n const result = await deleteFile(worldsOptions(credentials(args)), target);\n if (!result.deleted) throw new CliError(`drive:${target}: nothing there to delete`, 1);\n ctx.stdout(`deleted ${result.deleted} from drive:${target}`);\n },\n });\n\n files.command({\n name: \"move\",\n help: \"Rename or move a file or a whole folder (metadata only, instant).\",\n positionals: [\n { name: \"from\", help: \"Current path.\" },\n { name: \"to\", help: \"New path.\" },\n ],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const [from, to] = args.positionals as [string, string];\n const result = await moveFile(worldsOptions(credentials(args)), from, to);\n if (!result.moved) throw new CliError(`drive:${drivePath(from)}: nothing there to move`, 1);\n ctx.stdout(`moved ${result.moved}: drive:${drivePath(from)} -> drive:${drivePath(to)}`);\n },\n });\n\n files.command({\n name: \"mkdir\",\n help: \"Create an empty folder (idempotent).\",\n positionals: [{ name: \"path\", help: \"Folder path, e.g. corpora/2026.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const result = await createFolder(worldsOptions(credentials(args)), args.positionals[0]!);\n ctx.stdout(`drive:${result.path}/`);\n },\n });\n\n files.command({\n name: \"fetch\",\n help: \"Download a public URL and put it in the drive.\",\n positionals: [{ name: \"url\", help: \"http(s) URL to fetch.\" }],\n flags: [\n { name: \"to\", help: \"Drive path to save to, e.g. imports/products.csv.\" },\n { name: \"content-type\", help: \"MIME type to record (default: the response's, else from the name).\" },\n { name: \"overwrite\", help: \"Replace a file already at that path.\", boolean: true },\n HOST_FLAG,\n ],\n notes:\n \"The bytes pass through this machine (the MCP tool download_url_to_drive fetches on the platform;\\n\" +\n \"the REST API has no route for that), so a URL only your network reaches works here.\",\n run: async (args, ctx) => {\n const url = args.positionals[0]!;\n const to = arg.str(args, \"to\");\n if (!to) throw new CliError(\"files fetch needs --to <drive path>\");\n if (!/^https?:\\/\\//i.test(url)) throw new CliError(`${url} is not an http(s) URL`);\n const res = await fetch(url);\n if (!res.ok) throw new CliError(`${url} answered HTTP ${res.status}`, 1);\n const bytes = Buffer.from(await res.arrayBuffer());\n if (!bytes.length) throw new CliError(`${url} answered an empty body`, 1);\n const header = res.headers.get(\"content-type\")?.split(\";\")[0]?.trim();\n const contentType = arg.str(args, \"content-type\") ?? (header && header !== \"application/octet-stream\" ? header : contentTypeFor(to));\n const result = await uploadBytes(worldsOptions(credentials(args)), bytes, to, { contentType, overwrite: arg.bool(args, \"overwrite\") });\n ctx.stdout(`${url} -> drive:${result.path} (${result.sizeBytes} bytes, ${result.contentType})`);\n },\n });\n\n const connectors = files.group(\"connectors\", \"The drive's inbound feeds (Slack channels, Google Drive files, URLs) a human shared with agents.\");\n connectors.command({\n name: \"list\",\n help: \"The connectors shared with agents: id, name, kind, target folder, last sync.\",\n flags: [JSON_FLAG, HOST_FLAG],\n run: async (args, ctx) => {\n const result = await listFileConnectors(worldsOptions(credentials(args)));\n if (arg.bool(args, \"json\")) return void printJson(ctx, result);\n if (!result.connectors.length) return void ctx.stdout(\"no connectors are shared with agents (a human turns that on in the Connectors tab)\");\n for (const c of result.connectors) ctx.stdout(`${c.id} ${c.name} ${c.kind} -> drive:${c.targetPrefix} last ${c.lastSyncAt ?? \"never\"}${c.lastStatus ? ` (${c.lastStatus})` : \"\"}`);\n },\n });\n connectors.command({\n name: \"sync\",\n help: \"Run one connector's sync now; fresh copies land under its folder.\",\n positionals: [{ name: \"connector-id\", help: \"Connector id from `files connectors list`.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n printJson(ctx, await syncFileConnector(worldsOptions(credentials(args)), args.positionals[0]!));\n },\n });\n}\n\ntype PlannedUpload = { local: string; path: string };\n\n/**\n * Local files (directories walked) → drive paths. One file with a --to whose\n * last segment looks like a file name takes that path; everything else lands\n * under --to by name, a directory under its own name.\n */\nexport function planUploads(inputs: string[], to: string | undefined): PlannedUpload[] {\n const base = to ? drivePath(to).replace(/\\/+$/, \"\") : \"\";\n const join = (...parts: string[]) => parts.filter(Boolean).join(\"/\");\n const plan: PlannedUpload[] = [];\n for (const input of inputs) {\n if (!fs.existsSync(input)) throw new CliError(`${input} does not exist`, 1);\n if (fs.statSync(input).isDirectory()) {\n const root = path.resolve(input);\n for (const file of walk(root)) plan.push({ local: file, path: join(base, path.basename(root), path.relative(root, file).split(path.sep).join(\"/\")) });\n continue;\n }\n const oneFileNamedInFull = inputs.length === 1 && base !== \"\" && !to!.endsWith(\"/\") && path.extname(base) !== \"\";\n plan.push({ local: input, path: oneFileNamedInFull ? base : join(base, path.basename(input)) });\n }\n if (!plan.length) throw new CliError(\"nothing to upload: the directories are empty\", 1);\n return plan;\n}\n\nfunction walk(dir: string): string[] {\n const out: string[] = [];\n for (const entry of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n if (entry.name.startsWith(\".\")) continue;\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) out.push(...walk(full));\n else if (entry.isFile()) out.push(full);\n }\n return out;\n}\n\n/** Byte counts on stderr while a transfer runs — on a TTY, or as GATEWAY_PROGRESS says; at most once a second. */\nfunction progressReporter(ctx: CommandContext, label: string): (done: number, total: number | null) => void {\n if (!showProgress()) return () => undefined;\n let last = 0;\n return (done, total) => {\n const now = Date.now();\n if (now - last < 1000 && done !== total) return;\n last = now;\n ctx.stderr(`${label}: ${done}${total ? ` / ${total}` : \"\"} bytes`);\n };\n}\n\nfunction renderListing(listing: DriveListing, ctx: CommandContext): void {\n const where = listing.prefix ? `drive:${listing.prefix}/` : \"drive:/\";\n for (const folder of listing.folders) ctx.stdout(`${folder.path}/`);\n for (const file of listing.files) ctx.stdout(`${file.path} ${file.sizeBytes ?? \"?\"} ${file.contentType ?? \"-\"} ${file.authorLabel} ${file.updatedAt}`);\n const shown = listing.folders.length + listing.files.length;\n if (!shown) ctx.stdout(`${where} is empty`);\n else if (listing.totalFiles > (listing.page + 1) * listing.limit) ctx.stderr(`${listing.totalFiles} files in ${where}; --page ${listing.page + 1} for more`);\n}\n","import type { CommandGroup } from \"../router\";\nimport { pythonOnly } from \"./shared\";\n\n/**\n * Root-level Python commands that build or scaffold PYTHON agent projects\n * (Docker images, gateway_manifest/, Algorithm subclasses). They exist here\n * so `gateway deploy` says what to do instead of \"unknown command\".\n */\nexport function registerPythonOnlyCommands(root: CommandGroup): void {\n root.command({\n name: \"deploy\",\n help: \"Python-only: build, push and register a Python agent image (gatewaysdk[platform]).\",\n run: async (_args, ctx) =>\n pythonOnly(\n ctx,\n \"deploy\",\n \"it builds a Docker image from a Python agent project and registers its manifest.\",\n \"pip install 'gatewaysdk[platform]' && gateway deploy --tag <agent>:<version>\",\n ),\n });\n\n root.command({\n name: \"init\",\n help: \"Python-only: scaffold a Python agent project (Dockerfile + gateway_manifest/).\",\n run: async (_args, ctx) =>\n pythonOnly(\n ctx,\n \"init\",\n \"it scaffolds a Python agent project around the gateway-agent runner.\",\n \"pip install 'gatewaysdk[platform]' && gateway init --agent module:attr\",\n ),\n });\n\n const algorithm = root.group(\"algorithm\", \"Python-only: list and scaffold Python SDK algorithms.\");\n algorithm.command({\n name: \"list\",\n help: \"Python-only: list Algorithm subclasses importable in the Python SDK.\",\n run: async (_args, ctx) =>\n pythonOnly(ctx, \"algorithm list\", \"algorithms are Python classes.\", \"pip install gatewaysdk && gateway algorithm list\"),\n });\n algorithm.command({\n name: \"new\",\n help: \"Python-only: scaffold an Algorithm subclass.\",\n run: async (_args, ctx) =>\n pythonOnly(ctx, \"algorithm new\", \"algorithms are Python classes.\", \"pip install gatewaysdk && gateway algorithm new <name>\"),\n });\n}\n","import type { Credentials } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\nimport { API_KEY_FLAG, appendStepSummary, credentials, HOST_FLAG, query, rawRequest, sleep } from \"./shared\";\n\n/**\n * `gateway release gate` — ask the release gate about a build, from CI.\n *\n * The verdict is computed on the server with the same rule the Releases page\n * enforces; this command only turns it into an exit code:\n * 0 pass · 1 blocked · 2 untested (no run recorded, or still going).\n */\n\nexport const GATE_PATH = \"/api/public/agent-builds/gate\";\nexport const EXIT_CODES: Record<string, number> = { pass: 0, blocked: 1, untested: 2 };\nexport const TERMINAL_STATES = new Set([\"COMPLETED\", \"FAILED\", \"ERROR\", \"TIMEOUT\", \"CANCELLED\"]);\n\nexport type GateResult = {\n build?: Record<string, unknown>;\n gate?: {\n verdict?: string;\n passRate?: number | null;\n threshold?: number | null;\n gradedRollouts?: number;\n minGradedRollouts?: number;\n reasons?: string[];\n };\n comparedTo?: Record<string, unknown> | null;\n evaluatedRuns?: Record<string, unknown>[];\n};\n\n/** Exactly one way of naming the build, as the endpoint's query string. */\nexport function buildQuery(opts: { build?: string; agent?: string; version?: string; commit?: string }): Record<string, string> {\n const ways = [opts.build !== undefined, opts.agent !== undefined || opts.version !== undefined, opts.commit !== undefined];\n if (ways.filter(Boolean).length !== 1)\n throw new CliError(\"name the build one way: --build, --agent + --version, or --commit\");\n if (opts.build !== undefined) return { buildId: opts.build };\n if (opts.commit !== undefined) return { commitSha: opts.commit };\n if (!opts.agent || !opts.version) throw new CliError(\"--agent and --version go together; supply both\");\n return { agentId: opts.agent, version: opts.version };\n}\n\nexport async function fetchGate(creds: Credentials, q: Record<string, string>): Promise<GateResult> {\n const res = await rawRequest(creds, \"GET\", `${GATE_PATH}${query(q)}`);\n if (res.status === 404) {\n let detail: string | undefined;\n try {\n const body = res.json() as Record<string, unknown>;\n detail = [body.message, body.error].find((v): v is string => typeof v === \"string\");\n } catch {\n detail = undefined;\n }\n throw new CliError(`Error: ${detail ?? \"no build matches that lookup\"}`, 2);\n }\n if (!res.ok) throw new CliError(`Failed (HTTP ${res.status}): ${res.text}`, 2);\n return res.json() as GateResult;\n}\n\nexport function runsSettled(result: GateResult): boolean {\n const runs = result.evaluatedRuns ?? [];\n if (runs.length === 0) return false;\n return runs.every((run) => TERMINAL_STATES.has(String(run.state ?? \"\").toUpperCase()));\n}\n\nexport function exitCodeFor(result: GateResult): number {\n const verdict = String(result.gate?.verdict ?? \"\").toLowerCase();\n if (!(verdict in EXIT_CODES)) throw new CliError(`unknown gate verdict '${verdict}'`, 2);\n return EXIT_CODES[verdict]!;\n}\n\nconst fmtRate = (rate: number | null | undefined) => (rate === null || rate === undefined ? \"n/a\" : rate.toFixed(2));\n\nexport function renderTable(result: GateResult): string {\n const build = result.build ?? {};\n const gate = result.gate ?? {};\n const rows: [string, string][] = [\n [\"verdict\", String(gate.verdict ?? \"?\").toUpperCase()],\n [\"agent\", String(build.agentId ?? \"?\")],\n [\"version\", String(build.version ?? \"-\")],\n [\"build\", String(build.id ?? \"?\")],\n [\"commit\", String(build.commitSha ?? \"-\")],\n [\"pass rate\", fmtRate(gate.passRate)],\n [\"graded\", String(gate.gradedRollouts ?? 0)],\n [\"rule\", `needs ${fmtRate(gate.threshold)} pass rate and at least ${gate.minGradedRollouts ?? \"?\"} graded`],\n ];\n if (result.comparedTo) rows.push([\"production\", String(result.comparedTo.stableVersion ?? result.comparedTo.stableBuildId)]);\n const width = Math.max(...rows.map(([k]) => k.length));\n const lines = rows.map(([k, v]) => `${k.padEnd(width)} ${v}`);\n const reasons = gate.reasons ?? [];\n if (reasons.length) lines.push(\"\", ...reasons.map((r) => `- ${r}`));\n const runs = result.evaluatedRuns ?? [];\n if (runs.length) {\n lines.push(\"\", \"runs (newest first):\");\n for (const run of runs)\n lines.push(\n ` ${run.runId} ${run.state} world=${run.world ?? \"-\"} model=${run.model ?? \"-\"} ` +\n `pass=${fmtRate(run.passRate as number | null | undefined)} graded=${run.graded ?? 0}`,\n );\n }\n return lines.join(\"\\n\");\n}\n\nfunction sortedJson(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(sortedJson);\n if (value && typeof value === \"object\")\n return Object.fromEntries(\n Object.keys(value as Record<string, unknown>)\n .sort()\n .map((k) => [k, sortedJson((value as Record<string, unknown>)[k])]),\n );\n return value;\n}\n\nexport function stepSummary(result: GateResult): string {\n const build = result.build ?? {};\n const gate = result.gate ?? {};\n const lines = [\n `### Release gate: ${build.agentId ?? \"?\"} ${build.version ?? \"\"}`.trimEnd(),\n \"\",\n \"| | |\",\n \"|---|---|\",\n `| verdict | ${String(gate.verdict ?? \"?\").toUpperCase()} |`,\n `| pass rate | ${fmtRate(gate.passRate)} |`,\n `| graded | ${gate.gradedRollouts ?? 0} |`,\n `| rule | ${fmtRate(gate.threshold)} / ${gate.minGradedRollouts ?? \"?\"} graded |`,\n ];\n for (const reason of gate.reasons ?? []) lines.push(`| reason | ${reason} |`);\n return lines.join(\"\\n\");\n}\n\nexport function registerReleaseCommands(root: CommandGroup): void {\n const release = root.group(\"release\", \"Release gate for agent builds — ask the platform whether a build may ship.\");\n\n release.command({\n name: \"gate\",\n help: \"The release gate's verdict on a build, as an exit code CI can branch on.\",\n flags: [\n { name: \"build\", help: \"Agent build id.\" },\n { name: \"agent\", help: \"Agent id (with --version).\" },\n { name: \"version\", help: \"Declared build version (with --agent).\" },\n { name: \"commit\", help: \"Commit sha the build was registered from (full, or a 7+ char prefix).\" },\n { name: \"wait\", help: \"Poll until every run attributed to the build is terminal.\", boolean: true },\n { name: \"timeout\", help: \"Seconds to wait for runs to settle (with --wait).\", default: \"1800\" },\n { name: \"interval\", help: \"Seconds between polls (with --wait).\", default: \"15\" },\n { name: \"json\", help: \"Print the endpoint's JSON instead of a table.\", boolean: true },\n HOST_FLAG,\n API_KEY_FLAG,\n ],\n notes: \"Exit codes:\\n 0 pass the gate is open on the build's latest run\\n 1 blocked the latest run failed the project's rule (reasons printed)\\n 2 untested no run recorded this build, or its latest run is still going\",\n run: async (args, ctx) => {\n const q = buildQuery({\n build: arg.str(args, \"build\"),\n agent: arg.str(args, \"agent\"),\n version: arg.str(args, \"version\"),\n commit: arg.str(args, \"commit\"),\n });\n const creds = credentials(args);\n const asJson = arg.bool(args, \"json\");\n let result: GateResult;\n if (arg.bool(args, \"wait\")) {\n const timeout = Number(arg.str(args, \"timeout\") ?? 1800);\n const interval = Number(arg.str(args, \"interval\") ?? 15);\n if (!(timeout >= 1) || !(interval >= 1)) throw new CliError(\"--timeout and --interval must be at least 1\");\n const deadline = Date.now() + timeout * 1000;\n for (;;) {\n result = await fetchGate(creds, q);\n if (!asJson) {\n const runs = result.evaluatedRuns ?? [];\n const pending = runs.filter((r) => !TERMINAL_STATES.has(String(r.state ?? \"\").toUpperCase()));\n if (runs.length === 0) ctx.stderr(\"waiting: no run has recorded this build yet\");\n else if (pending.length) ctx.stderr(`waiting: ${pending.length} of ${runs.length} run(s) still going`);\n }\n if (runsSettled(result)) break;\n if (Date.now() >= deadline) {\n ctx.stderr(`timed out after ${timeout}s; reporting the latest verdict`);\n break;\n }\n await sleep(interval * 1000);\n }\n } else {\n result = await fetchGate(creds, q);\n }\n ctx.stdout(asJson ? JSON.stringify(sortedJson(result), null, 2) : renderTable(result));\n appendStepSummary(stepSummary(result));\n return exitCodeFor(result);\n },\n });\n}\n","import { api } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\nimport { API_KEY_FLAG, credentials, HOST_FLAG, query } from \"./shared\";\n\n/** `gateway run start|verify|list` over /api/public/runs*. */\nexport function registerRunCommands(root: CommandGroup): void {\n const run = root.group(\"run\", \"Manage platform optimization runs.\");\n\n run.command({\n name: \"start\",\n help: \"Start a platform optimization run.\",\n positionals: [{ name: \"algorithm\", help: \"Algorithm name (e.g., gepa)\" }],\n flags: [\n { name: \"agent\", help: \"Registered agent ID\" },\n { name: \"dataset\", help: \"Dataset ID\" },\n { name: \"name\", help: \"Run name\" },\n { name: \"config\", help: \"JSON config string\" },\n HOST_FLAG,\n API_KEY_FLAG,\n ],\n run: async (args, ctx) => {\n const agentId = arg.str(args, \"agent\");\n const datasetId = arg.str(args, \"dataset\");\n if (!agentId || !datasetId) throw new CliError(\"run start needs --agent and --dataset\");\n const payload: Record<string, unknown> = {\n algorithmName: args.positionals[0],\n agentId,\n datasetId,\n };\n const name = arg.str(args, \"name\");\n if (name) payload.name = name;\n const config = arg.str(args, \"config\");\n if (config) {\n try {\n payload.config = JSON.parse(config);\n } catch {\n throw new CliError(\"--config must be a JSON string\");\n }\n }\n const data = await api<Record<string, unknown>>(\n credentials(args),\n \"POST\",\n \"/api/public/runs/start\",\n payload,\n );\n ctx.stdout(\"Run started!\");\n ctx.stdout(` Run ID: ${data.runId}`);\n ctx.stdout(` Run #: ${data.runNumber}`);\n ctx.stdout(` Job ID: ${data.jobId}`);\n ctx.stdout(` Status: ${data.status}`);\n },\n });\n\n run.command({\n name: \"verify\",\n help: \"Verify an algorithm configuration.\",\n positionals: [{ name: \"algorithm\", help: \"Algorithm name\" }],\n flags: [\n { name: \"agent\", help: \"Agent ID\" },\n { name: \"dataset\", help: \"Dataset ID\" },\n HOST_FLAG,\n API_KEY_FLAG,\n ],\n run: async (args, ctx) => {\n const agentId = arg.str(args, \"agent\");\n if (!agentId) throw new CliError(\"run verify needs --agent\");\n const payload: Record<string, unknown> = { algorithmName: args.positionals[0], agentId };\n const datasetId = arg.str(args, \"dataset\");\n if (datasetId) payload.datasetId = datasetId;\n const data = await api<{ jobId?: string }>(credentials(args), \"POST\", \"/api/public/runs/verify\", payload);\n ctx.stdout(`Verify job queued: ${data.jobId}`);\n },\n });\n\n run.command({\n name: \"list\",\n help: \"List runs.\",\n flags: [\n { name: \"source\", help: \"Filter by source (platform/sdk)\" },\n { name: \"limit\", help: \"Max results\", default: \"20\" },\n HOST_FLAG,\n API_KEY_FLAG,\n ],\n run: async (args, ctx) => {\n const data = await api<{ runs?: Record<string, unknown>[] }>(\n credentials(args),\n \"GET\",\n `/api/public/runs${query({ limit: arg.int(args, \"limit\") ?? 20, source: arg.str(args, \"source\") })}`,\n );\n const runs = data.runs ?? [];\n if (runs.length === 0) {\n ctx.stdout(\"No runs found.\");\n return;\n }\n ctx.stdout(`${\"#\".padEnd(6)} ${\"Name\".padEnd(30)} ${\"State\".padEnd(12)} ${\"Source\".padEnd(10)}`);\n ctx.stdout(\"-\".repeat(60));\n for (const r of runs) {\n ctx.stdout(\n `${String(r.runNumber ?? \"\").padEnd(6)} ` +\n `${String(r.name ?? \"\").slice(0, 28).padEnd(30)} ` +\n `${String(r.state ?? \"\").padEnd(12)} ` +\n `${String(r.source ?? \"\").padEnd(10)}`,\n );\n }\n },\n });\n}\n","import { api } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\nimport { API_KEY_FLAG, credentials, failed, HOST_FLAG, rawRequest } from \"./shared\";\n\ntype SecretRow = { name?: string; scope?: string; description?: string; displayValue?: string };\n\n/** `gateway secret set|list|delete` over /api/public/secrets. */\nexport function registerSecretCommands(root: CommandGroup): void {\n const secret = root.group(\"secret\", \"Manage project secrets (encrypted env vars for agent containers).\");\n\n secret.command({\n name: \"set\",\n help: \"Create or update a project secret.\",\n positionals: [{ name: \"name\", help: \"Secret name (UPPER_SNAKE_CASE, e.g. TAVILY_API_KEY)\" }],\n flags: [\n { name: \"value\", short: \"v\", help: \"Secret value. If omitted, it is read from stdin.\" },\n { name: \"description\", short: \"d\", help: \"Human-readable description\" },\n { name: \"scope\", help: \"Scope: agent, worker, or both\", default: \"agent\" },\n HOST_FLAG,\n API_KEY_FLAG,\n ],\n run: async (args, ctx) => {\n const name = args.positionals[0]!;\n const value = arg.str(args, \"value\") ?? (await ctx.stdin()).trim();\n if (!value) throw new CliError(\"empty value — nothing stored (pass --value or pipe stdin)\");\n const creds = credentials(args);\n const payload: Record<string, string> = { name, value, scope: arg.str(args, \"scope\") ?? \"agent\" };\n const description = arg.str(args, \"description\");\n if (description) payload.description = description;\n\n const created = await rawRequest(creds, \"POST\", \"/api/public/secrets\", payload);\n if (created.ok) {\n const data = created.json() as SecretRow;\n ctx.stdout(`Secret '${data.name ?? name}' saved (${data.displayValue ?? \"****\"})`);\n return;\n }\n if (created.status !== 409) throw failed(created.status, created.text);\n const updated = await rawRequest(\n creds,\n \"PUT\",\n `/api/public/secrets/${encodeURIComponent(name)}`,\n payload,\n );\n if (!updated.ok) throw failed(updated.status, updated.text);\n ctx.stdout(`Secret '${name}' updated.`);\n },\n });\n\n secret.command({\n name: \"list\",\n help: \"List project secrets (names and descriptions only, not values).\",\n flags: [HOST_FLAG, API_KEY_FLAG],\n run: async (args, ctx) => {\n const res = await api<{ secrets?: SecretRow[] }>(credentials(args), \"GET\", \"/api/public/secrets\");\n const secrets = res.secrets ?? [];\n if (secrets.length === 0) {\n ctx.stdout(\"No secrets configured. Run `gateway secret set <name>` to add one.\");\n return;\n }\n ctx.stdout(`${\"Name\".padEnd(30)} ${\"Scope\".padEnd(10)} Description`);\n ctx.stdout(\"-\".repeat(70));\n for (const s of secrets) {\n const desc = (s.description ?? \"\").slice(0, 28);\n ctx.stdout(`${(s.name ?? \"\").padEnd(30)} ${(s.scope ?? \"\").padEnd(10)} ${desc}`);\n }\n },\n });\n\n secret.command({\n name: \"delete\",\n help: \"Delete a project secret.\",\n positionals: [{ name: \"name\", help: \"Secret name to delete\" }],\n flags: [HOST_FLAG, API_KEY_FLAG],\n run: async (args, ctx) => {\n const name = args.positionals[0]!;\n await api(credentials(args), \"DELETE\", `/api/public/secrets/${encodeURIComponent(name)}`);\n ctx.stdout(`Secret '${name}' deleted.`);\n },\n });\n}\n","import * as fs from \"node:fs\";\n\nimport { api, printJson } from \"../config\";\nimport { arg, CliError, type CommandGroup } from \"../router\";\nimport {\n attachSession,\n openSession,\n surfaceKinds,\n uiEntryUrl,\n WorldSessionTimeout,\n type BrowserMode,\n type WorldSession,\n type WorldSurfaceKind,\n type WorldTaskRef,\n} from \"../../worlds/index\";\nimport { parseRows, rowsMode, rowsRedact, REDACT_FLAG } from \"./rows\";\nimport { credentials, HOST_FLAG, sleep, worldsOptions, printDeprecations } from \"./shared\";\nimport { landInDrive, scratchFile, TO_FLAG } from \"./worldData/driveIo\";\nimport { readTaskSpec } from \"./task\";\n\nconst SEED_TIMEOUT_MS = 60_000;\nconst SEED_POLL_MS = 1_000;\nconst EXPORT_PAGE = 500;\nconst EXPORT_KEYS = [\n \"args\",\n \"completedAt\",\n \"error\",\n \"kind\",\n \"result\",\n \"seq\",\n \"tool\",\n] as const;\n\nasync function surfacesJson(session: WorldSession) {\n const s = await session.surfaces();\n return {\n sessionId: session.sessionId,\n surfaces: surfaceKinds(s),\n ...(s.api\n ? {\n api: {\n url: s.api.url,\n ...(s.api.token ? { token: s.api.token } : {}),\n },\n }\n : {}),\n ...(s.ui\n ? {\n ui: {\n url: s.ui.url,\n entry: uiEntryUrl(s.ui),\n apiPath: s.ui.apiPath ?? null,\n },\n }\n : {}),\n ...(s.browser\n ? { browser: { wsUrl: s.browser.wsUrl, viewport: s.browser.viewport } }\n : {}),\n };\n}\n\nconst sessionRoute = (id: string) =>\n `/api/public/world-sessions/${encodeURIComponent(id)}`;\n\n/** Exactly one of `--task` (a bundled scenario), `--task-id` (a stored task,\n * optionally `--task-version`) and `--task-file` (a JSON task spec:\n * `{instruction, seed?, grader?, metadata?, name?}`). */\nfunction taskFromFlags(flags: {\n task?: string;\n taskId?: string;\n taskVersion?: number;\n taskFile?: string;\n}): WorldTaskRef {\n const given = [flags.task, flags.taskId, flags.taskFile].filter(Boolean);\n if (given.length > 1)\n throw new CliError(\n \"worlds session open takes one of --task, --task-id or --task-file\",\n );\n if (flags.taskVersion !== undefined && !flags.taskId)\n throw new CliError(\"--task-version needs --task-id\");\n if (flags.task) return flags.task;\n if (flags.taskId)\n return flags.taskVersion === undefined\n ? { id: flags.taskId }\n : { id: flags.taskId, version: flags.taskVersion };\n if (!flags.taskFile)\n throw new CliError(\n \"worlds session open needs --task, --task-id or --task-file\",\n );\n return readTaskSpec(flags.taskFile, \"--task-file\");\n}\n\n/** `gateway worlds session open|status|state|reset|browse|close|seed|export`. */\nexport function registerSessionCommands(root: CommandGroup): void {\n const session = root\n .group(\"worlds\", \"Build, seed, serve and run worlds.\")\n .group(\"session\", \"Live world sessions with api/ui/browser surfaces.\");\n\n session.command({\n name: \"open\",\n help: \"Open a live session and print where it answers.\",\n positionals: [{ name: \"slug\", help: \"World slug (optionally slug@ref).\" }],\n flags: [\n {\n name: \"task\",\n short: \"t\",\n help: \"Bundled task / scenario to open the session on.\",\n },\n {\n name: \"task-id\",\n help: \"Stored task (see `worlds task`) to open the session on instead of --task (host engine worlds).\",\n },\n {\n name: \"task-version\",\n help: \"With --task-id: open that version of the task instead of the current one.\",\n },\n {\n name: \"task-file\",\n help: \"JSON file with an inline task spec {instruction, seed?, grader?, metadata?, name?} instead of --task (host engine worlds).\",\n },\n {\n name: \"surface\",\n short: \"s\",\n help: \"Surface to ask for besides tools: api, ui, browser (repeatable or comma-separated).\",\n repeat: true,\n },\n { name: \"version-id\", help: \"Pin an exact world version.\" },\n {\n name: \"no-wait\",\n help: \"Return as soon as the platform accepts the session.\",\n boolean: true,\n },\n HOST_FLAG,\n ],\n notes:\n \"Prints {sessionId, ready, surfaces, api.url, ui.entry, browser.wsUrl} — the descriptor WorldSession.surfaces\\n\" +\n \"parses. A World Host session's api also carries `token`: send it as `Authorization: Bearer <token>`\\n\" +\n \"(header only, never in the URL) on every request to api.url. The platform refuses (HTTP 400) rather than serving\\n\" +\n \"fewer surfaces than asked.\\n\" +\n \"--task-file supplies the task with the open instead of naming a bundled one: `instruction` (what the agent is\\n\" +\n \"told), `seed` ({mode?, rows}) applied after the snapshot, `grader` ({kind: assertions, checks} or\\n\" +\n \"{kind: python, source}), `metadata` echoed on the session. --task-id opens a copy of a stored task's current\\n\" +\n \"(or --task-version) spec. The output's `task` block carries source (bundled|stored|inline)/name/hash/id/version.\",\n run: async (args, ctx) => {\n const task = taskFromFlags({\n task: arg.str(args, \"task\"),\n taskId: arg.str(args, \"task-id\"),\n taskVersion: arg.int(args, \"task-version\"),\n taskFile: arg.str(args, \"task-file\"),\n });\n const surfaces = arg\n .list(args, \"surface\")\n .flatMap((s) => s.split(\",\"))\n .map((s) => s.trim())\n .filter(Boolean) as WorldSurfaceKind[];\n const live = await openSession(args.positionals[0]!, {\n task,\n versionId: arg.str(args, \"version-id\"),\n surfaces,\n options: worldsOptions(credentials(args)),\n });\n printDeprecations(ctx, live.deprecations);\n const descriptor = async () => ({\n ...(await surfacesJson(live)),\n task: live.taskInfo,\n });\n if (!arg.bool(args, \"no-wait\")) {\n try {\n await live.ready();\n } catch (error) {\n if (!(error instanceof WorldSessionTimeout)) throw error;\n // Still coming (a cold pod takes longer): print where it will answer\n // so the caller polls instead of losing the id.\n printJson(ctx, { ...(await descriptor()), ready: false });\n ctx.stderr(\n `${error.message} Poll \\`gateway worlds session status ${live.sessionId}\\` until ready.`,\n );\n return 1;\n }\n }\n printJson(ctx, { ...(await descriptor()), ready: live.isReady });\n },\n });\n\n session.command({\n name: \"state\",\n help: \"Dump every entity's rows as the live world holds them now.\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const live = await attachSession(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n );\n printJson(ctx, await live.state());\n },\n });\n\n session.command({\n name: \"reset\",\n help: \"Put the world back to its opening state (base data + the task's seed); the call log stays.\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const live = await attachSession(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n );\n await live.reset();\n printJson(ctx, { sessionId: live.sessionId, reset: true });\n },\n });\n\n session.command({\n name: \"grade\",\n help: \"Run the session's task grader against the world's current state and print {reward, rewards, raw}.\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [\n {\n name: \"timeout\",\n help: \"Seconds to wait for the grade; defaults to the grader's budget (a rubric judge gets 15 min).\",\n },\n HOST_FLAG,\n ],\n notes:\n \"Assertions and python graders answer from the engine in seconds. A rubric grader is judged\\n\" +\n \"by the platform's worker; the command waits for that verdict.\",\n run: async (args, ctx) => {\n const timeout = arg.int(args, \"timeout\");\n if (timeout !== undefined && timeout <= 0)\n throw new CliError(\"--timeout must be a positive number of seconds\");\n const timeoutMs = timeout === undefined ? undefined : timeout * 1000;\n const live = await attachSession(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n );\n const grade = await live.grade({ timeoutMs });\n printJson(ctx, { sessionId: live.sessionId, ...grade });\n },\n });\n\n session.command({\n name: \"status\",\n help: \"Print a session's state, tools and surfaces.\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const live = await attachSession(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n );\n const state = await live.status();\n printJson(ctx, { ...state, ...(await surfacesJson(live)) });\n },\n });\n\n session.command({\n name: \"browse\",\n help: \"Open the session's UI in its browser surface and print what the agent would read.\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [\n {\n name: \"mode\",\n help: \"hosted | local | auto (prefers hosted).\",\n default: \"auto\",\n },\n { name: \"path\", help: \"UI path to open instead of the declared entry.\" },\n { name: \"screenshot\", help: \"Write a PNG of the page here.\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const live = await attachSession(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n );\n const browser = await live.browser({\n mode: (arg.str(args, \"mode\") ?? \"auto\") as BrowserMode,\n });\n try {\n const url = await browser.goto(arg.str(args, \"path\"));\n const shot = arg.str(args, \"screenshot\");\n if (shot) fs.writeFileSync(shot, await browser.screenshot());\n printJson(ctx, {\n url,\n title: await browser.title(),\n text: await browser.text(),\n });\n } finally {\n await browser.close();\n }\n },\n });\n\n session.command({\n name: \"close\",\n help: \"End a session.\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [\n {\n name: \"keep-warm\",\n help: \"Hand the container back to the warm pool.\",\n boolean: true,\n },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const live = await attachSession(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n );\n printJson(\n ctx,\n await live.close({ keepWarm: arg.bool(args, \"keep-warm\") }),\n );\n },\n });\n\n session.command({\n name: \"pin\",\n help: \"Pin a session so the idle reaper never closes it: its URL stays up until you close it. --off unpins.\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [\n {\n name: \"off\",\n help: \"Unpin: the session is reaped again after the idle TTL.\",\n boolean: true,\n },\n HOST_FLAG,\n ],\n notes:\n \"A session normally closes after WORLDS_SESSION_IDLE_TTL_MINUTES (30) without a call. Pinned, it runs until\\n\" +\n \"`worlds session close`; the api URL and token from `session open` keep answering. Check it with\\n\" +\n \"`worlds session status <id>` (state, engine, surfaces) or a request to the URL.\",\n run: async (args, ctx) =>\n printJson(\n ctx,\n await api(\n credentials(args),\n \"PATCH\",\n `/api/public/world-sessions/${encodeURIComponent(args.positionals[0]!)}`,\n {\n pinned: !arg.bool(args, \"off\"),\n },\n ),\n ),\n });\n\n session.command({\n name: \"seed\",\n help: \"Put rows into a LIVE session's world and wait for the engine's answer.\",\n positionals: [\n { name: \"session_id\", help: \"Session id.\" },\n {\n name: \"rows\",\n help: \"Rows files: {entity: [rows]} JSON, {entity,row} JSONL, or bare rows.\",\n variadic: true,\n },\n ],\n flags: [\n { name: \"entity\", help: \"The entity bare-row files hold.\" },\n {\n name: \"mode\",\n help: \"append (upsert by primary key) | replace (named entities).\",\n default: \"append\",\n },\n REDACT_FLAG,\n HOST_FLAG,\n ],\n notes:\n 'Posts {kind: \"seed\", args: {mode, rows, redact?}}; the engine applies the rows through the world\\'s contract,\\n' +\n \"so a refused row leaves the session unchanged and the error names it. --redact apply runs the\\n\" +\n \"world's [redact] policy over the rows first; --redact refuse rejects plaintext in a redacted field.\",\n run: async (args, ctx) => {\n const [sessionId, ...files] = args.positionals;\n if (files.length === 0)\n throw new CliError(\"worlds session seed needs at least one rows file\");\n const mode = rowsMode(arg.str(args, \"mode\"));\n const redact = rowsRedact(arg.str(args, \"redact\"));\n const rows = parseRows(files, arg.str(args, \"entity\"));\n const creds = credentials(args);\n const { callId } = await api<{ callId: string }>(\n creds,\n \"POST\",\n `${sessionRoute(sessionId!)}/calls`,\n {\n kind: \"seed\",\n args: { mode, rows, ...(redact !== \"off\" ? { redact } : {}) },\n },\n );\n const deadline = Date.now() + SEED_TIMEOUT_MS;\n for (;;) {\n const call = await api<{\n done?: boolean;\n state: string;\n result: unknown;\n error: string | null;\n }>(\n creds,\n \"GET\",\n `${sessionRoute(sessionId!)}/calls/${encodeURIComponent(callId)}`,\n );\n const settled =\n call.done || call.state === \"completed\" || call.state === \"failed\";\n if (settled) {\n if (call.error || call.state === \"failed\")\n throw new CliError(call.error ?? \"seed failed\", 1);\n printJson(ctx, { sessionId, mode, ...(redact !== \"off\" ? { redact } : {}), result: call.result });\n return;\n }\n if (Date.now() > deadline)\n throw new CliError(\n `Seed call ${callId} still ${call.state} after ${SEED_TIMEOUT_MS / 1000}s.`,\n 1,\n );\n await sleep(SEED_POLL_MS);\n }\n },\n });\n\n session.command({\n name: \"export\",\n help: \"The session's call log as JSONL, one {seq, kind, tool, args, result, error, completedAt} per line, oldest first.\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [\n { name: \"out\", help: \"Write the JSONL here instead of stdout.\" },\n TO_FLAG,\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const sessionId = args.positionals[0]!;\n const creds = credentials(args);\n const calls: Record<string, unknown>[] = [];\n let cursor: string | undefined;\n do {\n const params = new URLSearchParams({ limit: String(EXPORT_PAGE) });\n if (cursor) params.set(\"cursor\", cursor);\n const page = await api<{\n calls: Record<string, unknown>[];\n nextCursor?: string | null;\n }>(\n creds,\n \"GET\",\n `${sessionRoute(sessionId)}/calls?${params.toString()}`,\n );\n calls.push(...page.calls);\n cursor = page.nextCursor ?? undefined;\n } while (cursor);\n const lines = calls.map((call) =>\n JSON.stringify(\n Object.fromEntries(\n EXPORT_KEYS.map((key) => [key, call[key] ?? null]),\n ),\n ),\n );\n const text = lines.join(\"\\n\") + (lines.length ? \"\\n\" : \"\");\n const out = arg.str(args, \"out\");\n const to = arg.str(args, \"to\");\n if (out) {\n fs.writeFileSync(out, text);\n ctx.stdout(`wrote ${lines.length} calls to ${out}`);\n } else if (!to && text) process.stdout.write(text);\n if (!to) return;\n const scratch = out ? null : scratchFile(`${sessionId}.calls.jsonl`);\n if (scratch) fs.writeFileSync(scratch.file, text);\n try {\n const landed = await landInDrive(scratch?.file ?? out!, to, creds);\n ctx.stdout(`wrote ${lines.length} calls to drive:${landed.path}`);\n } finally {\n scratch?.cleanup();\n }\n },\n });\n}\n","import * as fs from \"node:fs\";\n\nimport { printJson } from \"../config\";\nimport { arg, CliError, type CommandGroup, type FlagSpec } from \"../router\";\nimport {\n attachSession,\n createTask,\n deleteTask,\n getTask,\n listTasks,\n updateTask,\n validateTask,\n type WorldTaskSpec,\n} from \"../../worlds/index\";\nimport { credentials, HOST_FLAG, worldsOptions, printDeprecations } from \"./shared\";\n\nconst WORLD_FLAG: FlagSpec = {\n name: \"world\",\n short: \"w\",\n help: \"Pin the task to this world (slug); validated against its contract.\",\n};\nconst NO_WORLD_FLAG: FlagSpec = {\n name: \"no-world\",\n help: \"Unpin the task so it can open on any world.\",\n boolean: true,\n};\nconst MESSAGE_FLAG: FlagSpec = {\n name: \"message\",\n short: \"m\",\n help: \"Note kept with this version.\",\n};\n\n/** A task spec from a JSON file: `{instruction, seed?, grader?, metadata?, name?}`. */\nexport function readTaskSpec(file: string, flag = \"--spec\"): WorldTaskSpec {\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch (error) {\n throw new CliError(\n `${flag} ${file}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (\n !parsed ||\n typeof parsed !== \"object\" ||\n Array.isArray(parsed) ||\n typeof (parsed as { instruction?: unknown }).instruction !== \"string\"\n )\n throw new CliError(\n `${flag} ${file}: a task spec is a JSON object with an \"instruction\" string`,\n );\n return parsed as WorldTaskSpec;\n}\n\n/** `--world <slug>` / `--no-world` → the API's `world` (slug, null, or unset). */\nfunction worldFromFlags(\n world: string | undefined,\n noWorld: boolean,\n): string | null | undefined {\n if (world && noWorld)\n throw new CliError(\"--world and --no-world exclude each other\");\n if (noWorld) return null;\n return world;\n}\n\n/** `--metadata key=value` pairs → the list filter. */\nfunction metadataFromFlags(pairs: string[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const pair of pairs) {\n const eq = pair.indexOf(\"=\");\n if (eq <= 0)\n throw new CliError(\n `--metadata takes key=value, got ${JSON.stringify(pair)}`,\n );\n out[pair.slice(0, eq)] = pair.slice(eq + 1);\n }\n return out;\n}\n\n/** `gateway worlds task create|update|list|show|validate|delete` and\n * `gateway worlds session task save`. */\nexport function registerTaskCommands(root: CommandGroup): void {\n const worlds = root.group(\"worlds\", \"Build, seed, serve and run worlds.\");\n const task = worlds.group(\n \"task\",\n \"Stored tasks: instruction + seed + grader kept by the project, outside any bundle.\",\n );\n\n task.command({\n name: \"create\",\n help: \"Store a task from a JSON spec file; prints the task (version 1).\",\n positionals: [\n {\n name: \"spec\",\n help: \"JSON file: {instruction, seed?, grader?, metadata?, name?}.\",\n },\n ],\n flags: [\n {\n name: \"name\",\n short: \"n\",\n help: \"Task name (default: the spec's `name`).\",\n },\n WORLD_FLAG,\n MESSAGE_FLAG,\n HOST_FLAG,\n ],\n notes:\n \"The same spec `worlds session open --task-file` takes, kept as a project resource so sessions open on it by id\\n\" +\n \"(`session open --task-id <id>`) and grades attribute to the task and its version. --world pins it to one world\\n\" +\n \"and checks the seed and grader entities against that world's contract.\",\n run: async (args, ctx) => {\n const spec = readTaskSpec(args.positionals[0]!, \"spec\");\n const created = await createTask(\n {\n spec,\n name: arg.str(args, \"name\"),\n world: arg.str(args, \"world\"),\n message: arg.str(args, \"message\"),\n },\n worldsOptions(credentials(args)),\n );\n printDeprecations(ctx, created.deprecations);\n printJson(ctx, created);\n },\n });\n\n task.command({\n name: \"update\",\n help: \"Change a task: a new spec becomes the next version; --name/--world change in place.\",\n positionals: [{ name: \"task_id\", help: \"Task id.\" }],\n flags: [\n { name: \"spec\", help: \"JSON spec file that becomes the next version.\" },\n { name: \"name\", short: \"n\", help: \"Rename the task.\" },\n WORLD_FLAG,\n NO_WORLD_FLAG,\n MESSAGE_FLAG,\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const specFile = arg.str(args, \"spec\");\n const world = worldFromFlags(\n arg.str(args, \"world\"),\n arg.bool(args, \"no-world\"),\n );\n const name = arg.str(args, \"name\");\n if (specFile === undefined && world === undefined && name === undefined)\n throw new CliError(\n \"worlds task update needs --spec, --name, --world or --no-world\",\n );\n const updated = await updateTask(\n args.positionals[0]!,\n {\n spec: specFile ? readTaskSpec(specFile) : undefined,\n name,\n world,\n message: arg.str(args, \"message\"),\n },\n worldsOptions(credentials(args)),\n );\n printJson(ctx, updated);\n },\n });\n\n task.command({\n name: \"list\",\n help: \"The project's stored tasks, most recently changed first.\",\n flags: [\n {\n name: \"world\",\n short: \"w\",\n help: \"Only tasks pinned to this world (slug).\",\n },\n {\n name: \"metadata\",\n help: \"Only tasks whose spec metadata has key=value (repeatable).\",\n repeat: true,\n },\n { name: \"page\", help: \"Page number (1-based).\", default: \"1\" },\n { name: \"limit\", help: \"Tasks per page.\", default: \"50\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const page = await listTasks(\n {\n world: arg.str(args, \"world\"),\n metadata: metadataFromFlags(arg.list(args, \"metadata\")),\n page: arg.int(args, \"page\"),\n limit: arg.int(args, \"limit\"),\n },\n worldsOptions(credentials(args)),\n );\n printJson(ctx, page);\n },\n });\n\n task.command({\n name: \"show\",\n help: \"One task with its spec and version history.\",\n positionals: [{ name: \"task_id\", help: \"Task id.\" }],\n flags: [\n {\n name: \"version\",\n help: \"Show this version's spec instead of the current one.\",\n },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const detail = await getTask(\n args.positionals[0]!,\n { version: arg.int(args, \"version\") },\n worldsOptions(credentials(args)),\n );\n printJson(ctx, detail);\n },\n });\n\n task.command({\n name: \"validate\",\n help: \"Check a task's seed and grader entities against a world version without opening a session.\",\n positionals: [{ name: \"task_id\", help: \"Task id.\" }],\n flags: [\n { name: \"version\", help: \"Check this task version (default: current).\" },\n {\n name: \"world\",\n short: \"w\",\n help: \"World (slug) to check against; default the task's pin.\",\n },\n { name: \"version-id\", help: \"Exact world version to check against.\" },\n HOST_FLAG,\n ],\n notes:\n \"Exit 1 with the problems listed when a seed or check names an entity the world does not have.\",\n run: async (args, ctx) => {\n const result = await validateTask(\n args.positionals[0]!,\n {\n version: arg.int(args, \"version\"),\n slug: arg.str(args, \"world\"),\n versionId: arg.str(args, \"version-id\"),\n },\n worldsOptions(credentials(args)),\n );\n printJson(ctx, result);\n if (!result.ok) return 1;\n },\n });\n\n task.command({\n name: \"delete\",\n help: \"Remove a task and every version; open sessions keep their copy.\",\n positionals: [{ name: \"task_id\", help: \"Task id.\" }],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n printJson(\n ctx,\n await deleteTask(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n ),\n );\n },\n });\n\n worlds\n .group(\"session\", \"Live world sessions with api/ui/browser surfaces.\")\n .group(\"task\", \"The task a live session runs.\")\n .command({\n name: \"save\",\n help: \"Promote a session's inline task into a stored task (version 1).\",\n positionals: [{ name: \"session_id\", help: \"Session id.\" }],\n flags: [\n {\n name: \"name\",\n short: \"n\",\n help: \"Task name (default: the spec's `name`).\",\n },\n WORLD_FLAG,\n NO_WORLD_FLAG,\n MESSAGE_FLAG,\n HOST_FLAG,\n ],\n notes:\n \"Default pin is the session's world. A session on a bundled task has nothing to save; one already on a stored\\n\" +\n \"task is refused (409).\",\n run: async (args, ctx) => {\n const live = await attachSession(\n args.positionals[0]!,\n worldsOptions(credentials(args)),\n );\n const saved = await live.saveTask({\n name: arg.str(args, \"name\"),\n world: worldFromFlags(\n arg.str(args, \"world\"),\n arg.bool(args, \"no-world\"),\n ),\n message: arg.str(args, \"message\"),\n });\n printJson(ctx, saved);\n },\n });\n}\n","import * as fs from \"node:fs\";\n\nimport { api, printJson } from \"../config\";\nimport { arg, CliError, type CommandGroup, type FlagSpec, type Parsed } from \"../router\";\nimport { exportTraces, getSession, getTrace, iterateSessions, iterateTraces, type Observation, type Trace, type TraceFilters } from \"../../traces/index\";\nimport { API_KEY_FLAG, credentials, HOST_FLAG, worldsOptions } from \"./shared\";\nimport { landInDrive, scratchFile } from \"./worldData/driveIo\";\nimport { drivePath, isDriveRef } from \"../../files/index\";\n\n/**\n * `gateway traces import <file>`: push OTLP/JSON traces exported by any tool\n * (an OpenTelemetry collector `file` exporter, Braintrust, Arize/Phoenix,\n * Galileo, LangSmith, a hand-written fixture) to the project's OTLP endpoint.\n * The platform normalizes vendor conventions on ingest; this command only\n * batches, optionally stamps resource attributes, and posts.\n */\n\nexport const OTLP_TRACES_ROUTE = \"/api/public/otel/v1/traces\";\n\ntype KeyValue = { key: string; value: Record<string, unknown> };\ntype ResourceSpans = { resource?: { attributes?: KeyValue[] } } & Record<string, unknown>;\nexport type ExportTraceServiceRequest = { resourceSpans: ResourceSpans[] };\n\nconst isObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\n/**\n * Accepts one OTLP request (`{resourceSpans: [...]}`), a bare `resourceSpans`\n * array, a JSON array of requests, or JSONL with one request per line.\n */\nexport function parseOtlpDocument(text: string, fileName = \"input\"): ExportTraceServiceRequest[] {\n const trimmed = text.trim();\n if (!trimmed) throw new CliError(`${fileName} is empty`);\n let values: unknown[];\n try {\n values = [JSON.parse(trimmed)];\n } catch {\n values = trimmed.split(\"\\n\").flatMap((line, i) => {\n if (!line.trim()) return [];\n try {\n return [JSON.parse(line)];\n } catch (err) {\n throw new CliError(`${fileName}:${i + 1} is neither JSON nor a JSONL line: ${(err as Error).message}`);\n }\n });\n }\n const out: ExportTraceServiceRequest[] = [];\n const push = (value: unknown, where: string) => {\n if (Array.isArray(value)) {\n if (value.every((item) => isObject(item) && Array.isArray(item.scopeSpans)))\n return void out.push({ resourceSpans: value as ResourceSpans[] });\n value.forEach((item, i) => push(item, `${where}[${i}]`));\n return;\n }\n if (!isObject(value) || !Array.isArray(value.resourceSpans))\n throw new CliError(`${where} is not an OTLP/JSON trace export: expected {\"resourceSpans\": [...]}`);\n out.push({ resourceSpans: value.resourceSpans as ResourceSpans[] });\n };\n values.forEach((value, i) => push(value, values.length === 1 ? fileName : `${fileName} line ${i + 1}`));\n return out.filter((req) => req.resourceSpans.length);\n}\n\n/** Set (or overwrite) string attributes on every resource of a request. */\nexport function stampResourceAttributes(\n request: ExportTraceServiceRequest,\n attributes: Record<string, string>,\n): ExportTraceServiceRequest {\n const entries = Object.entries(attributes);\n if (!entries.length) return request;\n return {\n resourceSpans: request.resourceSpans.map((rs) => {\n const existing = (rs.resource?.attributes ?? []).filter((kv) => !(kv.key in attributes));\n const added: KeyValue[] = entries.map(([key, value]) => ({ key, value: { stringValue: value } }));\n return { ...rs, resource: { ...(rs.resource ?? {}), attributes: [...existing, ...added] } };\n }),\n };\n}\n\nexport function countSpans(request: ExportTraceServiceRequest): number {\n let n = 0;\n for (const rs of request.resourceSpans) {\n const scopeSpans = Array.isArray(rs.scopeSpans) ? rs.scopeSpans : [];\n for (const ss of scopeSpans) if (isObject(ss) && Array.isArray(ss.spans)) n += ss.spans.length;\n }\n return n;\n}\n\nconst FILTER_FLAGS: FlagSpec[] = [\n { name: \"from\", help: \"Only traces at or after this ISO time.\" },\n { name: \"to\", help: \"Only traces before this ISO time.\" },\n { name: \"session\", help: \"Only traces of this trace session.\" },\n { name: \"user\", help: \"Only traces of this user id.\" },\n { name: \"name\", help: \"Only traces with this name.\" },\n { name: \"tag\", help: \"Only traces carrying this tag; repeat for more.\", repeat: true },\n { name: \"environment\", help: \"Only traces in this tracing environment.\" },\n { name: \"order\", help: \"timestamp.desc (default) | timestamp.asc\" },\n];\nconst JSON_FLAG: FlagSpec = { name: \"json\", help: \"Print the platform's JSON instead of one line per item.\", boolean: true };\n\nfunction filtersOf(args: Parsed): TraceFilters {\n const tags = arg.list(args, \"tag\");\n return {\n fromTimestamp: arg.str(args, \"from\"),\n toTimestamp: arg.str(args, \"to\"),\n sessionId: arg.str(args, \"session\"),\n userId: arg.str(args, \"user\"),\n name: arg.str(args, \"name\"),\n ...(tags.length ? { tags } : {}),\n environment: arg.str(args, \"environment\"),\n orderBy: arg.str(args, \"order\"),\n };\n}\n\nfunction limitOf(args: Parsed, fallback: number): number {\n const limit = arg.int(args, \"limit\") ?? fallback;\n if (limit < 1) throw new CliError(\"--limit must be at least 1\");\n return limit;\n}\n\nconst traceLine = (t: Trace) =>\n [t.id, t.timestamp, t.name ?? \"-\", t.sessionId ? `session=${t.sessionId}` : null, t.userId ? `user=${t.userId}` : null, t.tags?.length ? `tags=${t.tags.join(\",\")}` : null]\n .filter(Boolean)\n .join(\" \");\n\nconst observationLine = (o: Observation) =>\n [o.id, o.type, o.name ?? \"-\", o.startTime, o.level && o.level !== \"DEFAULT\" ? o.level : null, typeof o.model === \"string\" ? o.model : null].filter(Boolean).join(\" \");\n\nexport function registerTracesCommands(root: CommandGroup): void {\n const traces = root.group(\"traces\", \"Traces, observations and trace sessions: list, get, export; import OTLP.\");\n traces.notes =\n \"Everything here reads the public API (GET /api/public/traces, /observations, /sessions) except\\n\" +\n \"`import`. `export` writes one JSON object per line, to a file, stdout (-) or the drive (drive:<path>);\\n\" +\n \"from there `gateway worlds data ingest <world> drive:<path> --transform …` turns the calls into rows.\";\n\n traces.command({\n name: \"list\",\n help: \"Traces matching the filters, newest first: id, timestamp, name, session, user, tags.\",\n flags: [...FILTER_FLAGS, { name: \"limit\", help: \"At most this many (pages of 100 underneath).\", default: \"50\" }, JSON_FLAG, HOST_FLAG],\n run: async (args, ctx) => {\n const options = worldsOptions(credentials(args));\n const listed: Trace[] = [];\n for await (const trace of iterateTraces(options, filtersOf(args), { max: limitOf(args, 50) })) listed.push(trace);\n if (arg.bool(args, \"json\")) return void printJson(ctx, listed);\n if (!listed.length) return void ctx.stderr(\"no traces match\");\n for (const trace of listed) ctx.stdout(traceLine(trace));\n },\n });\n\n traces.command({\n name: \"get\",\n help: \"One trace: its fields, scores and, with --observations, every observation with input and output.\",\n positionals: [{ name: \"traceId\", help: \"Trace id.\" }],\n flags: [\n { name: \"observations\", help: \"Include the observations (they are fetched either way; without this only their count prints).\", boolean: true },\n { name: \"type\", help: \"With --observations: only this observation type (TOOL, GENERATION, SPAN, …).\" },\n JSON_FLAG,\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const detail = await getTrace(worldsOptions(credentials(args)), args.positionals[0]!);\n const type = arg.str(args, \"type\")?.toUpperCase();\n const observations = type ? detail.observations.filter((o) => o.type?.toUpperCase() === type) : detail.observations;\n const withObservations = arg.bool(args, \"observations\");\n if (arg.bool(args, \"json\")) {\n const { observations: _all, ...rest } = detail;\n return void printJson(ctx, withObservations ? { ...rest, observations } : { ...rest, observationCount: observations.length });\n }\n ctx.stdout(traceLine(detail));\n const summary = [\n `observations=${observations.length}`,\n `scores=${detail.scores?.length ?? 0}`,\n detail.latency !== undefined ? `latency=${detail.latency}s` : null,\n detail.totalCost !== undefined ? `cost=${detail.totalCost}` : null,\n ].filter(Boolean);\n ctx.stdout(` ${summary.join(\" \")}`);\n if (withObservations) for (const o of observations) ctx.stdout(` ${observationLine(o)}`);\n },\n });\n\n traces.command({\n name: \"export\",\n help: \"Every matching trace as JSONL (one object per line, ids and timestamps as the API returns them).\",\n positionals: [{ name: \"out\", help: \"File to write, - for stdout, or drive:<path> to land it in the drive.\" }],\n flags: [\n ...FILTER_FLAGS,\n { name: \"observations\", help: \"Attach each trace's observations and scores (one GET /traces/{id} per trace).\", boolean: true },\n { name: \"type\", help: \"With --observations: keep only this observation type (TOOL, GENERATION, SPAN, …).\" },\n { name: \"limit\", help: \"Stop after this many traces (default: all that match).\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const out = args.positionals[0]!;\n const type = arg.str(args, \"type\");\n if (type && !arg.bool(args, \"observations\")) throw new CliError(\"--type filters observations; add --observations\");\n const creds = credentials(args);\n const toStdout = out === \"-\";\n const toDrive = isDriveRef(out) ? drivePath(out) : null;\n const scratch = toDrive ? scratchFile(\"traces.jsonl\") : null;\n const file = toStdout ? null : (scratch?.file ?? out);\n try {\n const sink = file ? fs.createWriteStream(file) : null;\n const write = (record: Record<string, unknown>) => {\n const line = JSON.stringify(record) + \"\\n\";\n if (sink) sink.write(line);\n if (toStdout) process.stdout.write(line);\n };\n const limit = arg.int(args, \"limit\");\n const summary = await exportTraces(worldsOptions(creds), filtersOf(args), { observations: arg.bool(args, \"observations\"), type, max: limit }, write);\n if (sink) await new Promise<void>((resolve, reject) => sink.end((error?: Error | null) => (error ? reject(error) : resolve())));\n const what = `${summary.traces} traces${arg.bool(args, \"observations\") ? ` (${summary.observations} observations)` : \"\"}`;\n if (toDrive) ctx.stderr(`wrote ${what} to drive:${(await landInDrive(file!, toDrive, creds)).path}`);\n else ctx.stderr(toStdout ? `wrote ${what}` : `wrote ${what} to ${out}`);\n } finally {\n scratch?.cleanup();\n }\n },\n });\n\n const sessions = traces.group(\"sessions\", \"Trace sessions: the conversations traces group into.\");\n sessions.command({\n name: \"list\",\n help: \"Trace sessions in a time range, newest first: id, created, environment.\",\n flags: [\n { name: \"from\", help: \"Only sessions created at or after this ISO time.\" },\n { name: \"to\", help: \"Only sessions created before this ISO time.\" },\n { name: \"environment\", help: \"Only sessions in this tracing environment.\" },\n { name: \"limit\", help: \"At most this many.\", default: \"50\" },\n JSON_FLAG,\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const filters = { fromTimestamp: arg.str(args, \"from\"), toTimestamp: arg.str(args, \"to\"), environment: arg.str(args, \"environment\") };\n const listed = [];\n for await (const session of iterateSessions(worldsOptions(credentials(args)), filters, { max: limitOf(args, 50) })) listed.push(session);\n if (arg.bool(args, \"json\")) return void printJson(ctx, listed);\n if (!listed.length) return void ctx.stderr(\"no sessions match\");\n for (const session of listed) ctx.stdout(`${session.id} ${session.createdAt} ${session.environment}`);\n },\n });\n sessions.command({\n name: \"get\",\n help: \"One trace session and its traces; --io attaches every trace's observations with input and output.\",\n positionals: [{ name: \"sessionId\", help: \"Trace session id.\" }],\n flags: [{ name: \"io\", help: \"GET …?includeIO=true: full observations on every trace.\", boolean: true }, JSON_FLAG, HOST_FLAG],\n run: async (args, ctx) => {\n const session = await getSession(worldsOptions(credentials(args)), args.positionals[0]!, { includeIO: arg.bool(args, \"io\") });\n if (arg.bool(args, \"json\")) return void printJson(ctx, session);\n ctx.stdout(`${session.id} ${session.createdAt} ${session.environment} traces=${session.traces.length}`);\n for (const trace of session.traces) {\n ctx.stdout(` ${traceLine(trace)}`);\n for (const o of trace.observations ?? []) ctx.stdout(` ${observationLine(o)}`);\n }\n },\n });\n\n traces.command({\n name: \"import\",\n help: \"POST OTLP/JSON trace exports (a file, several, or `-` for stdin) to this project's OTLP endpoint.\",\n positionals: [{ name: \"file\", help: \"OTLP/JSON or JSONL export; `-` reads stdin\", variadic: true }],\n flags: [\n { name: \"source\", help: \"Label the exporter (braintrust, galileo, arize, …); stored as gateway.otel.source.\" },\n { name: \"world\", help: \"Link every trace to a world slug (gateway.world).\" },\n { name: \"world-version\", help: \"World version label (gateway.world.version).\" },\n { name: \"task\", help: \"Task name (gateway.task).\" },\n { name: \"session\", help: \"Force one session id on every span (gateway.session.id).\" },\n { name: \"environment\", help: \"Tracing environment (gateway.environment).\" },\n { name: \"attr\", help: \"Extra resource attribute key=value; repeatable.\", repeat: true },\n { name: \"dry-run\", help: \"Parse and count; send nothing.\", boolean: true },\n HOST_FLAG,\n API_KEY_FLAG,\n ],\n notes:\n \"Spans keep their own session/user/model/input/output attributes: Braintrust, OpenInference (Arize,\\n\" +\n \"Phoenix, Galileo), OpenTelemetry GenAI, Langfuse and LangSmith conventions are normalized on ingest.\\n\" +\n \"Flags only add resource attributes, so a span's own value always wins.\",\n run: async (args, ctx) => {\n const files = args.positionals.length ? args.positionals : [\"-\"];\n const stamp: Record<string, string> = {};\n const put = (key: string, flag: string) => {\n const value = arg.str(args, flag);\n if (value !== undefined) stamp[key] = value;\n };\n put(\"gateway.otel.source\", \"source\");\n put(\"gateway.world\", \"world\");\n put(\"gateway.world.version\", \"world-version\");\n put(\"gateway.task\", \"task\");\n put(\"gateway.session.id\", \"session\");\n put(\"gateway.environment\", \"environment\");\n for (const item of arg.list(args, \"attr\")) {\n const eq = item.indexOf(\"=\");\n if (eq <= 0) throw new CliError(`--attr looks like key=value, got ${JSON.stringify(item)}`);\n stamp[item.slice(0, eq).trim()] = item.slice(eq + 1);\n }\n\n const requests: ExportTraceServiceRequest[] = [];\n for (const file of files) {\n const text = file === \"-\" ? await ctx.stdin() : readFile(file);\n for (const req of parseOtlpDocument(text, file === \"-\" ? \"stdin\" : file))\n requests.push(stampResourceAttributes(req, stamp));\n }\n const spans = requests.reduce((n, req) => n + countSpans(req), 0);\n if (!spans) throw new CliError(\"No spans found in the input\");\n\n const dryRun = arg.bool(args, \"dry-run\");\n if (!dryRun) {\n const creds = credentials(args);\n for (const req of requests) await api(creds, \"POST\", OTLP_TRACES_ROUTE, req);\n }\n ctx.stdout(\n JSON.stringify(\n {\n status: dryRun ? \"dry-run\" : \"accepted\",\n batches: requests.length,\n spans,\n resourceAttributes: stamp,\n endpoint: OTLP_TRACES_ROUTE,\n },\n null,\n 2,\n ),\n );\n },\n });\n}\n\nfunction readFile(file: string): string {\n if (!fs.existsSync(file)) throw new CliError(`${file} does not exist`, 1);\n return fs.readFileSync(file, \"utf8\");\n}\n","/**\n * Read the project's traces, observations and trace sessions — the public\n * API behind `gateway traces …` and the MCP tools get_trace / get_observations\n * / get_session. Everything here is read-only.\n *\n * GET /api/public/traces?… a page of traces (page 1-based, limit ≤ 100)\n * GET /api/public/traces/{traceId} one trace with its observations and scores\n * GET /api/public/observations?… a page of observations (type, traceId, time window)\n * GET /api/public/sessions?… a page of trace sessions\n * GET /api/public/sessions/{sessionId} one session; includeIO=true attaches every trace's observations\n */\n\nimport { apiRequest, type WorldsClientOptions } from \"../worlds/index\";\n\nexport type TraceFilters = {\n fromTimestamp?: string;\n toTimestamp?: string;\n sessionId?: string;\n userId?: string;\n name?: string;\n tags?: string[];\n environment?: string;\n version?: string;\n release?: string;\n /** `timestamp.asc`, `timestamp.desc` (the default), … */\n orderBy?: string;\n};\n\nexport type ObservationFilters = {\n traceId?: string;\n type?: string;\n name?: string;\n userId?: string;\n level?: string;\n parentObservationId?: string;\n environment?: string;\n version?: string;\n fromStartTime?: string;\n toStartTime?: string;\n};\n\nexport type SessionFilters = { fromTimestamp?: string; toTimestamp?: string; environment?: string };\n\nexport type PageMeta = { page: number; limit: number; totalItems: number; totalPages: number };\nexport type Page<T> = { data: T[]; meta: PageMeta };\n\nexport type Trace = {\n id: string;\n timestamp: string;\n name: string | null;\n sessionId: string | null;\n userId: string | null;\n tags: string[];\n environment?: string;\n [key: string]: unknown;\n};\n\nexport type Observation = {\n id: string;\n traceId: string | null;\n type: string;\n name: string | null;\n startTime: string;\n endTime?: string | null;\n level?: string;\n [key: string]: unknown;\n};\n\nexport type TraceDetail = Trace & { observations: Observation[]; scores: unknown[]; latency?: number; totalCost?: number };\n\nexport type TraceSession = { id: string; createdAt: string; projectId: string; environment: string };\nexport type TraceSessionDetail = TraceSession & { traces: (Trace & { observations?: Observation[] })[] };\n\n/** The platform caps a page at 100. */\nexport const PAGE_LIMIT = 100;\n\ntype Scalar = string | number | boolean | undefined | null;\n\nfunction qs(params: Record<string, Scalar | string[]>): string {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null || value === \"\") continue;\n if (Array.isArray(value)) for (const item of value) search.append(key, item);\n else search.set(key, String(value));\n }\n const text = search.toString();\n return text ? `?${text}` : \"\";\n}\n\nexport async function listTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n page: { page?: number; limit?: number; fields?: string } = {},\n): Promise<Page<Trace>> {\n const { tags, ...rest } = filters;\n return apiRequest<Page<Trace>>(options, \"GET\", `/api/public/traces${qs({ ...rest, tags, page: page.page ?? 1, limit: page.limit ?? 50, fields: page.fields })}`);\n}\n\n/** Page through matching traces, newest first unless `orderBy` says otherwise; `max` stops early. */\nexport async function* iterateTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n limits: { max?: number; fields?: string } = {},\n): AsyncGenerator<Trace> {\n yield* paged((page) => listTraces(options, filters, { page, limit: PAGE_LIMIT, fields: limits.fields }), limits.max);\n}\n\n/** One trace with its observations (input/output included) and scores. */\nexport async function getTrace(options: WorldsClientOptions = {}, traceId: string): Promise<TraceDetail> {\n return apiRequest<TraceDetail>(options, \"GET\", `/api/public/traces/${encodeURIComponent(traceId)}`);\n}\n\nexport async function listObservations(\n options: WorldsClientOptions = {},\n filters: ObservationFilters = {},\n page: { page?: number; limit?: number } = {},\n): Promise<Page<Observation>> {\n return apiRequest<Page<Observation>>(options, \"GET\", `/api/public/observations${qs({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);\n}\n\nexport async function* iterateObservations(\n options: WorldsClientOptions = {},\n filters: ObservationFilters = {},\n limits: { max?: number } = {},\n): AsyncGenerator<Observation> {\n yield* paged((page) => listObservations(options, filters, { page, limit: PAGE_LIMIT }), limits.max);\n}\n\nexport async function listSessions(\n options: WorldsClientOptions = {},\n filters: SessionFilters = {},\n page: { page?: number; limit?: number } = {},\n): Promise<Page<TraceSession>> {\n return apiRequest<Page<TraceSession>>(options, \"GET\", `/api/public/sessions${qs({ ...filters, page: page.page ?? 1, limit: page.limit ?? 50 })}`);\n}\n\nexport async function* iterateSessions(\n options: WorldsClientOptions = {},\n filters: SessionFilters = {},\n limits: { max?: number } = {},\n): AsyncGenerator<TraceSession> {\n yield* paged((page) => listSessions(options, filters, { page, limit: PAGE_LIMIT }), limits.max);\n}\n\n/** One trace session and its traces; `includeIO` attaches every trace's full observations. */\nexport async function getSession(\n options: WorldsClientOptions = {},\n sessionId: string,\n detail: { includeIO?: boolean } = {},\n): Promise<TraceSessionDetail> {\n return apiRequest<TraceSessionDetail>(options, \"GET\", `/api/public/sessions/${encodeURIComponent(sessionId)}${qs({ includeIO: detail.includeIO ? \"true\" : undefined })}`);\n}\n\nexport type ExportOptions = {\n /** Attach each trace's observations (one GET /traces/{id} per trace). */\n observations?: boolean;\n /** With `observations`: keep only this observation type (TOOL, GENERATION, SPAN, …). */\n type?: string;\n /** Stop after this many traces. */\n max?: number;\n};\n\nexport type ExportSummary = { traces: number; observations: number };\n\n/**\n * Every matching trace as one JSON object handed to `write`, ids and\n * timestamps exactly as the API returns them. With `observations`, each object\n * carries its `observations` array (filtered by `type` when given) and the\n * trace's `scores`, from `GET /traces/{id}`.\n */\nexport async function exportTraces(\n options: WorldsClientOptions = {},\n filters: TraceFilters = {},\n exportOptions: ExportOptions = {},\n write: (record: Record<string, unknown>) => void,\n): Promise<ExportSummary> {\n const summary: ExportSummary = { traces: 0, observations: 0 };\n const wantedType = exportOptions.type?.toUpperCase();\n for await (const trace of iterateTraces(options, filters, { max: exportOptions.max })) {\n let record: Record<string, unknown> = trace;\n if (exportOptions.observations) {\n const detail = await getTrace(options, trace.id);\n const observations = wantedType ? detail.observations.filter((o) => o.type?.toUpperCase() === wantedType) : detail.observations;\n summary.observations += observations.length;\n record = { ...detail, observations };\n }\n summary.traces++;\n write(record);\n }\n return summary;\n}\n\nasync function* paged<T>(fetchPage: (page: number) => Promise<Page<T>>, max?: number): AsyncGenerator<T> {\n let yielded = 0;\n for (let page = 1; ; page++) {\n const answer = await fetchPage(page);\n for (const item of answer.data) {\n if (max !== undefined && yielded >= max) return;\n yielded++;\n yield item;\n }\n const totalPages = answer.meta?.totalPages ?? (answer.data.length < PAGE_LIMIT ? page : page + 1);\n if (!answer.data.length || page >= totalPages) return;\n }\n}\n","import type { CommandGroup } from \"../router\";\nimport { registerSchemaCommands } from \"./schema\";\nimport { registerConnectorCommands } from \"./connector\";\nimport { registerRunCommands } from \"./run\";\nimport { registerServeCommand } from \"./serve\";\nimport { registerTestCommand } from \"./test\";\nimport { registerCallCommand } from \"./call\";\nimport { registerScaffoldCommands } from \"./scaffold\";\n\nexport {\n importLocalWorldData,\n checkLocalWorldData,\n showLocalWorldData,\n} from \"./data\";\nexport {\n readWorldFiles,\n writeWorldFiles,\n runtime,\n BridgeRejected,\n formatBridgeError,\n} from \"./client\";\n\n/**\n * Runtime-backed commands: the schema runtime (compiler, store, connector\n * capture/ingest/conform, describe, import-data) is Python and runs on the\n * platform behind `POST /api/public/worlds/runtime`. These commands send a\n * world directory up and write the answer back:\n *\n * worlds schema templates | init | compile | check | describe | api-bundle (Python-only note)\n * worlds schema entity add local: declare one entity in schema/world.json\n * worlds connector validate | capture (--remote) | conform | ingest\n * worlds connector route add local: append one [[operations]] to connector.toml\n * worlds run | ci a TypeScript agent against hosted sessions\n * worlds serve one local session over HTTP (bundled runtime); a hosted api session without one\n * worlds test the world's own tests/ (tool + HTTP cases, pytest) against one local session\n * worlds call one tool call on a local session, a dependency's as alias.tool (local only)\n *\n * Commands that RUN a world (check, test, call) hand the bundled runtime the\n * directory in place (`world`) so its `[dependencies]` paths resolve and its\n * handlers execute; the platform gets `files` and runs no authored code.\n *\n * `worlds data import|show` are registered by the platform track and call\n * `importLocalWorldData` / `showLocalWorldData` for a local directory.\n */\nexport function registerRuntimeCommands(root: CommandGroup): void {\n const worlds = root.group(\"worlds\", \"Build, seed, serve and run worlds.\");\n registerSchemaCommands(\n worlds.group(\n \"schema\",\n \"Compile and check gateway-world/1 contracts (the runtime runs on the platform).\",\n ),\n );\n registerConnectorCommands(\n worlds.group(\n \"connector\",\n \"Vendor connections: validate, capture, conform, ingest, publish, clone.\",\n ),\n );\n registerScaffoldCommands(worlds);\n registerRunCommands(worlds);\n registerServeCommand(worlds);\n registerTestCommand(worlds);\n registerCallCommand(worlds);\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport {\n CliError,\n arg,\n type CommandContext,\n type CommandGroup,\n} from \"../router\";\nimport { api, resolveCredentials, type Credentials } from \"../config\";\nimport {\n credentialsForRuntime,\n localModule,\n localRuntime,\n localRuntimeReason,\n} from \"./local\";\nimport {\n readWorldFiles,\n runtime,\n sortedJson,\n writeWorldFiles,\n type WorldFile,\n} from \"./client\";\n\n/**\n * `gateway worlds connector validate|capture|conform|ingest` — the vendor\n * connection of a schema world. validate/conform/ingest go through the\n * platform runtime; capture is `--remote` only, because a local capture runs\n * the vendor call from this machine with the Python runtime.\n */\n\nconst HOST_FLAG = {\n name: \"host\",\n help: \"Platform host (default: GATEWAY_HOST or the saved login).\",\n env: \"GATEWAY_HOST\",\n};\n\nexport const CAPTURES = \"captures\";\nexport const MANIFEST = \"manifest.json\";\n\n/** `name=value` flags in the order given; a name may repeat, which is how a\n * vendor documents `expand[]=a&expand[]=b`. */\nexport function pairList(values: string[], what: string): [string, string][] {\n const out: [string, string][] = [];\n for (const item of values) {\n const eq = item.indexOf(\"=\");\n if (eq === -1)\n throw new CliError(\n `${what} must look like name=value, got ${JSON.stringify(item)}`,\n );\n out.push([item.slice(0, eq).trim(), item.slice(eq + 1)]);\n }\n return out;\n}\n\nfunction pairs(values: string[], what: string): Record<string, string> {\n return Object.fromEntries(pairList(values, what));\n}\n\n/** What goes on the wire for query parameters: the `{name: value}` form every\n * platform version accepts while no name repeats, the pairs only when one does. */\nexport function wireParams(\n params: Record<string, string> | [string, string][],\n): Record<string, string> | [string, string][] | undefined {\n const list: [string, string][] = Array.isArray(params)\n ? params\n : Object.entries(params);\n if (!list.length) return undefined;\n const names = new Set(list.map(([name]) => name));\n return names.size === list.length ? Object.fromEntries(list) : list;\n}\n\nfunction requireConnectorToml(dir: string): string {\n const file = path.join(dir, \"connector.toml\");\n if (!fs.existsSync(file))\n throw new CliError(`${dir} holds no connector.toml`, 1);\n return fs.readFileSync(file, \"utf8\");\n}\n\ntype Connection = {\n slug: string;\n baseUrl: string;\n auth: string;\n operations: {\n name: string;\n method: string;\n path: string;\n entity?: string | null;\n }[];\n};\n\nexport function renderConnection(spec: Connection): string[] {\n const lines = [`${spec.slug} ${spec.baseUrl} auth=${spec.auth}`];\n for (const op of spec.operations) {\n const target = op.entity ? ` -> ${op.entity}` : \"\";\n lines.push(` ${op.name}: ${op.method} ${op.path}${target}`);\n }\n return lines;\n}\n\n/** `request.undeclared_params` of a capture record, or nothing for any other file. */\nexport function undeclaredParams(record: Buffer | string): string[] {\n try {\n const parsed = JSON.parse(record.toString()) as {\n request?: { undeclared_params?: unknown };\n };\n const names = parsed?.request?.undeclared_params;\n return Array.isArray(names)\n ? names.filter((n): n is string => typeof n === \"string\")\n : [];\n } catch {\n return [];\n }\n}\n\n// ── remote capture (mirror of the Python `_remote_capture`) ─────────────────\n\nconst sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));\n\nasync function resolveEnvironmentId(\n creds: Credentials,\n ref: string,\n): Promise<string> {\n const listing = await api<{ environments?: { id: string; slug: string }[] }>(\n creds,\n \"GET\",\n `/api/public/environments?slug=${encodeURIComponent(ref)}&limit=5`,\n );\n for (const env of listing.environments ?? [])\n if (env.slug === ref) return env.id;\n return ref;\n}\n\ntype CaptureView = {\n stage: string;\n error?: string | null;\n worldSlug?: string;\n files?: { path: string }[];\n manifest?: unknown[];\n};\n\nexport async function remoteCapture(\n creds: Credentials,\n world: string,\n opts: {\n op: string;\n args: Record<string, string>;\n params: Record<string, string> | [string, string][];\n maxPages?: number;\n environment?: string;\n timeoutSeconds: number;\n pollMs?: number;\n },\n ctx: CommandContext,\n): Promise<string[]> {\n const specText = requireConnectorToml(world);\n const containerId = await resolveEnvironmentId(\n creds,\n opts.environment ?? path.basename(path.resolve(world)),\n );\n const base = `/api/public/environments/${encodeURIComponent(containerId)}`;\n const params = wireParams(opts.params);\n const started = await api<{ requestId: string }>(\n creds,\n \"POST\",\n `${base}/connector-captures`,\n {\n connectorToml: specText,\n op: opts.op,\n ...(Object.keys(opts.args).length ? { args: opts.args } : {}),\n ...(params !== undefined ? { params } : {}),\n ...(opts.maxPages !== undefined ? { maxPages: opts.maxPages } : {}),\n },\n );\n const requestId = String(started.requestId);\n ctx.stderr(`# remote capture ${requestId} on ${containerId}`);\n const deadline = Date.now() + opts.timeoutSeconds * 1000;\n let view: CaptureView;\n for (;;) {\n view = await api<CaptureView>(\n creds,\n \"GET\",\n `${base}/connector-captures/${encodeURIComponent(requestId)}`,\n );\n if (view.stage === \"complete\") break;\n if (view.stage === \"failed\" || view.stage === \"cancelled\")\n throw new CliError(\n `Remote capture ${view.stage}: ${view.error || \"no detail\"}`,\n 1,\n );\n if (Date.now() >= deadline)\n throw new CliError(\n `Remote capture still ${view.stage} after ${opts.timeoutSeconds}s; poll it with the request id ${requestId}`,\n 1,\n );\n await sleep(opts.pollMs ?? 5_000);\n }\n const slugPrefix = `worlds/${view.worldSlug}/`;\n const written: string[] = [];\n for (const file of view.files ?? []) {\n const drivePath = String(file.path);\n const relative = drivePath.startsWith(slugPrefix)\n ? drivePath.slice(slugPrefix.length)\n : drivePath;\n if (\n !relative.startsWith(`${CAPTURES}/`) ||\n relative.split(\"/\").includes(\"..\")\n )\n throw new CliError(\n `Refusing a capture outside ${CAPTURES}/: ${drivePath}`,\n 1,\n );\n const info = await api<{ url: string }>(\n creds,\n \"GET\",\n `${base}/files/download?path=${encodeURIComponent(drivePath)}`,\n );\n const res = await fetch(info.url);\n if (!res.ok)\n throw new CliError(`download ${drivePath} -> ${res.status}`, 1);\n const destination = path.join(world, relative);\n fs.mkdirSync(path.dirname(destination), { recursive: true });\n const bytes = Buffer.from(await res.arrayBuffer());\n fs.writeFileSync(destination, bytes);\n written.push(relative);\n // The runtime sends a --param the operation does not declare rather than refusing\n // it, and says so in the record; surface that here so a typo is seen, not guessed at.\n for (const name of undeclaredParams(bytes))\n ctx.stderr(\n `# note: ${name} is not declared by operation ${opts.op} in connector.toml; sent as given`,\n );\n }\n const manifestPath = path.join(world, CAPTURES, MANIFEST);\n const existing: unknown[] = fs.existsSync(manifestPath)\n ? (JSON.parse(fs.readFileSync(manifestPath, \"utf8\")) as unknown[])\n : [];\n const known = new Set(\n existing.map((e) =>\n e && typeof e === \"object\" ? (e as { file?: unknown }).file : undefined,\n ),\n );\n for (const entry of view.manifest ?? []) {\n if (!entry || typeof entry !== \"object\") continue;\n const file = (entry as { file?: unknown }).file;\n if (known.has(file)) continue;\n existing.push(entry);\n known.add(file);\n }\n fs.mkdirSync(path.dirname(manifestPath), { recursive: true });\n fs.writeFileSync(manifestPath, sortedJson(existing, 1) + \"\\n\");\n return written;\n}\n\n// ── conform ──────────────────────────────────────────────────────────────────\n\ntype ConformOutcome = {\n operation: string;\n method: string;\n path: string;\n documented: boolean;\n ok?: boolean;\n status?: number | null;\n expected?: string[];\n problems?: string[];\n schema?: string;\n};\n\ntype ConformReport = {\n /** `Report.to_json()` names the list `operations`; older payloads said `outcomes`. */\n operations?: ConformOutcome[];\n outcomes?: ConformOutcome[];\n summary?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\n/** Python's `Outcome.ok`: documented, answered a documented status, and no\n * schema violation. `ok` on the wire wins when a payload carries it. */\nexport function outcomeOk(outcome: ConformOutcome): boolean {\n if (typeof outcome.ok === \"boolean\") return outcome.ok;\n return (\n outcome.documented &&\n outcome.status != null &&\n (outcome.expected ?? []).includes(String(outcome.status)) &&\n (outcome.schema === \"ok\" || outcome.schema === \"no-schema\")\n );\n}\n\nexport function renderConformOutcome(outcome: ConformOutcome): string {\n const mark = !outcome.documented\n ? \" ? \"\n : outcomeOk(outcome)\n ? \" ok \"\n : \" FAIL\";\n let detail = outcome.documented ? \"\" : \"not in the document\";\n const expected = outcome.expected ?? [];\n const problems = outcome.problems ?? [];\n if (\n outcome.documented &&\n outcome.status != null &&\n !expected.includes(String(outcome.status))\n )\n detail = `status ${outcome.status}, vendor documents ${expected.join(\", \")}`;\n else if (problems.length)\n detail =\n problems[0]! + (problems.length > 1 ? ` (+${problems.length - 1})` : \"\");\n return `${mark} ${outcome.method.padEnd(6)} ${outcome.path.padEnd(60)} ${outcome.operation} ${detail}`;\n}\n\n/** Python `connector.check`: the ingest dry run. A refusal is the `data import --report`\n * record plus `capture`, the file the row came from (`chunk` is null: captures are not chunks). */\ntype IngestCheck = {\n captures?: number;\n rows?: number;\n entities?: Record<string, number>;\n refusals?: {\n capture: string | null;\n chunk: number | null;\n index: number | null;\n entity: string | null;\n primaryKey: Record<string, unknown> | null;\n field: string | null;\n pointer: string;\n detail: string;\n }[];\n summary?: {\n refused: number;\n by_capture: Record<string, number>;\n by_entity: Record<string, number>;\n };\n};\n\n// ── the commands ─────────────────────────────────────────────────────────────\n\nexport function registerConnectorCommands(connector: CommandGroup): void {\n connector.command({\n name: \"validate\",\n help: \"Parse connector.toml and list its operations.\",\n positionals: [\n { name: \"path\", help: \"World directory holding connector.toml\" },\n ],\n flags: [HOST_FLAG],\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n requireConnectorToml(dir);\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const res = await runtime<{\n summary?: { connection?: Connection | null };\n }>(creds, {\n command: \"template-summary\",\n files: readWorldFiles(dir),\n });\n const connection = res.summary?.connection;\n if (!connection)\n throw new CliError(\n \"The runtime read no vendor connection from this world\",\n 1,\n );\n for (const line of renderConnection(connection)) ctx.stdout(line);\n },\n });\n\n connector.command({\n name: \"capture\",\n help: \"Call the live connection once (following its cursor) and record every page under captures/.\",\n notes:\n \"The platform makes the calls (--remote) — from the pod whose IP the vendor allow-listed, with the\\n\" +\n \"credential held as the environment's secret (`gateway secret set`) — and the redacted pages land in\\n\" +\n \"captures/ here, ready for `connector ingest`. A local capture runs the vendor call from this machine\\n\" +\n \"and runs on this machine when a python3 >= 3.11 is installed (the CLI bundles the runtime).\",\n positionals: [\n { name: \"path\", help: \"World directory holding connector.toml\" },\n ],\n flags: [\n { name: \"op\", help: \"Operation name from connector.toml\" },\n {\n name: \"arg\",\n help: \"Path argument, name=value (repeatable)\",\n repeat: true,\n },\n {\n name: \"param\",\n help:\n \"Query parameter, name=value (repeatable; repeat a name to send it twice, e.g. expand[]=a expand[]=b). \" +\n \"A name the operation does not declare is sent as given, with a note.\",\n repeat: true,\n },\n { name: \"max-pages\", help: \"Override [capture].max_pages\" },\n {\n name: \"remote\",\n help: \"Run the capture on the platform and pull the pages into captures/ here.\",\n boolean: true,\n },\n {\n name: \"environment\",\n help: \"Environment slug or id for --remote (default: the world's directory name)\",\n },\n {\n name: \"timeout\",\n help: \"Seconds to wait for a --remote capture\",\n default: \"900\",\n },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const op = arg.str(args, \"op\");\n if (!op) throw new CliError(\"capture needs --op\");\n if (!arg.bool(args, \"remote\")) {\n // A local capture calls the vendor from this machine with the\n // credential from the environment variable connector.toml names —\n // the bundled runtime does it when a python3 is here.\n const local = localRuntime();\n if (!local)\n throw new CliError(\n \"local capture runs the vendor call from this machine and needs python3 >= 3.11 \" +\n `(the CLI bundles the runtime). ${localRuntimeReason()} Or use --remote to capture from the platform.`,\n );\n const argv = [\"connector-capture\", dir, \"--op\", op];\n for (const pair of arg.list(args, \"arg\")) argv.push(\"--arg\", pair);\n for (const pair of arg.list(args, \"param\")) argv.push(\"--param\", pair);\n const maxPages = arg.int(args, \"max-pages\");\n if (maxPages !== undefined) argv.push(\"--max-pages\", String(maxPages));\n return localModule(argv, local);\n }\n const creds = resolveCredentials(arg.str(args, \"host\"));\n const written = await remoteCapture(\n creds,\n dir,\n {\n op,\n args: pairs(arg.list(args, \"arg\"), \"--arg\"),\n params: pairList(arg.list(args, \"param\"), \"--param\"),\n maxPages: arg.int(args, \"max-pages\"),\n environment: arg.str(args, \"environment\"),\n timeoutSeconds: arg.int(args, \"timeout\") ?? 900,\n },\n ctx,\n );\n for (const file of written) ctx.stdout(file);\n },\n });\n\n connector.command({\n name: \"conform\",\n help:\n \"Serve the world and check every operation's answer against the vendor's OpenAPI: the documented \" +\n \"status, and a body the vendor's response schema accepts.\",\n positionals: [\n { name: \"path\", help: \"World directory holding connector.toml\" },\n ],\n flags: [\n {\n name: \"openapi\",\n help: \"The vendor's OpenAPI document (JSON or YAML); repeatable\",\n repeat: true,\n },\n { name: \"out\", help: \"Write the full report as JSON here\" },\n { name: \"limit\", help: \"Check only the first N operations\" },\n HOST_FLAG,\n ],\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const documents = arg.list(args, \"openapi\");\n if (!documents.length)\n throw new CliError(\"conform needs --openapi FILE (repeatable)\");\n requireConnectorToml(dir);\n const openapi: WorldFile[] = documents.map((file) => {\n if (!fs.existsSync(file))\n throw new CliError(`--openapi ${file} does not exist`);\n return {\n path: path.basename(file),\n content: fs.readFileSync(file).toString(\"base64\"),\n };\n });\n const limit = arg.int(args, \"limit\");\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const res = await runtime<{ report?: ConformReport }>(creds, {\n command: \"conform\",\n files: readWorldFiles(dir),\n openapi,\n ...(limit !== undefined ? { max_operations: limit } : {}),\n });\n const report = res.report ?? {};\n for (const outcome of report.operations ?? report.outcomes ?? [])\n ctx.stdout(renderConformOutcome(outcome));\n const summary = report.summary ?? {};\n ctx.stdout(JSON.stringify(summary));\n const out = arg.str(args, \"out\");\n if (out) {\n fs.writeFileSync(out, JSON.stringify(report, null, 1) + \"\\n\");\n ctx.stdout(`report: ${out}`);\n }\n return Number(summary.status_mismatch) ||\n Number(summary.schema_violations)\n ? 1\n : 0;\n },\n });\n\n connector.command({\n name: \"ingest\",\n help: \"Seed data/initial.json from the successful captures, gated by the world's contract.\",\n positionals: [{ name: \"path\", help: \"World directory holding captures/\" }],\n flags: [\n {\n name: \"batch-id\",\n help: \"Batch id; defaults to the next initial version\",\n },\n {\n name: \"dry-run\",\n help: \"Check every row of every capture against the contract and list every refusal; write nothing.\",\n boolean: true,\n },\n {\n name: \"report\",\n help: \"With --dry-run: write the refusals as JSONL here (the `data import --report` records, plus `capture`).\",\n },\n HOST_FLAG,\n ],\n notes:\n \"An ingest stops at the first row the contract refuses; --dry-run reports all of them at once, grouped\\n\" +\n \"by capture, entity and pointer, so a forty-capture world is fixed in one pass. Exit 2 when any row is refused.\",\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n if (!fs.existsSync(path.join(dir, CAPTURES)))\n throw new CliError(\n `${dir} holds no ${CAPTURES}/ — run \\`connector capture --remote\\` first`,\n 1,\n );\n const batchId = arg.str(args, \"batch-id\");\n const dryRun = arg.bool(args, \"dry-run\");\n const report = arg.str(args, \"report\");\n if (report && !dryRun)\n throw new CliError(\"--report belongs to `connector ingest --dry-run`\");\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n if (dryRun) {\n const res = await runtime<{ result?: IngestCheck }>(creds, {\n command: \"ingest\",\n files: readWorldFiles(dir),\n dry_run: true,\n });\n const result = res.result ?? {};\n const refusals = result.refusals ?? [];\n ctx.stdout(\n `${result.captures ?? 0} captures, ${result.rows ?? 0} rows, ${refusals.length} refused`,\n );\n for (const [entity, count] of Object.entries(\n result.entities ?? {},\n ).sort())\n ctx.stdout(` ${entity}: ${count} ok`);\n for (const refusal of refusals)\n ctx.stdout(\n ` ${refusal.capture ?? \"?\"} ${refusal.pointer}: ${refusal.detail}`,\n );\n if (report) {\n fs.writeFileSync(\n report,\n refusals.map((r) => JSON.stringify(r) + \"\\n\").join(\"\"),\n );\n ctx.stdout(`report: ${report}`);\n }\n return refusals.length ? 2 : 0;\n }\n // The real ingest: the dry run returned above, so this request is the\n // one every runtime has always seen.\n const res = await runtime<{\n result?: {\n batch?: string;\n mutations?: number;\n entity_counts?: Record<string, number>;\n };\n files?: WorldFile[];\n }>(creds, {\n command: \"ingest\",\n files: readWorldFiles(dir),\n ...(batchId ? { batch_id: batchId } : {}),\n });\n if (res.files?.length) writeWorldFiles(dir, res.files);\n const result = res.result ?? {};\n ctx.stdout(\n `batch ${result.batch ?? \"?\"}: ${result.mutations ?? 0} mutations`,\n );\n for (const [entity, count] of Object.entries(\n result.entity_counts ?? {},\n ).sort())\n ctx.stdout(` ${entity}: ${count}`);\n },\n });\n}\n\n// ── ingest report ────────────────────────────────────────────────────────────\n\ntype IngestReportRow = Record<string, unknown>;\n\n/** The report's rows, whatever the runtime's envelope: a bare list, or an\n * object whose list-valued members (`entries`, `refusals`, `rows`, …) are the\n * rows. Each row names its `capture` (or `file`), `entity` and `pointer`\n * (or `field`); anything else on it is the detail. */\nfunction ingestReportRows(report: unknown): IngestReportRow[] {\n if (Array.isArray(report))\n return report.filter((row) => row && typeof row === \"object\");\n if (!report || typeof report !== \"object\") return [];\n const rows: IngestReportRow[] = [];\n for (const value of Object.values(report as Record<string, unknown>))\n if (Array.isArray(value))\n rows.push(...value.filter((row) => row && typeof row === \"object\"));\n return rows;\n}\n\nconst ROW_KEYS = new Set([\n \"capture\",\n \"file\",\n \"source\",\n \"entity\",\n \"pointer\",\n \"field\",\n]);\n\nfunction rowText(row: IngestReportRow): string {\n for (const key of [\"detail\", \"message\", \"reason\", \"status\"])\n if (typeof row[key] === \"string\" && row[key]) return row[key] as string;\n const rest = Object.fromEntries(\n Object.entries(row).filter(([key]) => !ROW_KEYS.has(key)),\n );\n return Object.keys(rest).length ? JSON.stringify(rest) : \"\";\n}\n\n/** The report grouped capture → entity → pointer, one indented line each. */\nexport function renderIngestReport(report: unknown): string[] {\n const rows = ingestReportRows(report);\n if (!rows.length)\n return [\n report === undefined\n ? \"report: none returned (the runtime predates --report)\"\n : \"report: nothing to report\",\n ];\n const grouped = new Map<string, Map<string, string[]>>();\n for (const row of rows) {\n const capture = String(\n row.capture ?? row.file ?? row.source ?? \"(no capture)\",\n );\n const entity = String(row.entity ?? \"(no entity)\");\n const pointer = String(row.pointer ?? row.field ?? \"\");\n const text = rowText(row);\n const line = [pointer, text].filter(Boolean).join(\" \");\n const entities = grouped.get(capture) ?? new Map<string, string[]>();\n grouped.set(capture, entities);\n entities.set(entity, [...(entities.get(entity) ?? []), line]);\n }\n const lines = [\n `report: ${rows.length} ${rows.length === 1 ? \"entry\" : \"entries\"}`,\n ];\n for (const [capture, entities] of [...grouped].sort(([a], [b]) =>\n a.localeCompare(b),\n )) {\n lines.push(`${capture}`);\n for (const [entity, pointers] of [...entities].sort(([a], [b]) =>\n a.localeCompare(b),\n )) {\n lines.push(` ${entity}`);\n for (const pointer of pointers) lines.push(` ${pointer}`.trimEnd());\n }\n }\n return lines;\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nimport { CliError, arg, type CommandContext, type CommandGroup, type Parsed } from \"../router\";\nimport { resolveCredentials, type Credentials } from \"../config\";\nimport { openWorld, type WorldsClientOptions } from \"../../worlds/index\";\nimport { openSession, type WorldSession } from \"../../worlds/session\";\nimport type { WorldSurfaceKind } from \"../../worlds/browser\";\nimport { push, readLocalMeta } from \"../../worlds/hub\";\nimport { validateWorld } from \"../../worlds/validate\";\n\n/**\n * `gateway worlds run` and `gateway worlds ci`: a TypeScript agent module\n * against HOSTED sessions of a world. The Python `worlds run` executes the\n * world in-process; TypeScript cannot (a world's tools are Python), so every\n * task here is a live session the platform hosts — your agent stays where it\n * is and calls into the container through `WorldSession`.\n */\n\nexport type AgentTask = { name: string; instruction: string };\nexport type AgentModule = (session: WorldSession, task: AgentTask) => Promise<void>;\n\nconst HOST_FLAG = {\n name: \"host\",\n help: \"Platform host (default: GATEWAY_HOST or the saved login).\",\n env: \"GATEWAY_HOST\",\n};\n\nconst toOptions = (creds: Credentials): WorldsClientOptions => ({\n host: creds.host,\n publicKey: creds.publicKey,\n secretKey: creds.secretKey,\n});\n\n/** Import the agent module. `.js/.mjs/.cjs` load directly; a `.ts` file loads\n * through `tsx` (or `ts-node`) when one is installed next to the agent,\n * otherwise the user builds to JavaScript first. */\nexport async function loadAgent(file: string): Promise<AgentModule> {\n const abs = path.resolve(file);\n if (!fs.existsSync(abs)) throw new CliError(`--agent ${file} does not exist`);\n const ext = path.extname(abs);\n if (ext === \".ts\" || ext === \".mts\" || ext === \".cts\") await registerTypeScriptLoader(abs);\n else if (![\".js\", \".mjs\", \".cjs\"].includes(ext))\n throw new CliError(`--agent must be a .js/.mjs/.cjs or .ts module, got ${ext || \"no extension\"}`);\n const mod = (await import(pathToFileURL(abs).href)) as Record<string, unknown>;\n let candidate: unknown = mod.default ?? mod.agent ?? mod;\n if (candidate && typeof candidate === \"object\" && \"default\" in (candidate as object))\n candidate = (candidate as { default: unknown }).default;\n if (typeof candidate !== \"function\")\n throw new CliError(\n `${file} must default-export an agent: async (session, task) => void (see @withgateway/sdk/worlds WorldSession)`,\n );\n return candidate as AgentModule;\n}\n\nasync function registerTypeScriptLoader(agentPath: string): Promise<void> {\n // Resolve relative to the AGENT, so the user's own devDependency is found\n // — this package deliberately has no runtime dependencies.\n const { createRequire } = await import(\"node:module\");\n const localRequire = createRequire(agentPath);\n const loaders: (() => Promise<void>)[] = [\n async () => {\n const tsx = localRequire.resolve(\"tsx/esm/api\");\n const mod = (await import(pathToFileURL(tsx).href)) as { register?: () => void };\n if (typeof mod.register !== \"function\") throw new Error(\"tsx has no register()\");\n mod.register();\n },\n async () => {\n localRequire(\"ts-node/register\");\n },\n ];\n for (const load of loaders) {\n try {\n await load();\n return;\n } catch {\n // try the next loader\n }\n }\n throw new CliError(\n `${agentPath} is TypeScript and neither tsx nor ts-node is installed next to it. ` +\n \"Add `tsx` as a devDependency, or build the agent to .js and pass that.\",\n );\n}\n\n// ── the world to run against ─────────────────────────────────────────────────\n\nexport type RunTarget = {\n slug: string;\n ref: string | null;\n /** Pinned version every session opens on; null = the ref's head. */\n versionId: string | null;\n /** A local directory, when the target was one. */\n dir: string | null;\n};\n\n/** `<dir>` reads `.gateway/.env-metadata.json` (written by push/pull) for the\n * slug and pinned version; `<slug[@ref]>` is the platform world. */\nexport function resolveTarget(target: string, versionFlag?: string): RunTarget {\n if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {\n const dir = path.resolve(target);\n const meta = readLocalMeta(dir);\n return {\n slug: (meta?.slug as string | undefined) ?? path.basename(dir),\n ref: (meta?.branch as string | undefined) ?? null,\n versionId: versionFlag ?? meta?.versionId ?? null,\n dir,\n };\n }\n const at = target.indexOf(\"@\");\n return {\n slug: at === -1 ? target : target.slice(0, at),\n ref: at === -1 ? null : target.slice(at + 1),\n versionId: versionFlag ?? null,\n dir: null,\n };\n}\n\nasync function resolveTasks(\n target: RunTarget,\n args: Parsed,\n creds: Credentials,\n): Promise<{ tasks: string[]; versionId: string | null }> {\n const one = arg.str(args, \"task\");\n if (one && !arg.bool(args, \"all\")) return { tasks: [one], versionId: target.versionId };\n if (!arg.bool(args, \"all\")) throw new CliError(\"pass --task <name> or --all\");\n const world = await openWorld(target.ref ? `${target.slug}@${target.ref}` : target.slug, toOptions(creds));\n if (!world.tasks.length) throw new CliError(`${target.slug} declares no tasks`, 1);\n return {\n tasks: world.tasks.map((t) => t.name),\n versionId: target.versionId ?? world.version.versionId,\n };\n}\n\n// ── running ──────────────────────────────────────────────────────────────────\n\nexport type TaskResult = {\n task: string;\n sessionId: string;\n reward: number | null;\n rewards: Record<string, number>;\n error?: string;\n};\n\nexport type RunSummary = {\n world: { slug: string; versionId: string | null };\n agent: string;\n results: TaskResult[];\n /** Mean reward over every task, a failed task counting 0. */\n mean: number;\n};\n\nexport async function runTasks(opts: {\n target: RunTarget;\n versionId: string | null;\n tasks: string[];\n agent: AgentModule;\n agentName: string;\n surfaces: WorldSurfaceKind[];\n timeoutMs?: number;\n creds: Credentials;\n ctx: CommandContext;\n}): Promise<RunSummary> {\n const options = toOptions(opts.creds);\n const results: TaskResult[] = [];\n for (const task of opts.tasks) {\n let session: WorldSession | null = null;\n try {\n session = await openSession(opts.target.slug, task, {\n ...(opts.versionId ? { versionId: opts.versionId } : {}),\n ...(opts.surfaces.length ? { surfaces: opts.surfaces } : {}),\n options,\n });\n opts.ctx.stderr(`# ${task}: session ${session.sessionId}`);\n await session.ready({ timeoutMs: opts.timeoutMs });\n await opts.agent(session, { name: task, instruction: session.instruction ?? task });\n const graded = await session.grade({ timeoutMs: opts.timeoutMs });\n results.push({ task, sessionId: session.sessionId, reward: graded.reward, rewards: graded.rewards });\n } catch (error) {\n results.push({\n task,\n sessionId: session?.sessionId ?? \"\",\n reward: 0,\n rewards: {},\n error: (error instanceof Error ? error.message : String(error)) || \"Unknown error\",\n });\n } finally {\n await session?.close().catch(() => undefined);\n }\n }\n const mean = results.reduce((sum, r) => sum + (r.reward ?? 0), 0) / (results.length || 1);\n return {\n world: { slug: opts.target.slug, versionId: opts.versionId },\n agent: opts.agentName,\n results,\n mean,\n };\n}\n\nfunction parseSurfaces(value: string | undefined): WorldSurfaceKind[] {\n return (value ?? \"\")\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s && s !== \"tools\") as WorldSurfaceKind[];\n}\n\nfunction timeoutMs(args: Parsed): number | undefined {\n const minutes = arg.int(args, \"timeout-min\");\n return minutes === undefined ? undefined : minutes * 60_000;\n}\n\nconst RUN_FLAGS = [\n { name: \"agent\", short: \"a\", help: \"Agent module (.js/.mjs/.cjs, or .ts with tsx installed) whose default export is async (session, task) => void.\" },\n { name: \"task\", short: \"t\", help: \"Run this one task.\" },\n { name: \"all\", help: \"Run every task in the world's task set.\", boolean: true },\n { name: \"version-id\", help: \"Pin every session to this version (default: the dir's recorded base, else the ref's head).\" },\n { name: \"surface\", short: \"s\", help: \"Surfaces to open besides tools, comma-separated: api,ui,browser.\", default: \"\" },\n { name: \"timeout-min\", help: \"Minutes to wait for a container to be ready, and for a grade.\" },\n HOST_FLAG,\n];\n\n/** The Python `_ci_finish`: a step-summary table under GitHub Actions. */\nexport function writeStepSummary(title: string, rows: [string, string][]): void {\n const summaryPath = process.env.GITHUB_STEP_SUMMARY;\n if (!summaryPath) return;\n const lines = [`### ${title}`, \"\", \"| | |\", \"|---|---|\", ...rows.map(([k, v]) => `| ${k} | ${v} |`)];\n try {\n fs.appendFileSync(summaryPath, lines.join(\"\\n\") + \"\\n\\n\");\n } catch {\n // the summary is a nicety; the gate is the contract\n }\n}\n\nexport function registerRunCommands(worlds: CommandGroup): void {\n worlds.command({\n name: \"run\",\n help: \"Run a TypeScript agent module against hosted sessions of a world and print the graded results.\",\n notes:\n \" gateway worlds run ./acme-world --agent ./agent.mjs --all\\n\" +\n \" gateway worlds run acme-world@main --agent ./agent.ts --task acme-alice-dedupe\\n\\n\" +\n \"Each task opens one live session; the agent gets (session, {name, instruction}) and uses\\n\" +\n \"session.call / session.toolkit(); the task's own grader scores the end state.\",\n positionals: [{ name: \"world\", help: \"World directory (pushed or pulled), or a platform slug[@ref].\" }],\n flags: RUN_FLAGS,\n run: async (args, ctx) => {\n const agentFile = arg.str(args, \"agent\");\n if (!agentFile) throw new CliError(\"run needs --agent <module>\");\n const creds = resolveCredentials(arg.str(args, \"host\"));\n const target = resolveTarget(args.positionals[0]!, arg.str(args, \"version-id\"));\n const agent = await loadAgent(agentFile);\n const { tasks, versionId } = await resolveTasks(target, args, creds);\n const summary = await runTasks({\n target,\n versionId,\n tasks,\n agent,\n agentName: agentFile,\n surfaces: parseSurfaces(arg.str(args, \"surface\")),\n timeoutMs: timeoutMs(args),\n creds,\n ctx,\n });\n ctx.stdout(JSON.stringify(summary, null, 2));\n return summary.results.some((r) => r.error) ? 1 : 0;\n },\n });\n\n worlds.command({\n name: \"ci\",\n help: \"Push the checked-out world, run every task, and exit 1 below --min-score — the PR gate in one command.\",\n notes:\n \" gateway worlds ci ./acme-world --agent ./agent.mjs --min-score 0.7\\n\" +\n \" gateway worlds ci ./acme-world --run-config nightly --min-score 0.7\\n\\n\" +\n \"The branch defaults to GITHUB_HEAD_REF (PRs), then GITHUB_REF_NAME, then the dir's recorded branch.\\n\" +\n \"--run-config dispatches a hosted run config against the pushed version instead of a local agent.\\n\" +\n \"Writes a $GITHUB_STEP_SUMMARY table under GitHub Actions.\",\n positionals: [{ name: \"path\", help: \"World directory inside the checked-out repo.\" }],\n flags: [\n ...RUN_FLAGS.filter((f) => ![\"task\", \"all\"].includes(f.name)),\n { name: \"run-config\", help: \"Dispatch this run config (name or id) on the platform instead of running --agent.\" },\n { name: \"min-score\", help: \"Reward gate: exit 1 when the mean reward lands below this bar.\" },\n { name: \"summary-file\", help: \"Write the JSON summary here as well as to stdout.\" },\n { name: \"branch\", short: \"b\", help: \"Hub branch to push and run.\" },\n { name: \"message\", short: \"M\", help: \"Push change reason (default: a CI commit line).\" },\n ],\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())\n throw new CliError(`path is not a directory: ${args.positionals[0]}`);\n const agentFile = arg.str(args, \"agent\");\n const runConfig = arg.str(args, \"run-config\");\n if (!agentFile && !runConfig) throw new CliError(\"ci needs --agent <module> or --run-config <name>\");\n const minScoreRaw = arg.str(args, \"min-score\");\n const minScore = minScoreRaw === undefined ? null : Number(minScoreRaw);\n if (minScore !== null && !(minScore >= 0 && minScore <= 1))\n throw new CliError(\"--min-score must be a number between 0 and 1\");\n const creds = resolveCredentials(arg.str(args, \"host\"));\n const options = toOptions(creds);\n const meta = readLocalMeta(dir) ?? {};\n const branch =\n arg.str(args, \"branch\") ||\n process.env.GITHUB_HEAD_REF ||\n process.env.GITHUB_REF_NAME ||\n (meta.branch as string | undefined) ||\n (meta.ref as string | undefined) ||\n \"main\";\n const sha = (process.env.GITHUB_SHA ?? \"\").slice(0, 12);\n const repo = process.env.GITHUB_REPOSITORY ?? \"\";\n const message = arg.str(args, \"message\") ?? (repo && sha ? `[ci] ${repo}@${sha}` : \"[ci] working tree\");\n const summaryFile = arg.str(args, \"summary-file\");\n\n if (runConfig) {\n const report = await validateWorld(dir, {\n runConfig,\n branch,\n minScore,\n timeoutMinutes: arg.int(args, \"timeout-min\") ?? undefined,\n onProgress: (line) => ctx.stderr(line),\n options,\n });\n const { markdown, ...summary } = report;\n ctx.stdout(JSON.stringify(summary, null, 2));\n if (summaryFile) fs.writeFileSync(summaryFile, JSON.stringify(summary, null, 2) + \"\\n\");\n const stepSummary = process.env.GITHUB_STEP_SUMMARY;\n if (stepSummary) {\n try {\n fs.appendFileSync(stepSummary, markdown + \"\\n\\n\");\n } catch {\n // nicety only\n }\n }\n return report.ok ? 0 : 1;\n }\n\n // The hub branch MIRRORS this checkout (the PR's code), so force.\n const pushed = await push(dir, { branch, force: true, message, options });\n ctx.stderr(`pushed ${pushed.slug}@${branch} (${pushed.contentHash.slice(0, 8)})`);\n const agent = await loadAgent(agentFile!);\n const world = await openWorld(`${pushed.slug}@${branch}`, options);\n const tasks = world.tasks.map((t) => t.name);\n if (!tasks.length) throw new CliError(`${pushed.slug} declares no tasks`, 1);\n const target: RunTarget = { slug: pushed.slug, ref: branch, versionId: pushed.versionId, dir };\n const summary = await runTasks({\n target,\n versionId: pushed.versionId,\n tasks,\n agent,\n agentName: agentFile!,\n surfaces: parseSurfaces(arg.str(args, \"surface\")),\n timeoutMs: timeoutMs(args),\n creds,\n ctx,\n });\n const out = { ...summary, branch, contentHash: pushed.contentHash };\n ctx.stdout(JSON.stringify(out, null, 2));\n if (summaryFile) fs.writeFileSync(summaryFile, JSON.stringify(out, null, 2) + \"\\n\");\n const rows: [string, string][] = [\n [\"avg reward\", summary.mean.toFixed(3)],\n [\"tasks\", String(summary.results.length)],\n [\"agent\", agentFile!],\n [\"version\", pushed.contentHash.slice(0, 8)],\n ];\n const passed = minScore === null || summary.mean >= minScore;\n if (minScore !== null) rows.push([\"gate\", `${passed ? \"PASS\" : \"FAIL\"} — bar ${minScore}`]);\n writeStepSummary(`World sim · ${pushed.slug}@${branch}`, rows);\n if (minScore !== null) {\n ctx.stderr(\n passed\n ? `gate: avg reward ${summary.mean.toFixed(3)} clears the ${minScore} bar.`\n : `gate: avg reward ${summary.mean.toFixed(3)} is below the ${minScore} bar.`,\n );\n }\n return passed ? 0 : 1;\n },\n });\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError, arg, type CommandGroup } from \"../router\";\nimport { resolveCredentials } from \"../config\";\nimport { openWorld } from \"../../worlds/index\";\nimport { openSession } from \"../../worlds/session\";\nimport { readLocalMeta } from \"../../worlds/hub\";\nimport {\n assertPortFree,\n localModule,\n localRuntime,\n localRuntimeReason,\n} from \"./local\";\n\n/**\n * `gateway worlds serve`: one session of the world on this machine through the\n * bundled runtime when a python3 is installed — its tools under `/__session/*`\n * and, when the tree has a connector.toml, the vendor routes beside them — or\n * a HOSTED api-surface session when none is: the same routes, from the\n * platform's container, no wait.\n */\n\nexport function registerServeCommand(worlds: CommandGroup): void {\n worlds.command({\n name: \"serve\",\n help: \"Serve one session of the world here (bundled runtime + python3): its tools over HTTP, the vendor routes when it has them, its ui on its own port when it declares one; or open a hosted api session when no Python is installed.\",\n notes:\n \"With a python3 >= 3.11 on this machine the CLI serves the world here from its bundled runtime\\n\" +\n \"(the same files the platform runs), on --port, in the foreground, as ONE session with state that\\n\" +\n \"lasts until you stop it or a client closes it. Every schema world gets the session verbs (loopback,\\n\" +\n \"no credential), the surface an outside agent acts on:\\n\" +\n \" GET /__session/task {task, prompt, tools, verifiers, worlds: {alias: [verifiers]}}\\n\" +\n \" GET /__session/tools the tools it serves (a dependency's as alias.tool)\\n\" +\n \" POST /__session/call {tool, args} -> {status, body}, as a hosted session answers\\n\" +\n \" GET /__session/state rows per entity (a dependency's under worlds.<alias>)\\n\" +\n \" POST /__session/grade {reward, rewards}: the root's verifiers by name, a dependency's as alias/name\\n\" +\n \" POST /__session/seed {entity: [rows]}; POST /__session/reset back to the start\\n\" +\n \" POST /__session/close end the session; this command returns\\n\" +\n \"--task <id> opens the session on one of the world's tasks: its prompt is in the banner and at\\n\" +\n \"/__session/task, its verifiers grade, and each dependency starts in the scenario its link's `task`\\n\" +\n \"names. `gateway worlds call <url> <tool> [--grade] [--close]` acts on the session from another shell.\\n\" +\n \"A world with a connector.toml serves its vendor routes beside them, and with `[ui]` its page on its own\\n\" +\n \"port (--ui-port, default the port after --port) at /, the layout the host serves it in, so a frontend\\n\" +\n \"built for the root works unchanged; the same page is at /__ui/ on --port. The page's api_path calls are\\n\" +\n \"answered with the pin; the bare routes still need it. `[dependencies]` entries with\\n\" +\n \"a `path` open beside the root. A --port another process holds is refused by name (its pid when lsof\\n\" +\n \"can see it): this serve never answers from another server. The runtime closes when the process that\\n\" +\n \"started it is gone, so a killed CLI leaves no server on the port. Without a python3 it does what `gateway worlds session open <slug>\\n\" +\n \"--task <scenario> --surface api --no-wait` does: the platform serves the world's vendor API for one\\n\" +\n \"session, and the session id + api url are printed. Close it with `gateway worlds session close <id>`.\\n\" +\n \"GATEWAY_RUNTIME=platform forces the hosted path.\",\n positionals: [\n {\n name: \"path\",\n help: \"World directory (pushed or pulled), or a platform slug[@ref].\",\n },\n ],\n flags: [\n {\n name: \"task\",\n help: \"Local: open the session on one of the world's tasks (its prompt, seed, verifiers).\",\n },\n {\n name: \"scenario\",\n help: \"Start in one of the world's scenarios (default: the world's first task).\",\n },\n {\n name: \"port\",\n help: \"Port for the local server (a hosted session picks its own address).\",\n default: \"8080\",\n },\n {\n name: \"ui-port\",\n help: \"Local: the ui's own port (default: the port after --port).\",\n },\n {\n name: \"api-key\",\n help: \"Pin the credential the local server accepts (a hosted session carries its own).\",\n },\n {\n name: \"host\",\n help: \"Platform host (default: GATEWAY_HOST or the saved login).\",\n env: \"GATEWAY_HOST\",\n },\n ],\n run: async (args, ctx) => {\n const target = args.positionals[0]!;\n // With a python3 on this machine the bundled runtime serves the world\n // here, exactly as the Python CLI did; the hosted session is the\n // fallback for a machine without one.\n const local = localRuntime();\n if (local && fs.existsSync(target) && fs.statSync(target).isDirectory()) {\n const port = arg.int(args, \"port\") ?? 8080;\n if (!Number.isInteger(port) || port < 0 || port > 65535)\n throw new CliError(\n `--port must be a port number (got ${String(args.flags.port)})`,\n );\n if (port !== 0) await assertPortFree(port);\n const argv = [\"serve\", path.resolve(target), \"--port\", String(port)];\n const apiKey = arg.str(args, \"api-key\");\n if (apiKey) argv.push(\"--api-key\", apiKey);\n const uiPort = arg.str(args, \"ui-port\");\n if (uiPort) argv.push(\"--ui-port\", uiPort);\n const scenario = arg.str(args, \"scenario\");\n if (scenario) argv.push(\"--scenario\", scenario);\n const task = arg.str(args, \"task\");\n if (task) argv.push(\"--task\", task);\n ctx.stderr(\n `# serving ${path.resolve(target)} on http://127.0.0.1:${port} (local runtime: ${local.python})`,\n );\n return localModule(argv, local);\n }\n const creds = resolveCredentials(arg.str(args, \"host\"));\n const options = {\n host: creds.host,\n publicKey: creds.publicKey,\n secretKey: creds.secretKey,\n };\n let slugRef = target;\n let versionId: string | undefined;\n if (fs.existsSync(target) && fs.statSync(target).isDirectory()) {\n const dir = path.resolve(target);\n const meta = readLocalMeta(dir);\n const slug = (meta?.slug as string | undefined) ?? path.basename(dir);\n slugRef = meta?.branch ? `${slug}@${meta.branch}` : slug;\n versionId = meta?.versionId;\n }\n ctx.stderr(\n \"`worlds serve` runs a local session with the Python runtime; opening a hosted api-surface session instead.\",\n );\n if (!local) ctx.stderr(`# ${localRuntimeReason()}`);\n let scenario = arg.str(args, \"scenario\") ?? arg.str(args, \"task\");\n if (!scenario) {\n const world = await openWorld(slugRef, options);\n scenario = world.tasks[0]?.name;\n if (!scenario)\n throw new CliError(\n `${slugRef} declares no tasks; pass --scenario`,\n 1,\n );\n ctx.stderr(\n `# no --scenario given; using the world's first task: ${scenario}`,\n );\n }\n const session = await openSession(slugRef, scenario, {\n ...(versionId ? { versionId } : {}),\n surfaces: [\"api\"],\n options,\n });\n const surfaces = await session.surfaces();\n ctx.stdout(\n JSON.stringify(\n {\n sessionId: session.sessionId,\n task: scenario,\n versionId: session.versionId,\n api: surfaces.api?.url ?? null,\n note: \"hosted session; `gateway worlds session status <id>` for readiness, `session close <id>` when done\",\n },\n null,\n 2,\n ),\n );\n },\n });\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError, arg, type CommandGroup } from \"../router\";\nimport { HOST_FLAG } from \"../platform/shared\";\nimport { credentialsForRuntime } from \"./local\";\nimport { api, resolveCredentials } from \"../config\";\nimport { runtime, worldPayload } from \"./client\";\n\n/** The report `run-tests` returns: what `<world>/tests/` asserted and how the world answered. */\nexport type WorldTestReport = {\n world?: string;\n scenario?: string | null;\n summary?: {\n total?: number;\n passed?: number;\n failed?: number;\n skipped?: number;\n status?: string;\n };\n cases?: {\n name: string;\n file: string;\n status: string;\n description?: string;\n group?: string;\n request?: { method?: string; path?: string; tool?: string; args?: Record<string, unknown> };\n actual?: { status?: number; body?: string };\n problems?: string[];\n }[];\n python?: {\n status: string;\n files?: string[];\n tests?: number;\n failures?: number;\n errors?: number;\n reason?: string | null;\n output?: string;\n };\n};\n\nexport function renderWorldTestReport(report: WorldTestReport): string[] {\n const lines: string[] = [];\n // Cases under their author's group headers (a route family, a workflow\n // step), each with its description when it has one.\n let group: string | null = null;\n for (const c of report.cases ?? []) {\n const own = c.group?.trim() || \"\";\n if (own !== (group ?? \"\") || group === null) {\n group = own;\n if (own) lines.push(`== ${own}`);\n }\n const mark = c.status === \"passed\" ? \" ok \" : \"FAIL\";\n const where = c.request?.tool\n ? `call ${c.request.tool}(${JSON.stringify(c.request.args ?? {})})`\n : c.request\n ? `${c.request.method ?? \"GET\"} ${c.request.path ?? \"/\"}`\n : \"\";\n lines.push(`${mark} ${c.name} ${where}`.trimEnd());\n if (c.description) lines.push(` ${c.description}`);\n for (const p of c.problems ?? []) lines.push(` ! ${p}`);\n }\n const py = report.python;\n if (py && py.status !== \"none\") {\n const detail =\n py.status === \"skipped\"\n ? (py.reason ?? \"skipped\")\n : `${py.tests ?? 0} tests, ${py.failures ?? 0} failures, ${py.errors ?? 0} errors`;\n lines.push(\n `${py.status === \"passed\" ? \" ok \" : py.status === \"skipped\" ? \"skip\" : \"FAIL\"} python tests (${(py.files ?? []).join(\", \")}) ${detail}`,\n );\n if (py.status === \"failed\" && py.output)\n lines.push(\n ...py.output\n .trimEnd()\n .split(\"\\n\")\n .slice(-30)\n .map((l) => ` ${l}`),\n );\n }\n return lines;\n}\n\n/**\n * `gateway worlds test <path>` — run the tests a world ships for itself\n * (`tests/*.json` tool and HTTP cases, `tests/test_*.py`) against the world at\n * that path, opened as one session in the schema runtime. Tests are not evals:\n * an eval grades an agent on a task; a test asserts the world answers as its\n * author says it must, and runs on every push when the manifest asks for it.\n */\nexport function registerTestCommand(worlds: CommandGroup): void {\n worlds.command({\n name: \"test\",\n help: \"Run the tests a world ships for itself (tests/*.json tool + HTTP cases, tests/test_*.py) against one session of it.\",\n positionals: [\n {\n name: \"path\",\n help: \"World directory (a schema world, or its api bundle), or a platform slug[@versionId] to run the suite on the platform.\",\n },\n ],\n flags: [\n {\n name: \"scenario\",\n help: \"Start the world in one of its scenarios before testing (default: the base state).\",\n },\n { name: \"out\", help: \"Write the full report as JSON here\" },\n {\n name: \"json\",\n help: \"Print the report as JSON instead of lines.\",\n boolean: true,\n },\n HOST_FLAG,\n ],\n notes:\n \"A world's tests live in <world>/tests/ and run in order against ONE session of the world, so a case sees\\n\" +\n \"what the cases before it wrote. *.json files hold cases of two shapes:\\n\" +\n ' {name, tool: \"send_message\", args: {...}, expect} a tool call (root tools by name, a dependency\\'s as alias.tool);\\n' +\n \" {name, request: {method, path, query?, headers?, body?, auth?}, expect} an HTTP call on the vendor routes (connector.toml).\\n\" +\n \"expect is {status?, json?, length?, contains?, headers?}; a refused call (unknown tool, arguments off the\\n\" +\n \"schema) answers 400 with {error, detail}; a handler that raises answers 500 with {error: its message}.\\n\" +\n \"tests/test_*.py run under pytest with WORLD_DIR, WORLD_URL and\\n\" +\n \"WORLD_API_KEY set (a Python without pytest FAILS the suite, it never skips it). No tests/ directory passes as\\n\" +\n 'zero cases. With `[actions] on_push = [\"tests\"]` in gateway-env.toml the platform runs the same suite on\\n' +\n \"every push; `gateway bench tests <slug>` reads those runs. Exit 1 when any test fails.\",\n run: async (args, ctx) => {\n const target = args.positionals[0] ?? \".\";\n const dir = path.resolve(target);\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {\n // Not a directory here: a world on the platform. The platform runs the\n // suite the pushed version ships and answers with the run.\n if (/[\\/\\\\]/.test(target) || target.startsWith(\".\"))\n throw new CliError(`Not a directory: ${dir}`, 1);\n const creds = resolveCredentials(arg.str(args, \"host\"));\n const [slug, ref] = target.split(\"@\");\n const scenario = arg.str(args, \"scenario\");\n type Run = {\n id: string;\n state: string;\n versionId: string;\n summary?: WorldTestReport[\"summary\"];\n error?: string | null;\n report?: WorldTestReport | null;\n };\n // Start the run and read it back by id rather than holding one request\n // open for the whole suite: a dropped response then costs a retry of a\n // GET, not the run (one prod call sat 25 minutes on a run that had\n // finished in seconds).\n const body = {\n ...(ref ? { versionId: ref } : {}),\n ...(scenario ? { scenario } : {}),\n };\n const url = `/api/public/worlds/${encodeURIComponent(slug!)}/tests`;\n let run: Run;\n try {\n run = (\n await api<{ run: Run }>(creds, \"POST\", url, {\n ...body,\n wait: false,\n })\n ).run;\n } catch (error) {\n // a platform from before `wait` rejects the unknown key: hold the request instead\n if (!/wait|unrecognized|400/i.test(String(error))) throw error;\n run = (\n await api<{ run: Run }>(creds, \"POST\", url, body, {\n timeoutMs: 15 * 60_000,\n })\n ).run;\n }\n const deadline = Date.now() + 15 * 60_000;\n let misses = 0;\n while (run.state === \"queued\" || run.state === \"running\") {\n if (Date.now() > deadline)\n throw new CliError(\n `Test run ${run.id} still ${run.state} after 15 minutes`,\n 1,\n );\n await new Promise((resolve) => setTimeout(resolve, 2_000));\n try {\n run = (\n await api<{ run: Run }>(\n creds,\n \"GET\",\n `/api/public/worlds/${encodeURIComponent(slug!)}/tests/${run.id}`,\n )\n ).run;\n misses = 0;\n } catch (error) {\n // a transient read failure is not the run failing; give it a few tries\n if (++misses >= 5) throw error;\n }\n }\n const report = run.report ?? {};\n if (arg.bool(args, \"json\"))\n ctx.stdout(\n JSON.stringify(\n {\n runId: run.id,\n state: run.state,\n versionId: run.versionId,\n ...report,\n },\n null,\n 1,\n ),\n );\n else {\n for (const line of renderWorldTestReport(report)) ctx.stdout(line);\n const s = run.summary ?? report.summary ?? {};\n ctx.stdout(\n `${run.state}: ${s.passed ?? 0} passed, ${s.failed ?? 0} failed, ${s.skipped ?? 0} skipped (run ${run.id} on ${run.versionId})`,\n );\n if (run.error) ctx.stdout(`error: ${run.error}`);\n }\n const out = arg.str(args, \"out\");\n if (out)\n fs.writeFileSync(\n out,\n JSON.stringify(\n {\n runId: run.id,\n state: run.state,\n versionId: run.versionId,\n ...report,\n },\n null,\n 1,\n ) + \"\\n\",\n );\n return run.state === \"passed\" ? 0 : 1;\n }\n const creds = credentialsForRuntime(arg.str(args, \"host\"));\n const scenario = arg.str(args, \"scenario\");\n const res = await runtime<{ report?: WorldTestReport }>(creds, {\n command: \"run-tests\",\n ...worldPayload(dir),\n ...(scenario ? { scenario } : {}),\n });\n const report = res.report ?? {};\n if (arg.bool(args, \"json\")) ctx.stdout(JSON.stringify(report, null, 1));\n else {\n for (const line of renderWorldTestReport(report)) ctx.stdout(line);\n const s = report.summary ?? {};\n if (!(s.total ?? 0) && !(report.python?.files?.length ?? 0)) {\n const tests = path.join(dir, \"tests\");\n const state = fs.existsSync(tests) ? \"holds none\" : \"does not exist\";\n ctx.stdout(`no cases: ${tests} ${state} (see \\`gateway worlds test --help\\` for the shapes)`);\n }\n ctx.stdout(\n `${s.status ?? \"?\"}: ${s.passed ?? 0} passed, ${s.failed ?? 0} failed, ${s.skipped ?? 0} skipped`,\n );\n }\n const out = arg.str(args, \"out\");\n if (out) {\n fs.writeFileSync(out, JSON.stringify(report, null, 1) + \"\\n\");\n ctx.stdout(`report: ${out}`);\n }\n return report.summary?.status === \"passed\" ? 0 : 1;\n },\n });\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError, arg, type CommandGroup } from \"../router\";\nimport { localBridge, localRuntime, localRuntimeReason } from \"./local\";\nimport { BridgeRejected, detailFrom } from \"./client\";\n\n/**\n * `gateway worlds call <path> <tool>`: one tool call on a world directory,\n * the way a hosted session would make it — the world (and every\n * `[dependencies]` entry with a `path`) opened as one session in the bundled\n * runtime, the tool run, the `{status, body}` printed. Root tools go by name,\n * a dependency's as `alias.tool`. This runs a world's own Python, so it runs\n * on this machine only: the platform's bridge refuses `call`.\n *\n * Given a URL instead of a directory — the `url` `gateway worlds serve` printed\n * — the call goes to that running session over its `/__session/*` verbs, the\n * way an outside agent acts on it, and `--close` ends the session afterwards.\n */\n\n/** The answer the runtime's `call` returns. */\nexport type CallReport = {\n status: string;\n tools: string[];\n result: { status: number; body: unknown };\n seed?: Record<string, unknown>;\n state?: Record<string, unknown>;\n grade?: Record<string, unknown>;\n};\n\n/** `--args`: inline JSON, `@file` for a JSON file, `-` for stdin. Must be an object. */\nexport function parseArgs(raw: string | undefined, stdin: string): Record<string, unknown> {\n if (raw === undefined) return {};\n let text = raw;\n if (raw === \"-\") text = stdin;\n else if (raw.startsWith(\"@\")) {\n const file = raw.slice(1);\n if (!fs.existsSync(file)) throw new CliError(`--args ${raw}: ${file} does not exist`);\n text = fs.readFileSync(file, \"utf8\");\n }\n let value: unknown;\n try {\n value = JSON.parse(text);\n } catch (error) {\n throw new CliError(`--args is not JSON: ${(error as Error).message}`);\n }\n if (!value || typeof value !== \"object\" || Array.isArray(value))\n throw new CliError(\"--args must be a JSON object of the tool's arguments, e.g. '{\\\"channel\\\": \\\"C1\\\"}'\");\n return value as Record<string, unknown>;\n}\n\nconst SERVED_URL = /^https?:\\/\\//;\n\nasync function sessionVerb(base: string, verb: string, body?: unknown): Promise<{ status: number; body: unknown }> {\n let response: Response;\n try {\n response = await fetch(`${base}/__session/${verb}`, {\n method: body === undefined ? \"GET\" : \"POST\",\n headers: { \"content-type\": \"application/json\" },\n ...(body === undefined ? {} : { body: JSON.stringify(body) }),\n });\n } catch (error) {\n throw new CliError(`no session answers at ${base}: ${(error as Error).message}. Is \\`gateway worlds serve\\` running?`, 1);\n }\n const text = await response.text();\n let parsed: unknown = text;\n try {\n parsed = JSON.parse(text);\n } catch {\n // A non-JSON body (a proxy page, an empty answer) is kept as text.\n }\n return { status: response.status, body: parsed };\n}\n\n/** `worlds call <url> <tool>`: act on the served session as an outside agent would. */\nexport async function callServed(\n base: string,\n tool: string,\n args: Record<string, unknown>,\n wants: { seed?: Record<string, unknown>; state: boolean; grade: boolean; close: boolean },\n): Promise<CallReport & { closed?: boolean }> {\n const url = base.replace(/\\/+$/, \"\");\n const tools = await sessionVerb(url, \"tools\");\n if (tools.status !== 200 || !tools.body || typeof tools.body !== \"object\" || !(\"tools\" in tools.body))\n throw new CliError(`${url} is not a served world session: GET /__session/tools answered ${tools.status}`, 1);\n const report: CallReport & { closed?: boolean } = {\n status: \"ok\",\n tools: (tools.body as { tools: string[] }).tools,\n result: { status: 0, body: null },\n };\n if (wants.seed) {\n const seeded = await sessionVerb(url, \"seed\", wants.seed);\n if (seeded.status !== 200)\n throw new CliError(`POST /__session/seed answered ${seeded.status}: ${JSON.stringify(seeded.body)}`, 1);\n report.seed = seeded.body as Record<string, unknown>;\n }\n const answer = await sessionVerb(url, \"call\", { tool, args });\n report.result =\n answer.status === 200 && answer.body && typeof answer.body === \"object\" && \"status\" in answer.body\n ? (answer.body as { status: number; body: unknown })\n : { status: answer.status, body: answer.body };\n if (wants.state) report.state = (await sessionVerb(url, \"state\")).body as Record<string, unknown>;\n if (wants.grade) report.grade = (await sessionVerb(url, \"grade\", {})).body as Record<string, unknown>;\n if (wants.close) {\n const closed = await sessionVerb(url, \"close\", {});\n if (closed.status !== 200) throw new CliError(`POST /__session/close answered ${closed.status}`, 1);\n report.closed = true;\n }\n return report;\n}\n\nexport function registerCallCommand(worlds: CommandGroup): void {\n worlds.command({\n name: \"call\",\n help: \"Call one tool on a world directory here, or on a served session by URL; a dependency's tool as alias.tool.\",\n positionals: [\n {\n name: \"path\",\n help: \"World directory (a schema world with gateway-env.toml), or the url of a running `worlds serve` session.\",\n },\n { name: \"tool\", help: \"Tool name; a dependency's tool as <alias>.<tool>.\" },\n ],\n flags: [\n { name: \"args\", help: \"The tool's arguments as JSON, @file for a file, - for stdin (default {}).\" },\n { name: \"task\", help: \"Open the session under one of the world's tasks (its tool allow-list, its verifiers).\" },\n { name: \"scenario\", help: \"Start in one of the world's scenarios (default: the base state).\" },\n {\n name: \"seed\",\n help: \"Seed rows before the call, the host's shape: JSON {rows: {entity: [row, ...]}, mode?: append|replace}, @file, or -.\",\n },\n { name: \"state\", help: \"Print the world's state after the call.\", boolean: true },\n { name: \"grade\", help: \"Run the verifiers after the call and print the scores.\", boolean: true },\n { name: \"close\", help: \"On a served session (url): end it after the call; `worlds serve` returns.\", boolean: true },\n ],\n notes:\n \"The world is opened in place, so `[dependencies]` entries with a `path` open beside it and their tools\\n\" +\n \"answer as alias.tool; a pin without a path is refused here (add path = \\\"../<dir>\\\"). The world's handlers\\n\" +\n \"run on this machine through the bundled runtime (a python3 >= 3.11); the platform never runs them for you.\\n\" +\n \"Exit 0 when the tool answered 2xx, 1 otherwise: a refused call (unknown tool, arguments off the schema, a\\n\" +\n \"tool outside --task's allow-list) prints the refusal; a 500 is the handler raising, its error in the body.\\n\" +\n \"With a url (the `url` `gateway worlds serve <dir> --task <id>` prints) the call goes to THAT session over\\n\" +\n \"POST /__session/call, so state carries from call to call, --state/--grade read it, and --close ends it;\\n\" +\n \"--task and --scenario belong to the serve. This is the outside-agent path: any HTTP client does the same.\\n\" +\n \"Examples:\\n\" +\n \" gateway worlds call ./whatsapp list_conversations\\n\" +\n \" gateway worlds call ./whatsapp send_message --args '{\\\"conversation_id\\\": \\\"c1\\\", \\\"body\\\": \\\"hi\\\"}' --state\\n\" +\n \" gateway worlds call ./whatsapp slack.post_message --args @msg.json --task escalate --grade\\n\" +\n \" gateway worlds call http://127.0.0.1:8080 send_message --args '{\\\"conversation_id\\\": \\\"c1\\\", \\\"body\\\": \\\"hi\\\"}'\\n\" +\n \" gateway worlds call http://127.0.0.1:8080 slack.post_message --args @msg.json --grade --close\",\n run: async (args, ctx) => {\n const [target, tool] = args.positionals as [string, string];\n if (SERVED_URL.test(target)) {\n for (const flag of [\"task\", \"scenario\"] as const)\n if (arg.str(args, flag) !== undefined)\n throw new CliError(`--${flag} belongs to \\`gateway worlds serve\\`; the session at ${target} already has its own`);\n const stdin = args.flags.args === \"-\" || args.flags.seed === \"-\" ? await ctx.stdin() : \"\";\n const seedRaw = arg.str(args, \"seed\");\n const report = await callServed(target, tool, parseArgs(arg.str(args, \"args\"), stdin), {\n ...(seedRaw === undefined ? {} : { seed: parseArgs(seedRaw, stdin) }),\n state: arg.bool(args, \"state\"),\n grade: arg.bool(args, \"grade\"),\n close: arg.bool(args, \"close\"),\n });\n ctx.stdout(JSON.stringify(report, null, 2));\n return report.result.status >= 200 && report.result.status < 300 ? 0 : 1;\n }\n if (arg.bool(args, \"close\")) throw new CliError(\"--close ends a served session; pass its url instead of a directory\");\n const dir = path.resolve(target);\n if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new CliError(`Not a directory: ${dir}`, 1);\n const local = localRuntime();\n if (!local)\n throw new CliError(\n \"`worlds call` runs the world's own Python, so it needs the bundled runtime on this machine. \" +\n localRuntimeReason(),\n 1,\n );\n const stdin = args.flags.args === \"-\" || args.flags.seed === \"-\" ? await ctx.stdin() : \"\";\n const seedRaw = arg.str(args, \"seed\");\n const seed = seedRaw === undefined ? undefined : parseArgs(seedRaw, stdin);\n const task = arg.str(args, \"task\");\n const scenario = arg.str(args, \"scenario\");\n const payload = await localBridge<Record<string, unknown>>(\n {\n command: \"call\",\n world: dir,\n tool,\n args: parseArgs(arg.str(args, \"args\"), stdin),\n ...(task ? { task } : {}),\n ...(scenario ? { scenario } : {}),\n ...(seed ? { seed } : {}),\n ...(arg.bool(args, \"state\") ? { state: true } : {}),\n ...(arg.bool(args, \"grade\") ? { grade: true } : {}),\n },\n local,\n );\n const detail = detailFrom(payload);\n if (detail) throw new BridgeRejected(detail);\n const report = payload as CallReport;\n ctx.stdout(JSON.stringify(report, null, 2));\n return report.result.status >= 200 && report.result.status < 300 ? 0 : 1;\n },\n });\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"node:path\";\n\nimport { CliError, arg, type CommandGroup } from \"../router\";\n\n/**\n * `gateway worlds schema entity add` and `gateway worlds connector route add`:\n * local scaffolds that append one declaration to a hand-authored file so the\n * shape is right without the author remembering it. Neither talks to the\n * platform; `worlds schema check` / `worlds connector validate` still judge\n * the result.\n */\n\nconst ENTITY_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;\nconst PROPERTY_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;\nconst HTTP_METHODS = new Set([\"GET\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\nconst API_ACTIONS = new Set([\"read\", \"create\", \"update\", \"delete\", \"handler\"]);\nconst FIELD_TYPES = new Set([\"string\", \"integer\", \"number\", \"boolean\"]);\n\ntype JsonObject = Record<string, unknown>;\n\nconst isObject = (value: unknown): value is JsonObject =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport type Relationship = { fields: string[]; target: string; on_delete: \"restrict\" };\n\nexport type EntityDeclaration = {\n schema: JsonObject;\n primary_key: string[];\n unique?: string[][];\n relationships?: Relationship[];\n};\n\nexport type EntitySpec = {\n name: string;\n /** `--ref Name` → `{\"$ref\": \"#/$defs/Name\"}`. */\n ref?: string;\n /** Inline JSON Schema for the payload (mutually exclusive with `ref`). */\n schema?: JsonObject;\n /** `--fields id:string,name:string?`: an object def written under `$defs` and referenced. */\n fields?: string;\n primaryKey: string[];\n unique: string[][];\n relationships: Relationship[];\n};\n\nexport function parseFields(spec: string): JsonObject {\n const properties: JsonObject = {};\n const required: string[] = [];\n for (const raw of spec.split(\",\")) {\n const item = raw.trim();\n if (!item) continue;\n const colon = item.indexOf(\":\");\n if (colon === -1)\n throw new CliError(`--fields entries look like name:type[?], got ${JSON.stringify(item)}`);\n const name = item.slice(0, colon).trim();\n let type = item.slice(colon + 1).trim();\n const optional = type.endsWith(\"?\");\n if (optional) type = type.slice(0, -1);\n if (!PROPERTY_NAME.test(name)) throw new CliError(`Invalid property name ${JSON.stringify(name)}`);\n if (!FIELD_TYPES.has(type))\n throw new CliError(\n `Unknown field type ${JSON.stringify(type)} for ${name}; use ${[...FIELD_TYPES].join(\", \")}`,\n );\n if (name in properties) throw new CliError(`Duplicate field ${name}`);\n properties[name] = { type };\n if (!optional) required.push(name);\n }\n if (!Object.keys(properties).length) throw new CliError(\"--fields declares no properties\");\n return { type: \"object\", properties, required, additionalProperties: false };\n}\n\n/** `account_id->crm_accounts`, `workspace_id,user_id->slack_users`. */\nexport function parseRelationship(spec: string): Relationship {\n const arrow = spec.indexOf(\"->\");\n if (arrow === -1)\n throw new CliError(`--relationship looks like field[,field]->target_entity, got ${JSON.stringify(spec)}`);\n const fields = spec\n .slice(0, arrow)\n .split(\",\")\n .map((f) => f.trim())\n .filter(Boolean);\n const target = spec.slice(arrow + 2).trim();\n if (!fields.length || !target)\n throw new CliError(`--relationship looks like field[,field]->target_entity, got ${JSON.stringify(spec)}`);\n return { fields, target, on_delete: \"restrict\" };\n}\n\nfunction defName(entity: string): string {\n return entity\n .split(\"_\")\n .filter(Boolean)\n .map((part) => part[0]!.toUpperCase() + part.slice(1))\n .join(\"\");\n}\n\nfunction resolveObjectSchema(root: JsonObject, schema: JsonObject): JsonObject | undefined {\n const ref = schema.$ref;\n if (typeof ref === \"string\") {\n if (!ref.startsWith(\"#/$defs/\")) return undefined;\n const defs = root.$defs;\n const target = isObject(defs) ? defs[ref.slice(\"#/$defs/\".length)] : undefined;\n return isObject(target) ? target : undefined;\n }\n return schema;\n}\n\n/**\n * Pure: returns the document with the entity declared (and a `$defs` entry when\n * `--fields` built one). Throws a CliError naming exactly what is wrong.\n */\nexport function addEntity(root: JsonObject, spec: EntitySpec): { document: JsonObject; declaration: EntityDeclaration; def?: string } {\n if (!ENTITY_NAME.test(spec.name))\n throw new CliError(`Entity names match [A-Za-z][A-Za-z0-9_]*, got ${JSON.stringify(spec.name)}`);\n const gateway = root[\"x-gateway\"];\n if (!isObject(gateway) || !isObject(gateway.entities))\n throw new CliError(\"schema/world.json is not a gateway-world/1 root: it has no x-gateway.entities\");\n const entities = gateway.entities;\n const collision = Object.keys(entities).find((k) => k.toLowerCase() === spec.name.toLowerCase());\n if (collision) throw new CliError(`Entity ${collision} is already declared`);\n\n const chosen = [spec.ref, spec.schema, spec.fields].filter((v) => v !== undefined).length;\n if (chosen !== 1) throw new CliError(\"Give exactly one of --ref, --schema or --fields\");\n\n const defs: JsonObject = isObject(root.$defs) ? { ...root.$defs } : {};\n let schema: JsonObject;\n let def: string | undefined;\n if (spec.ref !== undefined) {\n if (!(spec.ref in defs))\n throw new CliError(\n `$defs has no ${spec.ref}; declare it first or use --fields to write one (have: ${Object.keys(defs).join(\", \") || \"none\"})`,\n );\n schema = { $ref: `#/$defs/${spec.ref}` };\n } else if (spec.fields !== undefined) {\n def = defName(spec.name);\n if (def in defs) throw new CliError(`$defs already has ${def}; use --ref ${def} to reuse it`);\n defs[def] = parseFields(spec.fields);\n schema = { $ref: `#/$defs/${def}` };\n } else {\n schema = spec.schema!;\n }\n\n if (!spec.primaryKey.length) throw new CliError(\"--key is required (repeat it for a composite key)\");\n if (new Set(spec.primaryKey).size !== spec.primaryKey.length)\n throw new CliError(\"--key fields must be distinct\");\n const payload = resolveObjectSchema({ ...root, $defs: defs }, schema);\n if (payload) {\n if (payload.type !== \"object\" || payload.additionalProperties !== false)\n throw new CliError(\"An entity payload must be a closed object: type \\\"object\\\" with additionalProperties false\");\n const properties = isObject(payload.properties) ? payload.properties : {};\n const required = Array.isArray(payload.required) ? payload.required : [];\n for (const key of spec.primaryKey) {\n const prop = properties[key];\n if (!isObject(prop)) throw new CliError(`Primary key field ${key} is not a property of the payload`);\n if (prop.type !== \"string\" && prop.type !== \"integer\")\n throw new CliError(`Primary key field ${key} must be a string or integer property`);\n if (!required.includes(key)) throw new CliError(`Primary key field ${key} must be required`);\n }\n for (const rel of spec.relationships)\n for (const field of rel.fields)\n if (!(field in properties) && !field.startsWith(\"/\"))\n throw new CliError(`Relationship field ${field} is not a property of the payload`);\n }\n\n for (const rel of spec.relationships) {\n const target = entities[rel.target];\n if (!isObject(target)) {\n if (rel.target === spec.name) continue;\n throw new CliError(`Relationship target ${rel.target} is not a declared entity`);\n }\n const targetKey = Array.isArray(target.primary_key) ? target.primary_key : [];\n if (targetKey.length !== rel.fields.length)\n throw new CliError(\n `Relationship to ${rel.target} needs ${targetKey.length} field(s) to match its primary key [${targetKey.join(\", \")}]`,\n );\n }\n\n const declaration: EntityDeclaration = { schema, primary_key: spec.primaryKey };\n if (spec.unique.length) declaration.unique = spec.unique;\n if (spec.relationships.length) declaration.relationships = spec.relationships;\n\n const document: JsonObject = { ...root };\n if (def !== undefined || root.$defs !== undefined) document.$defs = defs;\n document[\"x-gateway\"] = { ...gateway, entities: { ...entities, [spec.name]: declaration } };\n return { document, declaration, def };\n}\n\n// ── connector routes ────────────────────────────────────────────────────────\n\nexport type RouteSpec = {\n name: string;\n method: string;\n path: string;\n params: string[];\n entity?: string;\n results?: string;\n api: {\n action?: string;\n status?: number;\n /** The served answer's own envelope key (`{\"data\": [...]}`); `\"\"` for a bare array. */\n envelope?: string;\n single?: boolean;\n filter: Record<string, string>;\n body: Record<string, string>;\n handler?: string;\n };\n};\n\nconst tomlString = (value: string) => JSON.stringify(value);\n\nconst tomlInlineTable = (pairs: Record<string, string>) =>\n `{ ${Object.entries(pairs)\n .map(([k, v]) => `${PROPERTY_NAME.test(k) ? k : tomlString(k)} = ${tomlString(v)}`)\n .join(\", \")} }`;\n\n/** The `[[operations]]` block (and `[operations.api]` when any api key is set). */\nexport function renderRoute(spec: RouteSpec): string {\n const lines = [\"[[operations]]\", `name = ${tomlString(spec.name)}`, `method = ${tomlString(spec.method)}`, `path = ${tomlString(spec.path)}`];\n if (spec.params.length) lines.push(`params = [${spec.params.map(tomlString).join(\", \")}]`);\n if (spec.entity !== undefined) lines.push(`entity = ${tomlString(spec.entity)}`);\n if (spec.results !== undefined) lines.push(`results = ${tomlString(spec.results)}`);\n const api: string[] = [];\n if (spec.api.action !== undefined) api.push(`action = ${tomlString(spec.api.action)}`);\n if (spec.api.status !== undefined) api.push(`status = ${spec.api.status}`);\n if (spec.api.envelope !== undefined) api.push(`envelope = ${tomlString(spec.api.envelope)}`);\n if (spec.api.single) api.push(\"single = true\");\n if (Object.keys(spec.api.filter).length) api.push(`filter = ${tomlInlineTable(spec.api.filter)}`);\n if (Object.keys(spec.api.body).length) api.push(`body = ${tomlInlineTable(spec.api.body)}`);\n if (spec.api.handler !== undefined) api.push(`handler = ${tomlString(spec.api.handler)}`);\n if (api.length) lines.push(\"\", \"[operations.api]\", ...api);\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nexport function declaredOperationNames(toml: string): string[] {\n const names: string[] = [];\n let inOperation = false;\n for (const raw of toml.split(\"\\n\")) {\n const line = raw.trim();\n if (line.startsWith(\"[\")) inOperation = line === \"[[operations]]\";\n else if (inOperation) {\n const m = /^name\\s*=\\s*\"([^\"]*)\"/.exec(line);\n if (m) names.push(m[1]!);\n }\n }\n return names;\n}\n\n/** Pure: the connector.toml text without the `[[operations]]` block named\n * `name` — its own keys and its `[operations.api]` sub-table, up to the next\n * block or table header — every other byte kept. Null when no block has it. */\nexport function removeRoute(toml: string, name: string): string | null {\n const lines = toml.split(\"\\n\");\n const kept: string[] = [];\n let inOperation = false;\n let dropping = false;\n let found = false;\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!.trim();\n if (line === \"[[operations]]\") {\n // Look ahead: is this the block being removed?\n let named = false;\n for (let j = i + 1; j < lines.length; j++) {\n const next = lines[j]!.trim();\n if (next.startsWith(\"[\")) break;\n const m = /^name\\s*=\\s*\"([^\"]*)\"/.exec(next);\n if (m) {\n named = m[1] === name;\n break;\n }\n }\n inOperation = true;\n dropping = named;\n found ||= named;\n if (!dropping) kept.push(lines[i]!);\n continue;\n }\n if (line.startsWith(\"[\")) {\n // `[operations.api]` belongs to the block above it; any other header ends it.\n const subtable = /^\\[operations\\.[^\\]]+\\]$/.test(line) && inOperation;\n if (!subtable) {\n inOperation = false;\n dropping = false;\n }\n if (!dropping) kept.push(lines[i]!);\n continue;\n }\n if (!dropping) kept.push(lines[i]!);\n }\n if (!found) return null;\n // The removed block took its own blank separator with it; leave one newline at the end.\n return kept.join(\"\\n\").replace(/\\n{3,}/g, \"\\n\\n\").replace(/\\n+$/, \"\\n\");\n}\n\n/** Pure: the connector.toml text with one more `[[operations]]` appended; with\n * `replace`, the existing block of that name is removed first, so a route can\n * be corrected without hand-editing (WhatsApp dogfood: the second `route add`\n * was refused as a duplicate and the envelope had to be typed in by hand). */\nexport function addRoute(\n toml: string,\n spec: RouteSpec,\n declaredEntities?: string[],\n options: { replace?: boolean } = {},\n): string {\n if (!/^\\s*\\[connector\\]\\s*$/m.test(toml))\n throw new CliError(\"connector.toml has no [connector] table; it is not a connector spec\");\n if (!PROPERTY_NAME.test(spec.name))\n throw new CliError(`Operation names match [A-Za-z_][A-Za-z0-9_]*, got ${JSON.stringify(spec.name)}`);\n const declared = declaredOperationNames(toml).includes(spec.name);\n if (declared && !options.replace)\n throw new CliError(`Operation ${spec.name} is already declared; pass --replace to rewrite it`);\n if (!declared && options.replace)\n throw new CliError(`--replace: no operation ${spec.name} is declared (have: ${declaredOperationNames(toml).join(\", \") || \"none\"})`);\n if (!HTTP_METHODS.has(spec.method))\n throw new CliError(`--method must be one of ${[...HTTP_METHODS].join(\", \")}, got ${spec.method}`);\n if (!spec.path.startsWith(\"/\")) throw new CliError(`--path must start with /, got ${spec.path}`);\n if (spec.path.includes(\"?\")) throw new CliError(\"--path carries no query string; declare query parameters with --param\");\n if (spec.api.action !== undefined && !API_ACTIONS.has(spec.api.action))\n throw new CliError(`--action must be one of ${[...API_ACTIONS].join(\", \")}, got ${spec.api.action}`);\n if (spec.api.action === \"handler\" && spec.api.handler === undefined)\n throw new CliError(\"--action handler needs --handler <function> from api/handlers.py\");\n if (spec.api.handler !== undefined && spec.api.action !== \"handler\")\n throw new CliError(\"--handler only applies with --action handler\");\n if (spec.api.status !== undefined && (spec.api.status < 200 || spec.api.status > 299))\n throw new CliError(\"--status must be a 2xx\");\n if (spec.entity !== undefined && declaredEntities && !declaredEntities.includes(spec.entity))\n throw new CliError(\n `Entity ${spec.entity} is not declared in schema/world.json (have: ${declaredEntities.join(\", \") || \"none\"}); run \\`gateway worlds schema entity add\\` first`,\n );\n if (spec.entity === undefined && (spec.results !== undefined || spec.api.action !== undefined && spec.api.action !== \"handler\"))\n throw new CliError(\"--results and store actions need --entity: an operation without an entity never seeds\");\n const pathArgs = [...spec.path.matchAll(/\\{([^}]+)\\}/g)].map((m) => m[1]!);\n for (const [key] of Object.entries(spec.api.filter))\n if (!pathArgs.includes(key) && !spec.params.includes(key))\n throw new CliError(`--filter ${key} is neither a {${key}} path argument nor a declared --param`);\n if (spec.api.envelope !== undefined && spec.api.single)\n throw new CliError(\"--envelope wraps a list; --single answers the row itself — pass one of them\");\n\n const text = options.replace ? (removeRoute(toml, spec.name) ?? toml) : toml;\n const body = text.endsWith(\"\\n\") ? text : text + \"\\n\";\n return body + \"\\n\" + renderRoute(spec);\n}\n\n// ── gateway-env.toml: [dependencies.<alias>] and [[tasks]] ──────────────────\n\nconst ALIAS = /^[a-z][a-z0-9_]{0,31}$/;\nconst PIN = /^(?:[a-z0-9][a-z0-9_-]*\\/)?[a-z0-9][a-z0-9._-]*@[a-z0-9][a-z0-9._-]*$/i;\nconst TRANSFORMS = new Set([\n \"lower\", \"upper\", \"trim\", \"collapse_ws\", \"nfkc\", \"digits\", \"email_local_part\", \"email_domain\", \"sha1\", \"sha256\",\n]);\nconst isTransform = (name: string) => TRANSFORMS.has(name) || (name.startsWith(\"strip_prefix:\") && name.length > \"strip_prefix:\".length);\n\nexport type EntityMap = { local: string; dep: string; transform: string[] };\n\nexport type DependencySpec = {\n alias: string;\n pin: string;\n /** Relative directory from the world to the dependency's tree. */\n path: string;\n task?: string;\n tools: string[];\n entities: EntityMap[];\n};\n\nexport type TaskSpec = {\n id: string;\n prompt: string;\n verifiers: string[];\n /** alias → dependency verifiers graded on that world's own state. */\n worlds: Record<string, string[]>;\n};\n\nconst tomlArray = (values: string[]) => `[${values.map(tomlString).join(\", \")}]`;\n\n/** `--map wa_contacts.phone=slack_users.phone:digits,trim`. */\nexport function parseEntityMap(spec: string): EntityMap {\n const eq = spec.indexOf(\"=\");\n if (eq === -1) throw new CliError(`--map looks like local_entity.field=dep_entity.field[:transform,...], got ${JSON.stringify(spec)}`);\n const local = spec.slice(0, eq).trim();\n let dep = spec.slice(eq + 1).trim();\n let transform: string[] = [];\n const colon = dep.indexOf(\":\");\n if (colon !== -1) {\n transform = dep.slice(colon + 1).split(\",\").map((t) => t.trim()).filter(Boolean);\n dep = dep.slice(0, colon).trim();\n }\n for (const ref of [local, dep])\n if (!/^[A-Za-z_][A-Za-z0-9_]*\\.[A-Za-z_][A-Za-z0-9_]*$/.test(ref))\n throw new CliError(`--map sides are entity.field, got ${JSON.stringify(ref)}`);\n const unknown = transform.find((t) => !isTransform(t));\n if (unknown !== undefined)\n throw new CliError(`--map transform ${JSON.stringify(unknown)} is not one of ${[...TRANSFORMS].sort().join(\", \")}, strip_prefix:<p>`);\n return { local, dep, transform };\n}\n\nexport function renderDependency(spec: DependencySpec): string {\n const lines = [`[dependencies.${spec.alias}]`, `pin = ${tomlString(spec.pin)}`, `path = ${tomlString(spec.path)}`];\n if (spec.task !== undefined) lines.push(`task = ${tomlString(spec.task)}`);\n if (spec.tools.length) lines.push(`tools = ${tomlArray(spec.tools)}`);\n if (spec.entities.length) {\n lines.push(\"\", `[dependencies.${spec.alias}.entities]`);\n for (const m of spec.entities)\n lines.push(\n m.transform.length\n ? `${tomlString(m.local)} = { to = ${tomlString(m.dep)}, transform = ${tomlArray(m.transform)} }`\n : `${tomlString(m.local)} = ${tomlString(m.dep)}`,\n );\n }\n return lines.join(\"\\n\") + \"\\n\";\n}\n\nexport function renderTask(spec: TaskSpec): string {\n const lines = [\"[[tasks]]\", `id = ${tomlString(spec.id)}`, `prompt = ${tomlString(spec.prompt)}`];\n if (spec.verifiers.length) lines.push(`verifiers = ${tomlArray(spec.verifiers)}`);\n const worlds = Object.entries(spec.worlds);\n if (worlds.length)\n lines.push(`worlds = { ${worlds.map(([alias, names]) => `${alias} = ${tomlArray(names)}`).join(\", \")} }`);\n return lines.join(\"\\n\") + \"\\n\";\n}\n\n/** Table headers of a manifest, `[[tasks]]` as `tasks[]`. */\nexport function tomlHeaders(toml: string): string[] {\n const out: string[] = [];\n for (const raw of toml.split(\"\\n\")) {\n const line = raw.trim();\n const array = /^\\[\\[([^\\]]+)\\]\\]$/.exec(line);\n if (array) out.push(`${array[1]!.trim()}[]`);\n else {\n const table = /^\\[([^\\]]+)\\]$/.exec(line);\n if (table) out.push(table[1]!.trim());\n }\n }\n return out;\n}\n\n/** Aliases from both forms: `[dependencies.<alias>]` tables and `alias = \"slug@ref\"` under `[dependencies]`. */\nexport function declaredAliases(toml: string): string[] {\n const out = new Set(tomlHeaders(toml).filter((h) => h.startsWith(\"dependencies.\")).map((h) => h.split(\".\")[1]!));\n let inline = false;\n for (const raw of toml.split(\"\\n\")) {\n const line = raw.trim();\n if (line.startsWith(\"[\")) inline = line === \"[dependencies]\";\n else if (inline) {\n const m = /^([A-Za-z_][A-Za-z0-9_]*)\\s*=/.exec(line);\n if (m) out.add(m[1]!);\n }\n }\n return [...out];\n}\n\nexport function declaredTaskIds(toml: string): string[] {\n const ids: string[] = [];\n let inTask = false;\n for (const raw of toml.split(\"\\n\")) {\n const line = raw.trim();\n if (line.startsWith(\"[\")) inTask = line === \"[[tasks]]\";\n else if (inTask) {\n const m = /^id\\s*=\\s*\"([^\"]*)\"/.exec(line);\n if (m) ids.push(m[1]!);\n }\n }\n return ids;\n}\n\n/** `name = \"...\"` under `[environment]` (or `[env]`), the world's package id. */\nexport function manifestName(toml: string): string | undefined {\n let inEnv = false;\n for (const raw of toml.split(\"\\n\")) {\n const line = raw.trim();\n if (line.startsWith(\"[\")) inEnv = line === \"[environment]\" || line === \"[env]\";\n else if (inEnv) {\n const m = /^name\\s*=\\s*\"([^\"]*)\"/.exec(line);\n if (m) return m[1]!;\n }\n }\n return undefined;\n}\n\n/** `[tools] serve = [...]`, possibly spread over lines; undefined when absent. */\nexport function manifestServedTools(toml: string): string[] | undefined {\n const m = /^\\s*serve\\s*=\\s*\\[([^\\]]*)\\]/m.exec(toml);\n if (!m) return undefined;\n return [...m[1]!.matchAll(/\"([^\"]*)\"/g)].map((x) => x[1]!);\n}\n\nconst assertManifest = (toml: string) => {\n if (!/^\\s*\\[(environment|env)\\]\\s*$/m.test(toml))\n throw new CliError(\"gateway-env.toml has no [environment] table; it is not a schema world manifest\");\n};\n\n/** Pure: the manifest text with one `[dependencies.<alias>]` appended. */\nexport function addDependency(toml: string, spec: DependencySpec, depServes?: string[]): string {\n assertManifest(toml);\n if (!ALIAS.test(spec.alias))\n throw new CliError(`Aliases match [a-z][a-z0-9_]{0,31}, got ${JSON.stringify(spec.alias)}`);\n if (declaredAliases(toml).includes(spec.alias))\n throw new CliError(`[dependencies.${spec.alias}] is already declared`);\n if (!PIN.test(spec.pin)) throw new CliError(`--pin is <slug>@<ref>, got ${JSON.stringify(spec.pin)}`);\n if (path.isAbsolute(spec.path)) throw new CliError(\"The dependency path is stored relative to the world\");\n if (depServes)\n for (const tool of spec.tools)\n if (!depServes.includes(tool))\n throw new CliError(`${spec.alias} does not serve ${tool}; it serves: ${depServes.join(\", \") || \"nothing\"}`);\n const body = toml.endsWith(\"\\n\") ? toml : toml + \"\\n\";\n return body + \"\\n\" + renderDependency(spec);\n}\n\n/** Pure: the manifest text with one `[[tasks]]` appended. */\nexport function addTask(\n toml: string,\n spec: TaskSpec,\n known: { verifiers?: string[]; depVerifiers?: Record<string, string[] | undefined> } = {},\n): string {\n assertManifest(toml);\n if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(spec.id))\n throw new CliError(`Task ids match [A-Za-z_][A-Za-z0-9_-]*, got ${JSON.stringify(spec.id)}`);\n if (declaredTaskIds(toml).includes(spec.id)) throw new CliError(`Task ${spec.id} is already declared`);\n if (!spec.prompt.trim()) throw new CliError(\"--prompt is what the agent is told; it cannot be empty\");\n if (!spec.verifiers.length && !Object.keys(spec.worlds).length)\n throw new CliError(\"A task grades on at least one verifier: --verifier <name> or --world <alias>=<verifier>\");\n if (known.verifiers)\n for (const v of spec.verifiers)\n if (!known.verifiers.includes(v))\n throw new CliError(`verifiers/${v}.sql does not exist (have: ${known.verifiers.join(\", \") || \"none\"})`);\n const aliases = declaredAliases(toml);\n for (const [alias, names] of Object.entries(spec.worlds)) {\n if (!aliases.includes(alias))\n throw new CliError(\n `--world ${alias}: no [dependencies.${alias}] in gateway-env.toml (have: ${aliases.join(\", \") || \"none\"}); run \\`gateway worlds schema link\\` first`,\n );\n const have = known.depVerifiers?.[alias];\n if (have)\n for (const v of names)\n if (!have.includes(v))\n throw new CliError(`${alias} has no verifiers/${v}.sql (have: ${have.join(\", \") || \"none\"})`);\n }\n const body = toml.endsWith(\"\\n\") ? toml : toml + \"\\n\";\n return body + \"\\n\" + renderTask(spec);\n}\n\n/** `path = \"...\"` of `[dependencies.<alias>]`, when declared. */\nexport function dependencyPath(toml: string, alias: string): string | undefined {\n let inAlias = false;\n for (const raw of toml.split(\"\\n\")) {\n const line = raw.trim();\n if (line.startsWith(\"[\")) inAlias = line === `[dependencies.${alias}]`;\n else if (inAlias) {\n const m = /^path\\s*=\\s*\"([^\"]*)\"/.exec(line);\n if (m) return m[1]!;\n }\n }\n return undefined;\n}\n\n// ── commands ────────────────────────────────────────────────────────────────\n\nfunction readManifest(dir: string): { file: string; toml: string } {\n const file = path.join(dir, \"gateway-env.toml\");\n if (!fs.existsSync(file)) throw new CliError(`${dir} holds no gateway-env.toml; run \\`gateway worlds schema init\\` first`, 1);\n return { file, toml: fs.readFileSync(file, \"utf8\") };\n}\n\nfunction verifierNames(dir: string): string[] | undefined {\n const folder = path.join(dir, \"verifiers\");\n if (!fs.existsSync(folder)) return undefined;\n return fs.readdirSync(folder).filter((f) => f.endsWith(\".sql\")).map((f) => f.slice(0, -4)).sort();\n}\n\nconst toPosix = (p: string) => p.split(path.sep).join(\"/\");\n\n/** A world name as a pin slug: lower-case, anything outside [a-z0-9._-] as `-`. */\nexport const pinSlug = (name: string) =>\n name.toLowerCase().replace(/[^a-z0-9._-]+/g, \"-\").replace(/^[^a-z0-9]+/, \"\") || \"world\";\n\nfunction readJsonFile(file: string): JsonObject {\n if (!fs.existsSync(file)) throw new CliError(`${file} does not exist; run \\`gateway worlds schema init\\` first`, 1);\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(file, \"utf8\"));\n } catch (err) {\n throw new CliError(`${file} is not valid JSON: ${(err as Error).message}`, 1);\n }\n if (!isObject(parsed)) throw new CliError(`${file} must hold a JSON object`, 1);\n return parsed;\n}\n\nfunction declaredEntities(dir: string): string[] | undefined {\n const file = path.join(dir, \"schema\", \"world.json\");\n if (!fs.existsSync(file)) return undefined;\n const gateway = readJsonFile(file)[\"x-gateway\"];\n return isObject(gateway) && isObject(gateway.entities) ? Object.keys(gateway.entities) : [];\n}\n\nconst WORLD_SLUG = /^[a-z0-9][a-z0-9-]*$/;\n\n/** The first route of a world that has none yet: `connector.toml` is created\n * with the [connector] table `worlds connector validate` requires, so the\n * world's API surface starts from the same command that grows it. The slug is\n * the world's [environment] name when that is slug-shaped, else the directory. */\nexport function connectorTomlSkeleton(dir: string): string {\n const manifest = path.join(dir, \"gateway-env.toml\");\n if (!fs.existsSync(manifest))\n throw new CliError(`${dir} holds no connector.toml and no gateway-env.toml; run \\`gateway worlds schema init\\` first`, 1);\n const name = /^\\s*name\\s*=\\s*\"([^\"]*)\"/m.exec(fs.readFileSync(manifest, \"utf8\"))?.[1];\n const slug = name && WORLD_SLUG.test(name) ? name : path.basename(dir).toLowerCase().replace(/[^a-z0-9-]+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"world\";\n return [\n `# ${slug}'s API surface: the HTTP routes the world serves beside its tools, from one`,\n \"# World Host session. Declare routes with `gateway worlds connector route add`; an\",\n \"# operation with `--action handler` runs a function from api/handlers.py.\",\n \"[connector]\",\n `slug = \"${slug}\"`,\n `base_url = \"https://${slug}.example\"`,\n \"\",\n ].join(\"\\n\");\n}\n\n/** The scaffold's placeholder verifier (`verifiers/state_present.sql`, \"any row of\n * the first entity\"). It names one entity; when that entity is gone from the\n * catalog the world no longer checks, so `entity add` re-points it at the\n * entity being declared. Only the untouched placeholder is rewritten: an edited\n * verifier is the author's. */\nconst SCAFFOLD_VERIFIER = /^-- Scores 1\\.0 once the world holds any (\\S+) row; edit for real tasks\\.\\n/;\n\nexport function scaffoldVerifier(entity: string): string {\n return (\n `-- Scores 1.0 once the world holds any ${entity} row; edit for real tasks.\\n` +\n `SELECT CASE WHEN COUNT(*) > 0 THEN 1.0 ELSE 0.0 END FROM \"${entity}\";\\n`\n );\n}\n\n/** Re-point the placeholder verifier at `entity` when it names an entity the\n * catalog no longer declares; returns the verifier's path when it was rewritten. */\nexport function repointScaffoldVerifier(dir: string, entity: string, declared: string[]): string | null {\n const file = path.join(dir, \"verifiers\", \"state_present.sql\");\n if (!fs.existsSync(file)) return null;\n const text = fs.readFileSync(file, \"utf8\");\n const match = SCAFFOLD_VERIFIER.exec(text);\n if (!match || text !== scaffoldVerifier(match[1]!)) return null;\n if (declared.includes(match[1]!)) return null;\n fs.writeFileSync(file, scaffoldVerifier(entity));\n return file;\n}\n\nfunction parsePairs(values: string[], flag: string): Record<string, string> {\n const out: Record<string, string> = {};\n for (const item of values) {\n const eq = item.indexOf(\"=\");\n if (eq === -1) throw new CliError(`--${flag} looks like name=value, got ${JSON.stringify(item)}`);\n out[item.slice(0, eq).trim()] = item.slice(eq + 1).trim();\n }\n return out;\n}\n\nexport function registerScaffoldCommands(worlds: CommandGroup): void {\n const schema = worlds.group(\n \"schema\",\n \"Compile and check gateway-world/1 contracts (the runtime runs on the platform).\",\n );\n schema\n .group(\"entity\", \"Declare entities in schema/world.json without hand-editing the catalog.\")\n .command({\n name: \"add\",\n help: \"Declare one entity in schema/world.json: its payload, primary key, unique keys and relationships.\",\n positionals: [\n { name: \"path\", help: \"World directory holding schema/world.json\" },\n { name: \"entity\", help: \"Entity name, e.g. crm_accounts\" },\n ],\n flags: [\n { name: \"ref\", help: \"Payload is an existing $defs entry: --ref Account.\" },\n { name: \"fields\", help: \"Write a closed object def and reference it: --fields id:string,name:string,archived:boolean?\" },\n { name: \"schema\", help: \"Inline JSON Schema for the payload (a JSON string).\" },\n { name: \"key\", help: \"Primary-key field; repeat for a composite key.\", short: \"k\", repeat: true },\n { name: \"unique\", help: \"Unique key as field[,field]; repeatable.\", repeat: true },\n {\n name: \"relationship\",\n help: \"field[,field]->target_entity; repeatable. on_delete is always restrict.\",\n repeat: true,\n },\n ],\n notes:\n \"Exactly one of --ref, --fields or --schema. The file is rewritten with two-space indentation;\\n\" +\n \"run `gateway worlds schema check <path>` afterwards for the full contract check.\",\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const file = path.join(dir, \"schema\", \"world.json\");\n const root = readJsonFile(file);\n let inline: JsonObject | undefined;\n const schemaFlag = arg.str(args, \"schema\");\n if (schemaFlag !== undefined) {\n let parsed: unknown;\n try {\n parsed = JSON.parse(schemaFlag);\n } catch (err) {\n throw new CliError(`--schema is not valid JSON: ${(err as Error).message}`);\n }\n if (!isObject(parsed)) throw new CliError(\"--schema must be a JSON object\");\n inline = parsed;\n }\n const name = args.positionals[1]!;\n const { document, declaration, def } = addEntity(root, {\n name,\n ref: arg.str(args, \"ref\"),\n fields: arg.str(args, \"fields\"),\n schema: inline,\n primaryKey: arg.list(args, \"key\"),\n unique: arg.list(args, \"unique\").map((u) => u.split(\",\").map((f) => f.trim()).filter(Boolean)),\n relationships: arg.list(args, \"relationship\").map(parseRelationship),\n });\n fs.writeFileSync(file, JSON.stringify(document, null, 2) + \"\\n\");\n const out: JsonObject = { status: \"ok\", entity: name, declaration, file: path.relative(process.cwd(), file) || file };\n if (def) out.def = def;\n const verifier = repointScaffoldVerifier(dir, name, declaredEntities(dir) ?? []);\n if (verifier) {\n out.verifier = path.relative(process.cwd(), verifier) || verifier;\n ctx.stderr(`# ${out.verifier} named an entity the catalog no longer declares; it now scores over ${name}`);\n }\n ctx.stdout(JSON.stringify(out, null, 2));\n },\n });\n\n schema.command({\n name: \"link\",\n help: \"Link another local world as [dependencies.<alias>] in gateway-env.toml: its tools serve as <alias>.<tool>, its verifiers grade as <alias>/<verifier>.\",\n positionals: [\n { name: \"path\", help: \"World directory holding gateway-env.toml (the root world)\" },\n { name: \"alias\", help: \"Short name for the link, e.g. slack; [a-z][a-z0-9_]*\" },\n {\n name: \"dependency\",\n help: \"Directory of the world to link, relative to your shell like any path (a schema world with its own gateway-env.toml)\",\n },\n ],\n flags: [\n { name: \"pin\", help: \"<slug>@<ref> the platform resolves at push; default <dependency name>@main.\" },\n { name: \"tools\", help: \"Dependency tools to serve as <alias>.<tool>; comma-separated or repeatable. Default: none.\", repeat: true },\n { name: \"task\", help: \"Scenario the dependency starts in: scenarios/<name>/ of its tree (the shipped templates have `default`).\" },\n {\n name: \"map\",\n help: \"local_entity.field=dep_entity.field[:transform,...] joining rows across the two worlds; repeatable.\",\n repeat: true,\n },\n ],\n notes:\n \"The block is appended; existing text is untouched. `path` is written relative to the world so\\n\" +\n \"`schema check`, `test`, `serve` and `call` open the dependency here; the pin is what the platform\\n\" +\n \"resolves when both worlds are pushed. Then `gateway worlds schema check <path>` shows the link under\\n\" +\n \"`dependencies`, and `gateway worlds schema task add` grades it with --world <alias>=<verifier>.\",\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const alias = args.positionals[1]!;\n const depArg = args.positionals[2]!;\n const depDir = path.resolve(depArg);\n const { file, toml } = readManifest(dir);\n if (!fs.existsSync(path.join(depDir, \"gateway-env.toml\"))) {\n const fromWorld = path.resolve(dir, depArg);\n const hint =\n fromWorld !== depDir && fs.existsSync(path.join(fromWorld, \"gateway-env.toml\"))\n ? `; paths resolve from your shell, not from the world: did you mean ${path.relative(process.cwd(), fromWorld) || \".\"}?`\n : \"\";\n throw new CliError(\n `${depDir} holds no gateway-env.toml; the dependency must be a schema world (\\`gateway worlds schema init\\`)${hint}`,\n 1,\n );\n }\n if (path.resolve(depDir) === dir) throw new CliError(\"A world cannot depend on itself\");\n const depToml = fs.readFileSync(path.join(depDir, \"gateway-env.toml\"), \"utf8\");\n if (declaredAliases(depToml).length)\n throw new CliError(`${depDir} has [dependencies] of its own (${declaredAliases(depToml).join(\", \")}); links nest one level`);\n const task = arg.str(args, \"task\");\n if (task !== undefined && !fs.existsSync(path.join(depDir, \"scenarios\", task))) {\n const have = fs.existsSync(path.join(depDir, \"scenarios\")) ? fs.readdirSync(path.join(depDir, \"scenarios\")) : [];\n throw new CliError(`${depDir} has no scenarios/${task}/ (have: ${have.join(\", \") || \"none\"})`);\n }\n const rel = toPosix(path.relative(dir, depDir)) || \".\";\n const spec: DependencySpec = {\n alias,\n pin: arg.str(args, \"pin\") ?? `${pinSlug(manifestName(depToml) ?? path.basename(depDir))}@main`,\n path: rel.startsWith(\".\") ? rel : `./${rel}`,\n task,\n tools: arg.list(args, \"tools\").flatMap((t) => t.split(\",\")).map((t) => t.trim()).filter(Boolean),\n entities: arg.list(args, \"map\").map(parseEntityMap),\n };\n const updated = addDependency(toml, spec, manifestServedTools(depToml));\n fs.writeFileSync(file, updated);\n ctx.stdout(\n JSON.stringify(\n {\n status: \"ok\",\n alias,\n pin: spec.pin,\n path: spec.path,\n task: spec.task ?? null,\n tools: spec.tools.map((t) => `${alias}.${t}`),\n verifiers: (verifierNames(depDir) ?? []).map((v) => `${alias}/${v}`),\n file: path.relative(process.cwd(), file) || file,\n next: `gateway worlds schema check ${path.relative(process.cwd(), dir) || \".\"}`,\n },\n null,\n 2,\n ),\n );\n },\n });\n\n schema\n .group(\"task\", \"Declare [[tasks]] in gateway-env.toml: a prompt plus the verifiers that grade it (the platform's stored tasks are `gateway worlds task`).\")\n .command({\n name: \"add\",\n help: \"Append one [[tasks]] entry: the prompt an agent is given and the root and dependency verifiers that grade the session.\",\n positionals: [\n { name: \"path\", help: \"World directory holding gateway-env.toml\" },\n { name: \"id\", help: \"Task id, e.g. escalate_locked_account; what `worlds serve --task` takes\" },\n ],\n flags: [\n { name: \"prompt\", help: \"What the agent is told.\", short: \"p\" },\n { name: \"verifier\", help: \"Root verifier (verifiers/<name>.sql); repeatable.\", repeat: true },\n {\n name: \"world\",\n help: \"<alias>=<verifier>[,<verifier>]: a linked world's verifier, graded on that world's own state; repeatable.\",\n repeat: true,\n },\n ],\n notes:\n \"Verifiers are SQL files returning one number in 0..1; each becomes a key in `rewards` (`slack/state_present`\\n\" +\n \"for a dependency's). Then `gateway worlds schema check <path>` lists the task, and\\n\" +\n \"`gateway worlds serve <path> --task <id>` opens a session on it.\",\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const { file, toml } = readManifest(dir);\n const prompt = arg.str(args, \"prompt\");\n if (prompt === undefined) throw new CliError(\"--prompt is required: what the agent is told\");\n const worlds: Record<string, string[]> = {};\n for (const item of arg.list(args, \"world\")) {\n const eq = item.indexOf(\"=\");\n if (eq === -1) throw new CliError(`--world looks like alias=verifier[,verifier], got ${JSON.stringify(item)}`);\n const alias = item.slice(0, eq).trim();\n const names = item.slice(eq + 1).split(\",\").map((v) => v.trim()).filter(Boolean);\n if (!names.length) throw new CliError(`--world ${alias} names no verifier`);\n worlds[alias] = [...(worlds[alias] ?? []), ...names];\n }\n const depVerifiers: Record<string, string[] | undefined> = {};\n for (const alias of Object.keys(worlds)) {\n const rel = dependencyPath(toml, alias);\n if (rel !== undefined) depVerifiers[alias] = verifierNames(path.resolve(dir, rel));\n }\n const spec: TaskSpec = { id: args.positionals[1]!, prompt, verifiers: arg.list(args, \"verifier\"), worlds };\n const updated = addTask(toml, spec, { verifiers: verifierNames(dir), depVerifiers });\n fs.writeFileSync(file, updated);\n ctx.stdout(\n JSON.stringify(\n {\n status: \"ok\",\n task: spec.id,\n verifiers: spec.verifiers,\n worlds,\n rewards: [...spec.verifiers, ...Object.entries(worlds).flatMap(([a, names]) => names.map((n) => `${a}/${n}`))],\n file: path.relative(process.cwd(), file) || file,\n next: `gateway worlds serve ${path.relative(process.cwd(), dir) || \".\"} --task ${spec.id}`,\n },\n null,\n 2,\n ),\n );\n },\n });\n\n const connector = worlds.group(\n \"connector\",\n \"Vendor connections: validate, capture, conform, ingest, publish, clone.\",\n );\n connector\n .group(\"route\", \"Declare operations in connector.toml without hand-editing the spec.\")\n .command({\n name: \"add\",\n help: \"Append one [[operations]] entry to connector.toml; a world without one gets its connector.toml here.\",\n positionals: [\n { name: \"path\", help: \"World directory (holding connector.toml, or gateway-env.toml for its first route)\" },\n { name: \"name\", help: \"Operation name, e.g. list_users\" },\n ],\n flags: [\n { name: \"method\", help: \"HTTP method.\", short: \"X\", default: \"GET\" },\n { name: \"path\", help: \"Vendor path under base_url; {arg} segments become path arguments.\", short: \"p\" },\n { name: \"param\", help: \"Declared query parameter; repeatable.\", repeat: true },\n { name: \"entity\", help: \"Entity the rows seed and the route answers from (from schema/world.json).\" },\n { name: \"results\", help: \"Dotted path to the row array in the vendor body; empty when the body is the row.\" },\n { name: \"action\", help: \"read (default), create, update, delete or handler.\" },\n { name: \"status\", help: \"2xx the vendor answers (201 for create, 204 for delete by default).\" },\n {\n name: \"envelope\",\n help: \"Key the SERVED answer wraps its rows under (`data` for {\\\"data\\\": [...]}); \\\"\\\" for a bare array. Default: [api].envelope. --results is the capture side.\",\n },\n { name: \"single\", help: \"Answer the row itself instead of an envelope.\", boolean: true },\n { name: \"filter\", help: \"arg=row_field selecting rows by a path argument or --param; repeatable.\", repeat: true },\n { name: \"body\", help: \"row_field=request.body.path for create/update; repeatable.\", repeat: true },\n { name: \"handler\", help: \"Function in api/handlers.py (with --action handler).\" },\n { name: \"replace\", help: \"Rewrite the existing [[operations]] block of this name instead of refusing it.\", boolean: true },\n ],\n notes:\n \"A schema world with no connector.toml yet gets one: [connector] slug from its [environment] name, a\\n\" +\n \"placeholder base_url, then this route. That file is the world's API surface, served with its tools.\\n\" +\n \"Existing text is untouched; the block is appended. With --replace the block already declared under this\\n\" +\n \"name (and its [operations.api]) is removed first and the new one appended, every other byte kept.\\n\" +\n \"--entity must already be declared in schema/world.json (`gateway worlds schema entity add`). Then\\n\" +\n \"`gateway worlds connector validate <path>`.\",\n run: async (args, ctx) => {\n const dir = path.resolve(args.positionals[0]!);\n const file = path.join(dir, \"connector.toml\");\n const created = !fs.existsSync(file);\n const routePath = arg.str(args, \"path\");\n if (routePath === undefined) throw new CliError(\"--path is required, e.g. --path /users\");\n const spec: RouteSpec = {\n name: args.positionals[1]!,\n method: (arg.str(args, \"method\") ?? \"GET\").toUpperCase(),\n path: routePath,\n params: arg.list(args, \"param\"),\n entity: arg.str(args, \"entity\"),\n results: arg.str(args, \"results\"),\n api: {\n action: arg.str(args, \"action\"),\n status: arg.int(args, \"status\"),\n envelope: arg.str(args, \"envelope\"),\n single: arg.bool(args, \"single\"),\n filter: parsePairs(arg.list(args, \"filter\"), \"filter\"),\n body: parsePairs(arg.list(args, \"body\"), \"body\"),\n handler: arg.str(args, \"handler\"),\n },\n };\n const replace = arg.bool(args, \"replace\");\n const current = created ? connectorTomlSkeleton(dir) : fs.readFileSync(file, \"utf8\");\n const updated = addRoute(current, spec, declaredEntities(dir), { replace });\n fs.writeFileSync(file, updated);\n ctx.stdout(\n JSON.stringify(\n {\n status: \"ok\",\n operation: spec.name,\n method: spec.method,\n path: spec.path,\n entity: spec.entity ?? null,\n ...(replace ? { replaced: true } : {}),\n ...(created ? { created: true } : {}),\n file: path.relative(process.cwd(), file) || file,\n },\n null,\n 2,\n ),\n );\n },\n });\n}\n","#!/usr/bin/env node\n/**\n * The `gateway` CLI — the TypeScript port of the Python CLI, group for group:\n * auth, secret, agent, run, dataset, bench, worlds (session, schema,\n * connector, data, skill, run, ci, serve), environment, release. The tree\n * lives in src/cli/main.ts; each group in src/cli/platform/* (platform API)\n * or src/cli/runtime/* (the schema runtime, which runs on the platform).\n */\nimport { main } from \"./cli/main\";\n\n// Set the exit code and let the event loop drain rather than calling\n// process.exit: a piped stdout is asynchronous, and exiting the moment the\n// command returns truncated anything past the first 64 KiB (`describe --json`\n// of a real world, a long `session export`) for whoever was reading the pipe.\nmain().then(\n (code) => {\n process.exitCode = code;\n },\n (error) => {\n process.stderr.write((error instanceof Error ? error.message : String(error)) + \"\\n\");\n process.exitCode = 1;\n },\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsFO,SAAS,UAAU,MAAmB,MAAwB;AACnE,QAAM,YAAY,KAAK,SAAS,CAAC;AACjC,QAAM,SAAS,oBAAI,IAAsB;AACzC,aAAW,KAAK,WAAW;AACzB,WAAO,IAAI,EAAE,MAAM,CAAC;AACpB,QAAI,EAAE,MAAO,QAAO,IAAI,EAAE,OAAO,CAAC;AAAA,EACpC;AACA,QAAM,cAAwB,CAAC;AAC/B,QAAM,QAAyB,CAAC;AAChC,MAAI,kBAAkB;AACtB,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,UAAMA,OAAM,KAAK,CAAC;AAClB,QAAI,mBAAmB,CAACA,KAAI,WAAW,GAAG,KAAKA,SAAQ,KAAK;AAC1D,kBAAY,KAAKA,IAAG;AACpB;AAAA,IACF;AACA,QAAIA,SAAQ,MAAM;AAChB,wBAAkB;AAClB;AAAA,IACF;AACA,UAAM,OAAOA,KAAI,QAAQ,QAAQ,EAAE;AACnC,UAAM,CAAC,SAAS,WAAW,IAAI,KAAK,SAAS,GAAG,IAC5C,CAAC,KAAK,MAAM,GAAG,KAAK,QAAQ,GAAG,CAAC,GAAG,KAAK,MAAM,KAAK,QAAQ,GAAG,IAAI,CAAC,CAAC,IACpE,CAAC,MAAM,MAAS;AACpB,UAAM,IAAI,OAAO,IAAI,OAAO;AAC5B,QAAI,CAA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,YAAQ,WAAW;AAAA,EACrB;AAAA,EACA,CAAC,UAAU;AACT,YAAQ,OAAO,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAAK,IAAI;AACpF,YAAQ,WAAW;AAAA,EACrB;AACF;","names":["arg","path","lines","command","text","fs","text","command","path","resolve","fs","path","named","resolve","text","command","fs","path","walk","text","path","query","observe","text","resolve","sleep","openWorld","sleep","api","path","summary","timeoutMs","pollMs","redact","query","fs","path","walk","pad","text","SKIP_DIRS","resolve","source","sample","text","hex","createHash","createHash","shaped","text","digest","redact","named","fs","path","BUILD_OUTPUT","records","spawn","fs","os","path","isObject","records","timeoutMs","resolve","createHash","fs","sleep","text","resolve","createHash","text","fs","os","path","isObject","records","text","ingestLocalToolCalls","importLocalWorldData","checkLocalWorldData","redact","transformRecords","pull","pushRows","path","text","resolve","openSession","fs","path","text","relative","source","skill","fs","path","relative","readText","text","files","table","exists","source","fs","path","text","HOST_FLAG","command","out","query","fs","os","path","text","sample","row","id","stepSummary","fs","path","fs","path","text","source","spawnSync","fs","os","path","text","source","spawnSync","tail","timeoutMs","ran","fs","getRun","dispatch","failed","fs","path","fs","path","text","isObject","redact","relative","text","describeLocalWorld","withRowCounts","showLocalWorldData","credentialsForRuntime","failed","renderDescription","command","text","readConfig","writeConfig","report","result","failed","plan","describe","fs","os","path","Readable","isObject","text","records","summary","fs","text","refuse","path","rowObject","jsonlRows","text","summary","refuse","rowObject","text","path","fs","path","text","table","rest","text","isObject","records","fs","readText","records","text","fs","path","digest","fs","path","table","redact","fs","os","path","createHash","fs","path","text","listFiles","source","createHash","isDirectory","source","summary","resolve","showLocalWorldData","credentialsForRuntime","creds","queryLocalWorldData","queryLocalWorldDataAcross","result","queryRows","Readable","pollMs","named","status","toolCallsFromObservations","records","fetchToolObservations","text","pairs","redact","ingestLocalToolCalls","importLocalWorldData","checkLocalWorldData","BridgeRejected","table","sample","fs","path","fs","path","listFiles","join","walk","TERMINAL_STATES","sortedJson","fs","fs","MESSAGE_FLAG","pairs","EXPORT_PAGE","timeoutMs","redact","text","fs","qs","text","qs","summary","isObject","text","push","JSON_FLAG","summary","resolve","stamp","readFile","fs","path","HOST_FLAG","pairs","sleep","resolveEnvironmentId","drivePath","relative","manifestPath","registerConnectorCommands","summary","res","result","fs","path","HOST_FLAG","createRequire","registerRunCommands","summary","stepSummary","fs","path","scenario","fs","path","creds","scenario","resolve","report","out","fs","path","parseArgs","text","stdin","seedRaw","report","fs","path","isObject","pairs","api","named","declaredEntities","text","TRANSFORMS","table","readManifest","verifierNames","worlds","registerConnectorCommands","registerRunCommands"]}