@strands-agents/cli 0.4.0 → 0.6.0

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 (259) hide show
  1. package/README.md +374 -5
  2. package/dist/src/agent/backend.js +2 -2
  3. package/dist/src/agent/backend.js.map +1 -1
  4. package/dist/src/agent/background.js +9 -1
  5. package/dist/src/agent/background.js.map +1 -1
  6. package/dist/src/agent/configuration.js.map +1 -1
  7. package/dist/src/agent/context.js +5 -1
  8. package/dist/src/agent/context.js.map +1 -1
  9. package/dist/src/agent/events.js +2 -0
  10. package/dist/src/agent/events.js.map +1 -1
  11. package/dist/src/agent/extension.js +46 -0
  12. package/dist/src/agent/extension.js.map +1 -0
  13. package/dist/src/agent/mcp.js +1 -2
  14. package/dist/src/agent/mcp.js.map +1 -1
  15. package/dist/src/agent/runtime.js +28 -5
  16. package/dist/src/agent/runtime.js.map +1 -1
  17. package/dist/src/cli/acp-events.js +15 -0
  18. package/dist/src/cli/acp-events.js.map +1 -1
  19. package/dist/src/cli/acp-python.js +2 -2
  20. package/dist/src/cli/acp-python.js.map +1 -1
  21. package/dist/src/cli/acp.js +2 -17
  22. package/dist/src/cli/acp.js.map +1 -1
  23. package/dist/src/cli/arguments.js +91 -11
  24. package/dist/src/cli/arguments.js.map +1 -1
  25. package/dist/src/cli/console.js +2 -0
  26. package/dist/src/cli/console.js.map +1 -1
  27. package/dist/src/cli/invocation.js +10 -2
  28. package/dist/src/cli/invocation.js.map +1 -1
  29. package/dist/src/cli/run.js +154 -15
  30. package/dist/src/cli/run.js.map +1 -1
  31. package/dist/src/cli/telemetry.js.map +1 -1
  32. package/dist/src/config/settings.js +67 -2
  33. package/dist/src/config/settings.js.map +1 -1
  34. package/dist/src/config/store.js +171 -21
  35. package/dist/src/config/store.js.map +1 -1
  36. package/dist/src/config/watch.js +24 -0
  37. package/dist/src/config/watch.js.map +1 -0
  38. package/dist/src/dev/agent-choices.js +281 -0
  39. package/dist/src/dev/agent-choices.js.map +1 -0
  40. package/dist/src/dev/agent-options.js +467 -0
  41. package/dist/src/dev/agent-options.js.map +1 -0
  42. package/dist/src/dev/base-cli.js +201 -0
  43. package/dist/src/dev/base-cli.js.map +1 -0
  44. package/dist/src/dev/chat-extension.js +42 -0
  45. package/dist/src/dev/chat-extension.js.map +1 -0
  46. package/dist/src/dev/create.js +443 -0
  47. package/dist/src/dev/create.js.map +1 -0
  48. package/dist/src/dev/errors.js +89 -0
  49. package/dist/src/dev/errors.js.map +1 -0
  50. package/dist/src/dev/evals/chat/agent-tools.js +941 -0
  51. package/dist/src/dev/evals/chat/agent-tools.js.map +1 -0
  52. package/dist/src/dev/evals/chat/background-flags.js +231 -0
  53. package/dist/src/dev/evals/chat/background-flags.js.map +1 -0
  54. package/dist/src/dev/evals/chat/command.js +140 -0
  55. package/dist/src/dev/evals/chat/command.js.map +1 -0
  56. package/dist/src/dev/evals/chat/ui-tools.js +252 -0
  57. package/dist/src/dev/evals/chat/ui-tools.js.map +1 -0
  58. package/dist/src/dev/evals/chat/workflow-skills.js +48 -0
  59. package/dist/src/dev/evals/chat/workflow-skills.js.map +1 -0
  60. package/dist/src/dev/evals/host.js +22 -0
  61. package/dist/src/dev/evals/host.js.map +1 -0
  62. package/dist/src/dev/evals/jobs.js +151 -0
  63. package/dist/src/dev/evals/jobs.js.map +1 -0
  64. package/dist/src/dev/evals/layout.js +223 -0
  65. package/dist/src/dev/evals/layout.js.map +1 -0
  66. package/dist/src/dev/evals/model.js +4 -0
  67. package/dist/src/dev/evals/model.js.map +1 -0
  68. package/dist/src/dev/evals/package.js +14 -0
  69. package/dist/src/dev/evals/package.js.map +1 -0
  70. package/dist/src/dev/evals/python/entry-files.js +70 -0
  71. package/dist/src/dev/evals/python/entry-files.js.map +1 -0
  72. package/dist/src/dev/evals/python/strands_dev_evals/__init__.py +0 -0
  73. package/dist/src/dev/evals/python/strands_dev_evals/errors.py +2 -0
  74. package/dist/src/dev/evals/python/strands_dev_evals/harness.py +265 -0
  75. package/dist/src/dev/evals/python/strands_dev_evals/imports.py +61 -0
  76. package/dist/src/dev/evals/python/strands_dev_evals/model_effort.py +120 -0
  77. package/dist/src/dev/evals/python/strands_dev_evals/optimize.py +152 -0
  78. package/dist/src/dev/evals/python/strands_dev_evals/run.py +55 -0
  79. package/dist/src/dev/evals/python/strands_dev_evals/space.py +212 -0
  80. package/dist/src/dev/evals/python/strands_dev_evals/temporary_typescript.py +313 -0
  81. package/dist/src/dev/evals/runs/background-runs.js +182 -0
  82. package/dist/src/dev/evals/runs/background-runs.js.map +1 -0
  83. package/dist/src/dev/evals/runs/environment.js +258 -0
  84. package/dist/src/dev/evals/runs/environment.js.map +1 -0
  85. package/dist/src/dev/evals/runs/evals-process.js +157 -0
  86. package/dist/src/dev/evals/runs/evals-process.js.map +1 -0
  87. package/dist/src/dev/evals/runs/evaluate.js +288 -0
  88. package/dist/src/dev/evals/runs/evaluate.js.map +1 -0
  89. package/dist/src/dev/evals/runs/experiment.js +319 -0
  90. package/dist/src/dev/evals/runs/experiment.js.map +1 -0
  91. package/dist/src/dev/evals/runs/layout-migration.js +302 -0
  92. package/dist/src/dev/evals/runs/layout-migration.js.map +1 -0
  93. package/dist/src/dev/evals/runs/optimize.js +249 -0
  94. package/dist/src/dev/evals/runs/optimize.js.map +1 -0
  95. package/dist/src/dev/evals/runs/typescript-runner-main.js +40 -0
  96. package/dist/src/dev/evals/runs/typescript-runner-main.js.map +1 -0
  97. package/dist/src/dev/evals/runs/typescript-runner.js +192 -0
  98. package/dist/src/dev/evals/runs/typescript-runner.js.map +1 -0
  99. package/dist/src/dev/evals/sessions/auto-optimize.js +259 -0
  100. package/dist/src/dev/evals/sessions/auto-optimize.js.map +1 -0
  101. package/dist/src/dev/evals/sessions/evals-ui.js +232 -0
  102. package/dist/src/dev/evals/sessions/evals-ui.js.map +1 -0
  103. package/dist/src/dev/evals/sessions/evaluate-session.js +252 -0
  104. package/dist/src/dev/evals/sessions/evaluate-session.js.map +1 -0
  105. package/dist/src/dev/evals/sessions/experiments-session.js +305 -0
  106. package/dist/src/dev/evals/sessions/experiments-session.js.map +1 -0
  107. package/dist/src/dev/evals/sessions/optimize-session.js +942 -0
  108. package/dist/src/dev/evals/sessions/optimize-session.js.map +1 -0
  109. package/dist/src/dev/evals/sessions/review-run.js +245 -0
  110. package/dist/src/dev/evals/sessions/review-run.js.map +1 -0
  111. package/dist/src/dev/evals/sessions/session-converter.js +110 -0
  112. package/dist/src/dev/evals/sessions/session-converter.js.map +1 -0
  113. package/dist/src/dev/evals/sessions/sessions.js +81 -0
  114. package/dist/src/dev/evals/sessions/sessions.js.map +1 -0
  115. package/dist/src/dev/evals/shell/arguments.js +26 -0
  116. package/dist/src/dev/evals/shell/arguments.js.map +1 -0
  117. package/dist/src/dev/evals/shell/cli.js +77 -0
  118. package/dist/src/dev/evals/shell/cli.js.map +1 -0
  119. package/dist/src/dev/evals/tuning/apply.js +535 -0
  120. package/dist/src/dev/evals/tuning/apply.js.map +1 -0
  121. package/dist/src/dev/evals/tuning/knobs.js +293 -0
  122. package/dist/src/dev/evals/tuning/knobs.js.map +1 -0
  123. package/dist/src/dev/evals/tuning/objective.js +273 -0
  124. package/dist/src/dev/evals/tuning/objective.js.map +1 -0
  125. package/dist/src/dev/evals/tuning/plan.js +156 -0
  126. package/dist/src/dev/evals/tuning/plan.js.map +1 -0
  127. package/dist/src/dev/evals/tuning/study.js +392 -0
  128. package/dist/src/dev/evals/tuning/study.js.map +1 -0
  129. package/dist/src/dev/failed-turns.js +31 -0
  130. package/dist/src/dev/failed-turns.js.map +1 -0
  131. package/dist/src/dev/file-edits.js +67 -0
  132. package/dist/src/dev/file-edits.js.map +1 -0
  133. package/dist/src/dev/fix-in-new-tab.js +151 -0
  134. package/dist/src/dev/fix-in-new-tab.js.map +1 -0
  135. package/dist/src/dev/picker.js +498 -0
  136. package/dist/src/dev/picker.js.map +1 -0
  137. package/dist/src/dev/prepare.js +526 -0
  138. package/dist/src/dev/prepare.js.map +1 -0
  139. package/dist/src/dev/project-setup.js +209 -0
  140. package/dist/src/dev/project-setup.js.map +1 -0
  141. package/dist/src/dev/runtime.js +55 -0
  142. package/dist/src/dev/runtime.js.map +1 -0
  143. package/dist/src/dev/search.js +466 -0
  144. package/dist/src/dev/search.js.map +1 -0
  145. package/dist/src/dev/telemetry.js +30 -0
  146. package/dist/src/dev/telemetry.js.map +1 -0
  147. package/dist/src/dev/workspace.js +547 -0
  148. package/dist/src/dev/workspace.js.map +1 -0
  149. package/dist/src/model/credential-failure.js +5 -0
  150. package/dist/src/model/credential-failure.js.map +1 -0
  151. package/dist/src/model/effort-fields.js +76 -0
  152. package/dist/src/model/effort-fields.js.map +1 -0
  153. package/dist/src/model/packages.js +2 -0
  154. package/dist/src/model/packages.js.map +1 -1
  155. package/dist/src/model/runtime.js +12 -4
  156. package/dist/src/model/runtime.js.map +1 -1
  157. package/dist/src/paths.js +9 -1
  158. package/dist/src/paths.js.map +1 -1
  159. package/dist/src/process-lock.js +89 -0
  160. package/dist/src/process-lock.js.map +1 -0
  161. package/dist/src/project/archive.js +11 -1
  162. package/dist/src/project/archive.js.map +1 -1
  163. package/dist/src/project/export.js +40 -14
  164. package/dist/src/project/export.js.map +1 -1
  165. package/dist/src/project/install.js +33 -0
  166. package/dist/src/project/install.js.map +1 -0
  167. package/dist/src/project/module-loader.js +36 -0
  168. package/dist/src/project/module-loader.js.map +1 -1
  169. package/dist/src/project/portability.js +2 -1
  170. package/dist/src/project/portability.js.map +1 -1
  171. package/dist/src/project/preparation-plan.js +182 -0
  172. package/dist/src/project/preparation-plan.js.map +1 -0
  173. package/dist/src/project/preparation.js +515 -0
  174. package/dist/src/project/preparation.js.map +1 -0
  175. package/dist/src/project/python-runtime.js +234 -0
  176. package/dist/src/project/python-runtime.js.map +1 -0
  177. package/dist/src/project/python.js +44 -11
  178. package/dist/src/project/python.js.map +1 -1
  179. package/dist/src/project/source.js +12 -7
  180. package/dist/src/project/source.js.map +1 -1
  181. package/dist/src/project/state-folder.js +15 -0
  182. package/dist/src/project/state-folder.js.map +1 -0
  183. package/dist/src/project/typescript-backend.js +18 -8
  184. package/dist/src/project/typescript-backend.js.map +1 -1
  185. package/dist/src/project/typescript-worker.js +14 -0
  186. package/dist/src/project/typescript-worker.js.map +1 -1
  187. package/dist/src/project/typescript.js +14 -1
  188. package/dist/src/project/typescript.js.map +1 -1
  189. package/dist/src/project/watch.js +37 -6
  190. package/dist/src/project/watch.js.map +1 -1
  191. package/dist/src/project/worker.py +168 -14
  192. package/dist/src/session/desktop-profile.js +4 -0
  193. package/dist/src/session/desktop-profile.js.map +1 -1
  194. package/dist/src/session/sessions.js +18 -2
  195. package/dist/src/session/sessions.js.map +1 -1
  196. package/dist/src/terminal/npm.js +1 -1
  197. package/dist/src/terminal/npm.js.map +1 -1
  198. package/dist/src/terminal/terminal.js +16 -2
  199. package/dist/src/terminal/terminal.js.map +1 -1
  200. package/dist/src/terminal/text.js +23 -0
  201. package/dist/src/terminal/text.js.map +1 -1
  202. package/dist/src/ui/app.js +17 -6
  203. package/dist/src/ui/app.js.map +1 -1
  204. package/dist/src/ui/chat/commands.js +3 -5
  205. package/dist/src/ui/chat/commands.js.map +1 -1
  206. package/dist/src/ui/chat/controller.js +405 -38
  207. package/dist/src/ui/chat/controller.js.map +1 -1
  208. package/dist/src/ui/chat/conversations.js +88 -10
  209. package/dist/src/ui/chat/conversations.js.map +1 -1
  210. package/dist/src/ui/chat/help.js +8 -0
  211. package/dist/src/ui/chat/help.js.map +1 -1
  212. package/dist/src/ui/chat/panel-state.js +36 -14
  213. package/dist/src/ui/chat/panel-state.js.map +1 -1
  214. package/dist/src/ui/chat/projector.js +10 -0
  215. package/dist/src/ui/chat/projector.js.map +1 -1
  216. package/dist/src/ui/chat/runtime.js +106 -9
  217. package/dist/src/ui/chat/runtime.js.map +1 -1
  218. package/dist/src/ui/chat/screen.js +215 -55
  219. package/dist/src/ui/chat/screen.js.map +1 -1
  220. package/dist/src/ui/chat/state.js +28 -0
  221. package/dist/src/ui/chat/state.js.map +1 -1
  222. package/dist/src/ui/chat/transcript-turn.js +15 -3
  223. package/dist/src/ui/chat/transcript-turn.js.map +1 -1
  224. package/dist/src/ui/chat/transcript.js +7 -5
  225. package/dist/src/ui/chat/transcript.js.map +1 -1
  226. package/dist/src/ui/chat/types.js.map +1 -1
  227. package/dist/src/ui/chat/view.js +84 -27
  228. package/dist/src/ui/chat/view.js.map +1 -1
  229. package/dist/src/ui/clipboard.js +41 -0
  230. package/dist/src/ui/clipboard.js.map +1 -0
  231. package/dist/src/ui/footer.js +19 -0
  232. package/dist/src/ui/footer.js.map +1 -1
  233. package/dist/src/ui/input.js +18 -0
  234. package/dist/src/ui/input.js.map +1 -0
  235. package/dist/src/ui/interaction.js +30 -8
  236. package/dist/src/ui/interaction.js.map +1 -1
  237. package/dist/src/ui/panels/dev.js +60 -0
  238. package/dist/src/ui/panels/dev.js.map +1 -0
  239. package/dist/src/ui/panels/settings.js +15 -1
  240. package/dist/src/ui/panels/settings.js.map +1 -1
  241. package/dist/src/ui/panels/wizard-request-panel.js +356 -0
  242. package/dist/src/ui/panels/wizard-request-panel.js.map +1 -0
  243. package/dist/src/ui/panels/wizard-request.js +251 -0
  244. package/dist/src/ui/panels/wizard-request.js.map +1 -0
  245. package/dist/src/ui/presentation.js +23 -7
  246. package/dist/src/ui/presentation.js.map +1 -1
  247. package/dist/src/ui/run.js +188 -11
  248. package/dist/src/ui/run.js.map +1 -1
  249. package/dist/src/ui/setup/providers.js +17 -1
  250. package/dist/src/ui/setup/providers.js.map +1 -1
  251. package/dist/src/ui/setup/steps.js +18 -6
  252. package/dist/src/ui/setup/steps.js.map +1 -1
  253. package/dist/src/ui/setup/wizard.js +12 -9
  254. package/dist/src/ui/setup/wizard.js.map +1 -1
  255. package/dist/src/ui/startup.js +32 -8
  256. package/dist/src/ui/startup.js.map +1 -1
  257. package/dist/src/ui/update.js +3 -2
  258. package/dist/src/ui/update.js.map +1 -1
  259. package/package.json +4 -4
@@ -0,0 +1,61 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ import importlib.util
5
+ import sys
6
+ from pathlib import Path
7
+ from types import ModuleType
8
+ from typing import Any
9
+
10
+ from .errors import StrandsDevEvalsError
11
+
12
+ _PYTHON_SUFFIX = ".py"
13
+ _PATH_STARTS = (".", "~")
14
+ _PATH_SEPARATORS = ("/", "\\")
15
+
16
+
17
+ def import_file(path: Path) -> ModuleType:
18
+ name = f"_strands_dev_evals_{path.stem}_{abs(hash(str(path)))}"
19
+ spec = importlib.util.spec_from_file_location(name, path)
20
+ if spec is None or spec.loader is None:
21
+ raise StrandsDevEvalsError(f"cannot import {path}: it is not a Python file")
22
+ module = importlib.util.module_from_spec(spec)
23
+ sys.modules[name] = module
24
+ try:
25
+ spec.loader.exec_module(module)
26
+ except BaseException:
27
+ del sys.modules[name]
28
+ raise
29
+ return module
30
+
31
+
32
+ def import_attribute(spec: str) -> Any:
33
+ module_part, _, attribute = spec.rpartition(":")
34
+ if not module_part or not attribute:
35
+ raise StrandsDevEvalsError(f"{spec} is not MODULE:ATTRIBUTE, for example evals.py:Tone")
36
+ try:
37
+ module = _module(module_part)
38
+ except Exception as e:
39
+ raise StrandsDevEvalsError(f"cannot import {spec}: {e}") from e
40
+ if not hasattr(module, attribute):
41
+ raise StrandsDevEvalsError(f"cannot import {spec}: {module_part} has no attribute {attribute}")
42
+ return getattr(module, attribute)
43
+
44
+
45
+ def _module(module_part: str) -> ModuleType:
46
+ if _is_path(module_part):
47
+ return import_file(_python_file(module_part))
48
+ return importlib.import_module(module_part)
49
+
50
+
51
+ def _is_path(module_part: str) -> bool:
52
+ return (
53
+ module_part.endswith(_PYTHON_SUFFIX)
54
+ or module_part.startswith(_PATH_STARTS)
55
+ or any(separator in module_part for separator in _PATH_SEPARATORS)
56
+ )
57
+
58
+
59
+ def _python_file(module_part: str) -> Path:
60
+ path = Path(module_part).expanduser().resolve()
61
+ return path if path.suffix == _PYTHON_SUFFIX else path.with_suffix(_PYTHON_SUFFIX)
@@ -0,0 +1,120 @@
1
+ from __future__ import annotations
2
+
3
+ import copy
4
+ import importlib
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ import strands.models
9
+
10
+ EFFORT_LEVELS = ("auto", "off", "minimal", "low", "medium", "high", "xhigh", "max")
11
+ _SUPPORTED_MODELS = (
12
+ ("BedrockModel", "bedrock", "additional_request_fields"),
13
+ ("AnthropicModel", "anthropic", "params"),
14
+ ("OpenAIResponsesModel", "openai", "params"),
15
+ )
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class ModelEffort:
20
+ model: Any
21
+ config_key: str = ""
22
+ fields_by_level: dict[str, dict[str, Any]] = field(default_factory=dict)
23
+ unavailable: str | None = None
24
+
25
+ @property
26
+ def baseline(self) -> str:
27
+ if self.unavailable is not None:
28
+ return "auto"
29
+ controlled = self._controlled_keys
30
+ current = {key: value for key, value in self._request_fields().items() if key in controlled}
31
+ return next(
32
+ (level for level, fields in self.fields_by_level.items() if level != "auto" and fields == current),
33
+ "auto",
34
+ )
35
+
36
+ def options_for(self, level: str) -> dict[str, Any]:
37
+ if level == "auto":
38
+ return {}
39
+ if level not in self.fields_by_level:
40
+ raise ValueError(f"the agent's model has no reasoning level {level!r}")
41
+ return {"model": self._trial_model(self.fields_by_level[level])}
42
+
43
+ @property
44
+ def _controlled_keys(self) -> set[str]:
45
+ return {key for fields in self.fields_by_level.values() for key in fields}
46
+
47
+ def _request_fields(self) -> dict[str, Any]:
48
+ return self.model.get_config().get(self.config_key) or {}
49
+
50
+ def _trial_model(self, level_fields: dict[str, Any]) -> Any:
51
+ controlled = self._controlled_keys
52
+ kept = {key: value for key, value in self._request_fields().items() if key not in controlled}
53
+ merged = _clamp_thinking_budget({**kept, **level_fields}, self.model.get_config().get("max_tokens"))
54
+ trial = copy.copy(self.model)
55
+ trial.config = dict(self.model.config)
56
+ trial.update_config(**{self.config_key: merged})
57
+ return trial
58
+
59
+
60
+ def read_model_effort(model: Any) -> ModelEffort:
61
+ class_name = type(model).__name__
62
+ supported = _provider_and_config_key(model)
63
+ if supported is None:
64
+ return ModelEffort(
65
+ model,
66
+ unavailable=(
67
+ f"the agent's model is a {class_name} object, and strands dev can set effort only on BedrockModel, "
68
+ "AnthropicModel, and OpenAIResponsesModel objects. Tune instructions instead (the default)."
69
+ ),
70
+ )
71
+ provider, config_key = supported
72
+ model_id = model.get_config().get("model_id")
73
+ if not isinstance(model_id, str):
74
+ return ModelEffort(
75
+ model,
76
+ unavailable=(
77
+ f"the agent's {class_name} has no model id, so strands dev cannot look up its reasoning settings. "
78
+ "Tune instructions instead (the default)."
79
+ ),
80
+ )
81
+ spec = f"{provider}/{model_id}"
82
+ fields_by_level, first_error = _read_fields_by_level(spec, config_key)
83
+ if not fields_by_level:
84
+ return ModelEffort(
85
+ model, unavailable=f"strands dev could not read the reasoning settings for {spec}: {first_error}"
86
+ )
87
+ return ModelEffort(model, config_key, fields_by_level)
88
+
89
+
90
+ def _provider_and_config_key(model: Any) -> tuple[str, str] | None:
91
+ for class_name, provider, config_key in _SUPPORTED_MODELS:
92
+ try:
93
+ model_class = getattr(strands.models, class_name)
94
+ except ImportError:
95
+ continue
96
+ if isinstance(model, model_class):
97
+ return provider, config_key
98
+ return None
99
+
100
+
101
+ def _read_fields_by_level(spec: str, config_key: str) -> tuple[dict[str, dict[str, Any]], Exception | None]:
102
+ resolve_model = importlib.import_module("strands_harness.models").resolve_model
103
+ fields_by_level: dict[str, dict[str, Any]] = {}
104
+ errors: list[Exception] = []
105
+ for level in EFFORT_LEVELS:
106
+ if level == "auto":
107
+ continue
108
+ try:
109
+ fields_by_level[level] = resolve_model(spec, spec, effort=level).get_config().get(config_key) or {}
110
+ except Exception as e:
111
+ errors.append(e)
112
+ return fields_by_level, errors[0] if errors else None
113
+
114
+
115
+ def _clamp_thinking_budget(request_fields: dict[str, Any], max_tokens: Any) -> dict[str, Any]:
116
+ thinking = request_fields.get("thinking")
117
+ if not isinstance(max_tokens, int) or not isinstance(thinking, dict) or "budget_tokens" not in thinking:
118
+ return request_fields
119
+ budget = min(thinking["budget_tokens"], max_tokens - 1)
120
+ return {**request_fields, "thinking": {**thinking, "budget_tokens": budget}}
@@ -0,0 +1,152 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from collections.abc import Callable, Sequence
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ from strands_evals import Case
9
+ from strands_evals.optimization import OneOf, Schedule, ScheduleContext, Search, TextValue, TunableFactory, tunable
10
+
11
+ from .errors import StrandsDevEvalsError
12
+ from .harness import Harness, answer_text, load_harness
13
+ from .model_effort import EFFORT_LEVELS
14
+ from .space import SpaceFile, SpaceVariable, VariableKind, read_space_file
15
+
16
+ SETTINGS = ("instructions", "effort")
17
+ _DEFAULT_SETTINGS = ("instructions",)
18
+ _LEVELS_WITHOUT_REASONING = frozenset({"auto", "off"})
19
+ _TEXT_MIN_SIZE_CAP = 8000
20
+ _INSTRUCTIONS_ABOUT = "the agent's domain instructions, which the harness appends to its own system prompt"
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class OptimizeTask:
25
+ agent: TunableFactory
26
+ rollout: Callable[..., Any]
27
+ search: Search | None
28
+
29
+
30
+ class _BaselineOnly(Schedule):
31
+ name = "baseline_only"
32
+
33
+ def next(self, ctx: ScheduleContext) -> None:
34
+ return None
35
+
36
+
37
+ def optimize_task(
38
+ agent_file: str,
39
+ *,
40
+ experiment_file: str,
41
+ space_file: str | None = None,
42
+ settings: Sequence[str] = _DEFAULT_SETTINGS,
43
+ temporary_typescript_runner: str | None = None,
44
+ custom_evaluators: Sequence[str] = (),
45
+ baseline_only: bool = False,
46
+ ) -> OptimizeTask:
47
+ space = read_space_file(space_file) if space_file is not None else None
48
+ harness = load_harness(
49
+ agent_file,
50
+ experiment_file=experiment_file,
51
+ custom_evaluators=custom_evaluators,
52
+ temporary_typescript_runner=temporary_typescript_runner,
53
+ )
54
+ factory = (
55
+ _space_factory(harness, space)
56
+ if space is not None
57
+ else _settings_factory(harness, tuple(dict.fromkeys(settings)))
58
+ )
59
+ return OptimizeTask(
60
+ agent=factory,
61
+ rollout=rollout,
62
+ search=Search([], schedule=_BaselineOnly()) if baseline_only else None,
63
+ )
64
+
65
+
66
+ async def rollout(agent_factory: Callable[..., Any], case: Case) -> dict[str, Any]:
67
+ agent = agent_factory()
68
+ return {"output": answer_text(await agent.invoke_async(case.input))}
69
+
70
+
71
+ def _text_marker(default: str, about: str) -> TextValue:
72
+ size_cap = max(_TEXT_MIN_SIZE_CAP, 2 * len(default))
73
+ return TextValue(default=default, size_cap=size_cap, edit_instructions=about or None)
74
+
75
+
76
+ def _check_instructions(harness: Harness) -> None:
77
+ if "system_prompt" in harness.options:
78
+ raise StrandsDevEvalsError(
79
+ "instructions cannot be tuned: the agent passes a full system prompt, which replaces its instructions. "
80
+ "Move that text into instructions, or tune another setting such as effort."
81
+ )
82
+
83
+
84
+ def _instructions_marker(harness: Harness) -> TextValue:
85
+ _check_instructions(harness)
86
+ return _text_marker(harness.options.get("instructions") or "", _INSTRUCTIONS_ABOUT)
87
+
88
+
89
+ def _effort_marker(harness: Harness) -> OneOf:
90
+ reason = harness.effort_unavailable()
91
+ if reason is not None:
92
+ raise StrandsDevEvalsError(f"effort cannot be tuned: {reason}")
93
+ baseline = harness.effort_baseline()
94
+ candidates = [level for level in EFFORT_LEVELS if level != "auto" or baseline == "auto"]
95
+ levels = [level for level in candidates if level == baseline or harness.builds_with(effort=level)]
96
+ if len(levels) < 2 or all(level in _LEVELS_WITHOUT_REASONING for level in levels):
97
+ raise StrandsDevEvalsError(
98
+ f"effort cannot be tuned: the agent's model accepts no reasoning levels besides {levels}. "
99
+ "Tune instructions instead."
100
+ )
101
+ return OneOf(*levels, default=baseline)
102
+
103
+
104
+ _SETTING_MARKERS: dict[str, Callable[[Harness], Any]] = {
105
+ "instructions": _instructions_marker,
106
+ "effort": _effort_marker,
107
+ }
108
+
109
+
110
+ def _settings_factory(harness: Harness, settings: tuple[str, ...]) -> TunableFactory:
111
+ unknown = [setting for setting in settings if setting not in _SETTING_MARKERS]
112
+ if unknown or not settings:
113
+ raise StrandsDevEvalsError(f"settings must name one or more of {', '.join(SETTINGS)}, got {list(settings)}")
114
+ markers = {name: _SETTING_MARKERS[name](harness) for name in settings}
115
+
116
+ def create_agent(**values: Any) -> Any:
117
+ return harness.build(values)
118
+
119
+ return tunable(create_agent, inject=markers)
120
+
121
+
122
+ def _check_variable(harness: Harness, variable: SpaceVariable) -> None:
123
+ if variable.option == "instructions":
124
+ _check_instructions(harness)
125
+ if variable.item is None:
126
+ return
127
+ problem = harness.switch_problem(variable.option, variable.item)
128
+ if problem:
129
+ raise StrandsDevEvalsError(
130
+ f"the space variable {variable.key} cannot leave out {json.dumps(variable.item)} of {variable.option}: "
131
+ f"{problem}. Make the space file again from the agent file as it is now, then try again."
132
+ )
133
+
134
+
135
+ def _variable_marker(variable: SpaceVariable, options: dict[str, Any]) -> Any:
136
+ if variable.kind is VariableKind.TEXT:
137
+ return _text_marker(variable.text_default(options), variable.about)
138
+ if variable.kind is VariableKind.CHOICE:
139
+ return OneOf(*variable.values, default=variable.default)
140
+ return OneOf(True, False, default=variable.default)
141
+
142
+
143
+ def _space_factory(harness: Harness, space: SpaceFile) -> TunableFactory:
144
+ for variable in space.variables:
145
+ _check_variable(harness, variable)
146
+ markers = {variable.key: _variable_marker(variable, harness.options) for variable in space.variables}
147
+
148
+ def create_agent(**values: Any) -> Any:
149
+ settings, without = space.overrides(values)
150
+ return harness.build(settings, without)
151
+
152
+ return tunable(create_agent, inject=markers)
@@ -0,0 +1,55 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Callable, Sequence
4
+ from dataclasses import dataclass
5
+ from typing import Any
6
+
7
+ from strands_evals import Case
8
+ from strands_evals.cli._agent_task import synthesize_task_function
9
+
10
+ from .harness import Harness, answer_text, load_harness
11
+ from .temporary_typescript import TemporaryTypescriptHarness
12
+
13
+ RunTask = Callable[[Case], Any]
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class _ZeroArgumentFactory:
18
+ obj: Callable[[], Any]
19
+ spec: str
20
+ kind: str = "callable_no_arg"
21
+
22
+
23
+ def run_task(
24
+ agent_file: str,
25
+ *,
26
+ experiment_file: str,
27
+ custom_evaluators: Sequence[str] = (),
28
+ temporary_typescript_runner: str | None = None,
29
+ ) -> RunTask:
30
+ harness = load_harness(
31
+ agent_file,
32
+ experiment_file=experiment_file,
33
+ custom_evaluators=custom_evaluators,
34
+ temporary_typescript_runner=temporary_typescript_runner,
35
+ )
36
+ if isinstance(harness, TemporaryTypescriptHarness):
37
+ return _temporary_typescript_task(harness)
38
+ return _traced_task(harness, agent_file)
39
+
40
+
41
+ def _traced_task(harness: Harness, agent_file: str) -> RunTask:
42
+ traced = synthesize_task_function(_ZeroArgumentFactory(lambda: harness.build({}), agent_file))
43
+
44
+ def run_case(case: Case) -> dict[str, Any]:
45
+ result = traced(case)
46
+ return {**result, "output": answer_text(result["output"])}
47
+
48
+ return run_case
49
+
50
+
51
+ def _temporary_typescript_task(harness: TemporaryTypescriptHarness) -> RunTask:
52
+ async def run_case(case: Case) -> dict[str, Any]:
53
+ return {"output": answer_text(await harness.build({}).invoke_async(case.input))}
54
+
55
+ return run_case
@@ -0,0 +1,212 @@
1
+ from __future__ import annotations
2
+
3
+ import importlib
4
+ import json
5
+ import re
6
+ from dataclasses import dataclass
7
+ from enum import Enum
8
+ from pathlib import Path
9
+ from typing import Any, TypeGuard
10
+
11
+ from .errors import StrandsDevEvalsError
12
+
13
+ Without = dict[str, list[dict[str, Any]]]
14
+
15
+ _KEY_PATTERN = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
16
+ _ITEM_FIELDS = ("index", "key", "name")
17
+ _SCALAR_TYPES = (str, int, float, bool, type(None))
18
+ _NAME_ATTRIBUTES = ("tool_name", "name", "__name__")
19
+ # A map of off switches edits the harness's own default set, so web_search stays off where the model has none.
20
+ _DEFAULT_SET_OPTIONS = frozenset({"builtin_tools"})
21
+
22
+
23
+ class VariableKind(str, Enum):
24
+ TEXT = "text"
25
+ CHOICE = "choice"
26
+ SWITCH = "switch"
27
+
28
+
29
+ class _SpaceProblem(ValueError):
30
+ pass
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class SpaceVariable:
35
+ key: str
36
+ kind: VariableKind
37
+ option: str
38
+ default: Any
39
+ values: tuple[Any, ...] = ()
40
+ about: str = ""
41
+ item: dict[str, Any] | None = None
42
+
43
+ def text_default(self, options: dict[str, Any]) -> str:
44
+ text = self.default if self.default is not None else (options.get(self.option) or "")
45
+ if not isinstance(text, str):
46
+ raise StrandsDevEvalsError(
47
+ f"the space variable {self.key} is text, but the agent's {self.option} is not text "
48
+ f"({type(text).__name__}). Give the variable a default, or make it a choice, then try again."
49
+ )
50
+ return text
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class SpaceFile:
55
+ variables: tuple[SpaceVariable, ...]
56
+
57
+ def overrides(self, values: dict[str, Any]) -> tuple[dict[str, Any], Without]:
58
+ settings = {variable.option: values[variable.key] for variable in self.variables if variable.item is None}
59
+ without: Without = {}
60
+ for variable in self.variables:
61
+ if variable.item is not None and not values[variable.key]:
62
+ without.setdefault(variable.option, []).append(variable.item)
63
+ return settings, without
64
+
65
+
66
+ def read_space_file(path_text: str) -> SpaceFile:
67
+ try:
68
+ return _space(_document(path_text))
69
+ except _SpaceProblem as e:
70
+ raise StrandsDevEvalsError(f"{path_text} is not a usable space file: {e}. Fix the file, then try again.") from e
71
+
72
+
73
+ def without_items(collection: Any, items: list[dict[str, Any]]) -> Any:
74
+ if isinstance(collection, dict):
75
+ keys = {item["key"] for item in items}
76
+ return {key: value for key, value in collection.items() if key not in keys}
77
+ indexes = {item["index"] for item in items if "index" in item}
78
+ names = {item["name"] for item in items if "name" in item}
79
+ return [entry for index, entry in enumerate(collection) if index not in indexes and not _is_named(entry, names)]
80
+
81
+
82
+ def harness_default(option: str) -> Any:
83
+ """The strands-harness default of an option, from its DEFAULT_HARNESS_AGENT_CONFIG."""
84
+ config = importlib.import_module("strands_harness").DEFAULT_HARNESS_AGENT_CONFIG
85
+ return config.get(re.sub(r"_([a-z])", lambda match: match.group(1).upper(), option))
86
+
87
+
88
+ def default_without(option: str, items: list[dict[str, Any]]) -> Any:
89
+ """The harness default of an option that the agent leaves out, without the items that are off."""
90
+ if option in _DEFAULT_SET_OPTIONS:
91
+ return {item["name"]: False for item in items if "name" in item}
92
+ return without_items(list(harness_default(option) or []), items)
93
+
94
+
95
+ def item_problem(options: dict[str, Any], option: str, item: dict[str, Any]) -> str | None:
96
+ collection = options[option] if option in options else harness_default(option)
97
+ owner = f"the agent's {option}" if option in options else f"the harness default {option}"
98
+ container = dict if "key" in item else list
99
+ if collection is None:
100
+ return f"the agent passes no {option}, and the harness has none by default"
101
+ if isinstance(collection, tuple):
102
+ collection = list(collection)
103
+ if not isinstance(collection, container):
104
+ return f"{owner} is a {type(collection).__name__}, not a {container.__name__}"
105
+ if len(without_items(collection, [item])) == len(collection):
106
+ return f"{owner} has no such item"
107
+ return None
108
+
109
+
110
+ def _is_named(entry: Any, names: set[str]) -> bool:
111
+ identifiers = (entry, *(getattr(entry, attribute, None) for attribute in _NAME_ATTRIBUTES))
112
+ return any(isinstance(identifier, str) and identifier in names for identifier in identifiers)
113
+
114
+
115
+ def _document(path_text: str) -> Any:
116
+ try:
117
+ return json.loads(Path(path_text).expanduser().read_text(encoding="utf-8"))
118
+ except (OSError, ValueError) as e:
119
+ raise _SpaceProblem(f"it cannot be read as JSON ({e})") from e
120
+
121
+
122
+ def _space(document: Any) -> SpaceFile:
123
+ entries = document.get("variables") if isinstance(document, dict) else None
124
+ if not isinstance(entries, list):
125
+ raise _SpaceProblem('it must be a JSON object with a "variables" list')
126
+ variables = tuple(_variable(position, entry) for position, entry in enumerate(entries, start=1))
127
+ _check_keys(variables)
128
+ _check_options(variables)
129
+ return SpaceFile(variables)
130
+
131
+
132
+ def _variable(position: int, entry: Any) -> SpaceVariable:
133
+ if not isinstance(entry, dict):
134
+ raise _SpaceProblem(f"variable {position} is not a JSON object")
135
+ key = entry.get("key")
136
+ if not isinstance(key, str) or not _KEY_PATTERN.fullmatch(key):
137
+ raise _SpaceProblem(
138
+ f"variable {position} has the key {json.dumps(key)}, but a key must match [A-Za-z_][A-Za-z0-9_]*"
139
+ )
140
+ option = entry.get("option")
141
+ if not isinstance(option, str) or not option:
142
+ raise _SpaceProblem(f"variable {key} needs an option: the name of the createHarness option it changes")
143
+ kind = entry.get("kind")
144
+ if kind == VariableKind.TEXT:
145
+ return _text(key, option, entry)
146
+ if kind == VariableKind.CHOICE:
147
+ return _choice(key, option, entry)
148
+ if kind == VariableKind.SWITCH:
149
+ return _switch(key, option, entry)
150
+ raise _SpaceProblem(f"variable {key} has the kind {json.dumps(kind)}, but a kind is text, choice or switch")
151
+
152
+
153
+ def _text(key: str, option: str, entry: dict[str, Any]) -> SpaceVariable:
154
+ default, about = entry.get("default"), entry.get("about")
155
+ if not isinstance(default, (str, type(None))) or not isinstance(about, (str, type(None))):
156
+ raise _SpaceProblem(f"text {key} needs a default and an about that are strings, if it has them")
157
+ return SpaceVariable(key, VariableKind.TEXT, option, default, about=about or "")
158
+
159
+
160
+ def _choice(key: str, option: str, entry: dict[str, Any]) -> SpaceVariable:
161
+ values, default = entry.get("values"), entry.get("default")
162
+ if not isinstance(values, list) or not all(isinstance(value, _SCALAR_TYPES) for value in values):
163
+ raise _SpaceProblem(f"choice {key} needs values: a list of strings, numbers, booleans or nulls")
164
+ distinct = dict.fromkeys(map(_identity, values))
165
+ if len(distinct) < 2:
166
+ raise _SpaceProblem(f"choice {key} needs at least two distinct values")
167
+ if "default" not in entry or not isinstance(default, _SCALAR_TYPES) or _identity(default) not in distinct:
168
+ raise _SpaceProblem(f"choice {key} needs a default that is one of its values")
169
+ choices = tuple(value for _, value in distinct)
170
+ return SpaceVariable(key, VariableKind.CHOICE, option, default, values=choices)
171
+
172
+
173
+ def _switch(key: str, option: str, entry: dict[str, Any]) -> SpaceVariable:
174
+ default, item = entry.get("default"), entry.get("item")
175
+ if not isinstance(default, bool):
176
+ raise _SpaceProblem(f"switch {key} needs a default of true or false")
177
+ if not _is_item(item):
178
+ raise _SpaceProblem(f'switch {key} needs an item: {{"index": N}}, {{"key": "NAME"}} or {{"name": "NAME"}}')
179
+ return SpaceVariable(key, VariableKind.SWITCH, option, default, item=dict(item))
180
+
181
+
182
+ def _identity(value: Any) -> tuple[bool, Any]:
183
+ return isinstance(value, bool), value
184
+
185
+
186
+ def _is_item(item: Any) -> TypeGuard[dict[str, Any]]:
187
+ fields = [field for field in _ITEM_FIELDS if field in item] if isinstance(item, dict) else []
188
+ if len(fields) != 1:
189
+ return False
190
+ value = item[fields[0]]
191
+ if fields[0] == "index":
192
+ return isinstance(value, int) and not isinstance(value, bool) and value >= 0
193
+ return isinstance(value, str)
194
+
195
+
196
+ def _check_keys(variables: tuple[SpaceVariable, ...]) -> None:
197
+ seen: set[str] = set()
198
+ for variable in variables:
199
+ if variable.key in seen:
200
+ raise _SpaceProblem(f"two variables have the key {variable.key}; give each variable its own key")
201
+ seen.add(variable.key)
202
+
203
+
204
+ def _check_options(variables: tuple[SpaceVariable, ...]) -> None:
205
+ owners: dict[str, SpaceVariable] = {}
206
+ for variable in variables:
207
+ owner = owners.setdefault(variable.option, variable)
208
+ if owner is not variable and (owner.item is None or variable.item is None):
209
+ raise _SpaceProblem(
210
+ f"variables {owner.key} and {variable.key} both change {variable.option}; "
211
+ "only switches can share an option"
212
+ )