@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,941 @@
1
+ import { join } from 'node:path';
2
+ import { errorMessage } from '../../../terminal/text.js';
3
+ import { AUTO_OPTIMIZE_MAX_TURNS, autoOptimizeCadence } from '../../../config/settings.js';
4
+ import { STRANDS_EVALS_OPTIMIZE_SKILL, STRANDS_EVALS_SKILL } from '../package.js';
5
+ import { isGenerating } from '../model.js';
6
+ import { uiTools } from './ui-tools.js';
7
+ import { evalsWorkflowSkills } from './workflow-skills.js';
8
+ import { readEvalsExperimentFile } from '../runs/experiment.js';
9
+ import { plural } from '../host.js';
10
+ import { BACKGROUND_COMMANDS, generateFlagSettings, optimizeFlagSettings, runFlagCases, } from './background-flags.js';
11
+ import { checkEvalsObjective, EVALS_USAGE_METRICS, evalsObjectiveFromRequest } from '../tuning/objective.js';
12
+ import { isEvalsBudgetValue, EVALS_BUDGET_MINIMUMS, EVALS_DECISION_CHOICES, } from '../tuning/plan.js';
13
+ import { answerOptimizeReview, applyOptimizeEdits, showOptimizeReview, } from '../sessions/review-run.js';
14
+ import { EVALS_RUN_PHASES, evalsEditsAwaitingAnswer } from '../sessions/optimize-session.js';
15
+ import {} from '../sessions/sessions.js';
16
+ const TEXT_LIMIT = 600;
17
+ const EDIT_LIMIT = 4000;
18
+ const INSTRUCTIONS = `For experiments, evaluations, and test cases, activate the strands-evals skill; to tune this agent against an experiment, activate the optimize skill; to run any strands-evals command, follow the background-evals skill. The developer can also type /experiment or /optimize.
19
+
20
+ Runs cost money. Name the scope in chat and end the turn; start a run only after the developer approves it in a later turn. Being asked to run, test, or improve something is not that approval. In /experiment, picking Run, or the experiments to run, on screen is the approval.
21
+
22
+ When an optimization run finishes, its edits appear on the developer's screen as a diff, and they apply or leave each edit there, unless auto-accept writes them. Do not print the edits or ask in chat which ones to apply; strands_dev_review_optimization puts a closed diff back on screen. A message that comes with a <strands_dev_screen> block was written while that diff was on their screen: when it answers the diff, such as "approve this" or "leave it", pick for them with strands_dev_answer_review as the block says, and do not ask them to confirm. Call strands_dev_apply_optimization only for edits the developer names in chat when no diff of them is on screen. strands_dev_status gives each edit's answer: one they left as it is has been answered, so a bare "yes" never applies it.
23
+
24
+ Optimization can also run by itself. Auto-optimize every N turns makes an experiment from the chats of the developer with this agent every N chat turns and tunes the agent on it, in the background and outside this chat: you take no part in it, and a notice and the line below the chat input show it; Auto-accept optimization results writes the edits of a finished run without showing them. Both are in /settings under Strands dev workspace, and strands_dev_auto_optimize reads and sets them, so do not search files for how they work. When the developer asks for it, such as "optimize every 20 turns from my history", say what it does and that every automatic run is paid. A question whether you can is not yet a request: set it once they say to.
25
+
26
+ Answer what was asked from tool output of this turn: call strands_dev_status again whenever the question is what exists, because runs and files change between turns. Ask the developer to choose or enter numbers with the strands_dev_ UI tools, and ask a free-form question in chat. When a question comes back interrupted, the developer wrote to you instead of answering: reply to that message and end the turn, and never take its unsubmitted draft as the answer. Never make up the evals UI address; pass on only what strands_dev_open_evals_ui returns, as a markdown link with a short label such as [open the run](url).`;
27
+ const reply = (value) => JSON.stringify(value, null, 2);
28
+ const clip = (text, limit = TEXT_LIMIT) => text === undefined || text.length <= limit
29
+ ? text
30
+ : `${text.slice(0, limit)}… [${text.length - limit} more characters]`;
31
+ const until = (store, pick) => new Promise((resolve) => {
32
+ const found = pick(store.snapshot());
33
+ if (found !== undefined) {
34
+ resolve(found);
35
+ return;
36
+ }
37
+ const stop = store.subscribe(() => {
38
+ const next = pick(store.snapshot());
39
+ if (next === undefined)
40
+ return;
41
+ stop();
42
+ resolve(next);
43
+ });
44
+ });
45
+ const text = (input, key) => {
46
+ const value = input[key];
47
+ if (value === undefined || value === null)
48
+ return undefined;
49
+ if (typeof value !== 'string')
50
+ throw new Error(`${key} must be text.`);
51
+ return value.trim();
52
+ };
53
+ const requiredText = (input, key) => {
54
+ const value = text(input, key);
55
+ if (!value)
56
+ throw new Error(`${key} is required.`);
57
+ return value;
58
+ };
59
+ const flag = (input, key) => {
60
+ const value = input[key];
61
+ if (value === undefined || value === null)
62
+ return undefined;
63
+ if (typeof value !== 'boolean')
64
+ throw new Error(`${key} must be true or false.`);
65
+ return value;
66
+ };
67
+ const whole = (input, key, min, max) => {
68
+ const value = input[key];
69
+ if (value === undefined || value === null)
70
+ return undefined;
71
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < min || value > max)
72
+ throw new Error(`${key} must be a whole number from ${min} to ${max}.`);
73
+ return value;
74
+ };
75
+ const defined = (value) => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
76
+ const findExperiment = async (sessions, name) => {
77
+ const saved = await sessions().experiments.reload();
78
+ const found = saved.find((experiment) => experiment.name === name) ??
79
+ saved.find((experiment) => experiment.name.toLowerCase() === name.toLowerCase());
80
+ if (found)
81
+ return found;
82
+ const names = saved.map((experiment) => experiment.name).join(', ');
83
+ throw new Error(names
84
+ ? `There is no experiment named ${name}. Saved experiments: ${names}.`
85
+ : `There is no experiment named ${name}, and no experiment is saved yet. Create one first.`);
86
+ };
87
+ const pageOf = (items, input) => {
88
+ const offset = whole(input, 'offset', 0, Number.MAX_SAFE_INTEGER) ?? 0;
89
+ const limit = whole(input, 'limit', 1, 50) ?? 10;
90
+ const next = offset + limit;
91
+ return { offset, ...(next < items.length ? { nextOffset: next } : {}), items: items.slice(offset, next) };
92
+ };
93
+ const PAGED_EXPERIMENT = {
94
+ type: 'object',
95
+ properties: {
96
+ experiment: { type: 'string' },
97
+ offset: { type: 'integer', minimum: 0, description: 'Zero-based first case. Default 0.' },
98
+ limit: { type: 'integer', minimum: 1, maximum: 50, description: 'Cases to return. Default 10.' },
99
+ },
100
+ required: ['experiment'],
101
+ additionalProperties: false,
102
+ };
103
+ const readExperimentTool = (sessions) => ({
104
+ name: 'strands_dev_read_experiment',
105
+ readOnly: true,
106
+ description: 'Read a saved experiment, its evaluator definitions, and a page of cases. Does not run the agent or generate cases.',
107
+ inputSchema: PAGED_EXPERIMENT,
108
+ run: async (input) => {
109
+ const selected = await findExperiment(sessions, requiredText(input, 'experiment'));
110
+ const { experiment, raw } = await readEvalsExperimentFile(selected.path);
111
+ const page = pageOf(raw.cases, input);
112
+ return reply({
113
+ name: experiment.name,
114
+ file: experiment.path,
115
+ total: raw.cases.length,
116
+ evaluators: raw.evaluators ?? [],
117
+ offset: page.offset,
118
+ nextOffset: page.nextOffset,
119
+ cases: page.items,
120
+ });
121
+ },
122
+ });
123
+ const evaluationResultsTool = (sessions) => ({
124
+ name: 'strands_dev_evaluation_results',
125
+ readOnly: true,
126
+ description: 'Inspect existing progress or the last evaluation result, including inputs, outputs, and evaluator verdicts. Does not rerun evaluations.',
127
+ inputSchema: PAGED_EXPERIMENT,
128
+ run: async (input) => {
129
+ const experiment = await findExperiment(sessions, requiredText(input, 'experiment'));
130
+ const { evaluate } = sessions();
131
+ await evaluate.show();
132
+ const run = runOf(evaluate, experiment.path);
133
+ if (!run)
134
+ return reply({ experiment: experiment.name, status: 'not_run' });
135
+ if (run.status !== 'done')
136
+ return reply({ experiment: experiment.name, ...runStatus(run) });
137
+ const page = pageOf(run.results.cases, input);
138
+ return reply({
139
+ ...runStatus(run),
140
+ experiment: experiment.name,
141
+ seconds: Math.round(run.results.seconds),
142
+ offset: page.offset,
143
+ nextOffset: page.nextOffset,
144
+ cases: page.items,
145
+ });
146
+ },
147
+ });
148
+ const runOf = (evaluate, path) => evaluate.snapshot().runs.find(({ experiment }) => experiment.path === path)?.run;
149
+ const runStatus = (run) => {
150
+ if (!run)
151
+ return undefined;
152
+ if (run.status === 'running')
153
+ return { status: 'running', done: run.done, cases: run.cases };
154
+ if (run.status === 'failed')
155
+ return { status: 'failed', message: run.message };
156
+ const { cases, overall, report } = run.results;
157
+ return {
158
+ status: 'done',
159
+ passed: cases.filter((item) => item.passed).length,
160
+ total: cases.length,
161
+ score: overall,
162
+ report,
163
+ };
164
+ };
165
+ const generationStatus = ({ name, phase, made, failed, total, error, log }) => defined({ name, phase, made, failed, total, error: error?.summary, log });
166
+ /**
167
+ * What the developer answered for an edit, on screen or through the agent. An edit they were never offered has no
168
+ * answer, and neither has one that auto-accept or an older apply wrote without asking.
169
+ */
170
+ const answerOf = (edit, { auto, applied, reviewed }) => {
171
+ if (edit.unavailable !== undefined || auto)
172
+ return undefined;
173
+ if (!edit.decided)
174
+ return applied || reviewed ? undefined : 'waiting';
175
+ return edit.accepted ? 'apply' : 'leave as it is';
176
+ };
177
+ const reviewReport = (review) => {
178
+ const { run, baseline, best, measuredOn, edits, applied, applyError, auto } = review;
179
+ return defined({
180
+ run,
181
+ baseline,
182
+ best,
183
+ measuredOn,
184
+ edits: edits.map((edit, index) => defined({
185
+ index,
186
+ knob: edit.knob,
187
+ target: edit.target,
188
+ unavailable: edit.unavailable,
189
+ answer: answerOf(edit, review),
190
+ before: clip(edit.before, EDIT_LIMIT),
191
+ after: clip(edit.after, EDIT_LIMIT),
192
+ newInCall: edit.added,
193
+ })),
194
+ applied,
195
+ applyError,
196
+ // Written by the auto-accept setting as the run ended: the developer saw no diff of these edits.
197
+ autoApplied: auto ? true : undefined,
198
+ });
199
+ };
200
+ const AUTO_PLAN = 'Auto-accept optimization results is on in the settings of this workspace: when this run finishes, strands dev writes its edits to ' +
201
+ 'the agent source without showing them. Say so in the review the developer approves before the run starts. A ' +
202
+ 'run they stop early is not applied. They turn the setting off in /settings, under Strands dev workspace.';
203
+ const WAITING_NEXT = "for the developer's yes or no. They answer on their screen, not in chat. The diff may not be showing: the run is " +
204
+ 'on the status line under the chat input, where clicking it opens the diff, and strands_dev_review_optimization ' +
205
+ 'puts it on their screen. Do not say the diff is on screen unless that call just put it there.';
206
+ const LEFT_NEXT = 'That is their answer: apply such an edit only when they ask for that change in so many words, never on a bare ' +
207
+ '"yes" or "ok".';
208
+ /**
209
+ * Where a review stands with the developer, said so the agent neither calls a closed diff "on screen" nor takes an
210
+ * edit they left as it is for one that still waits.
211
+ */
212
+ const answersReport = (review) => {
213
+ if (review.applied)
214
+ return {};
215
+ const waiting = evalsEditsAwaitingAnswer(review);
216
+ const left = review.edits.filter((edit) => answerOf(edit, review) === 'leave as it is').length;
217
+ const next = [
218
+ ...(waiting > 0
219
+ ? [
220
+ `${waiting === 1 ? '1 edit of this run still waits' : `${waiting} edits of this run still wait`} ${WAITING_NEXT}`,
221
+ ]
222
+ : []),
223
+ ...(left > 0 ? [`The developer left ${plural(left, 'edit')} of this run as it is. ${LEFT_NEXT}`] : []),
224
+ ];
225
+ return defined({
226
+ awaitingAnswer: waiting > 0 ? waiting : undefined,
227
+ next: next.length > 0 ? next.join(' ') : undefined,
228
+ });
229
+ };
230
+ const optimizationStatus = (state) => defined({
231
+ ...pageStatus(state),
232
+ runs: state.runs?.length
233
+ ? state.runs.map(({ experiment, state: run }) => ({ experiment, ...pageStatus(run) }))
234
+ : undefined,
235
+ });
236
+ const pageStatus = (state) => {
237
+ switch (state.step) {
238
+ case 'pick':
239
+ return { step: 'idle' };
240
+ case 'setup':
241
+ return { step: 'setup', experiment: state.plan.experiment.name };
242
+ case 'running':
243
+ return defined({
244
+ step: 'running',
245
+ run: state.progress.run,
246
+ baseline: state.progress.baseline,
247
+ best: state.progress.best,
248
+ tried: state.progress.tried,
249
+ planned: state.progress.planned,
250
+ // Every version tried is not the end of the run: the finalists and the test are checked after the search.
251
+ phase: state.progress.phase ? EVALS_RUN_PHASES[state.progress.phase] : undefined,
252
+ rollouts: state.progress.rollouts,
253
+ });
254
+ case 'review':
255
+ return { step: 'review', ...reviewReport(state.review), ...answersReport(state.review) };
256
+ case 'cancelled':
257
+ return defined({ step: 'cancelled', experiment: state.experiment, run: state.run });
258
+ case 'failed':
259
+ return { step: 'failed', message: state.message };
260
+ }
261
+ };
262
+ const EVALS_UI_OPENING = 'strands_dev_open_evals_ui opens an experiment, a report, or an optimization run.';
263
+ const evalsUiStatus = (ui) => {
264
+ const { status, detail } = ui.snapshot();
265
+ return defined({ status, detail, open: status === 'ready' ? EVALS_UI_OPENING : undefined });
266
+ };
267
+ const statusTool = (sessions, history) => ({
268
+ name: 'strands_dev_status',
269
+ readOnly: true,
270
+ description: 'Show the strands dev workspace: the saved experiments with their last evaluation result, the generations that run or failed, ' +
271
+ 'the optimization state, and the suggested settings for a new experiment with the number of past chats. ' +
272
+ 'Call it again in every turn that asks what exists, including a repeated question. ' +
273
+ 'An answer from an earlier turn is stale, because files and runs change in between.',
274
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
275
+ run: async () => {
276
+ const { experiments, evaluate, optimize, ui } = sessions();
277
+ await evaluate.show();
278
+ const [saved, pastChats] = await Promise.all([experiments.reload(), history.pastChats()]);
279
+ const { folder, generations } = experiments.snapshot();
280
+ return reply({
281
+ experimentsFolder: folder,
282
+ experiments: saved.map(({ name, caseCount, path }) => defined({
283
+ name,
284
+ cases: caseCount,
285
+ file: path,
286
+ evalsUi: ui.link?.({ view: 'experiment', experiment: path }),
287
+ lastTest: runStatus(runOf(evaluate, path)),
288
+ })),
289
+ generations: generations.map(generationStatus),
290
+ optimization: optimizationStatus(optimize.snapshot()),
291
+ fileChanges: sessions().fileChanges(),
292
+ evalsUi: evalsUiStatus(ui),
293
+ newExperiment: {
294
+ cases: experiments.suggested().cases,
295
+ pastChats,
296
+ agentContext: experiments.agentSummary(),
297
+ },
298
+ });
299
+ },
300
+ });
301
+ const sessionConverterTool = (history) => ({
302
+ name: 'strands_dev_session_converter',
303
+ description: 'Load the newest session-converter skill from strands-agents/evals main, with the strands dev rules for it. ' +
304
+ 'Use it to build an experiment from past chats or traces instead of from a goal. ' +
305
+ 'It downloads the skill from GitHub, and the first call can take a minute while strands dev prepares the evals environment.',
306
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
307
+ run: () => history.converter(),
308
+ });
309
+ const AUTO_OPTIMIZE_TURNS = `a whole number from 0 to ${AUTO_OPTIMIZE_MAX_TURNS}`;
310
+ const AUTO_OPTIMIZE_ON = 'Every that many chat turns, strands dev works in the background, outside this chat: an agent in a process of ' +
311
+ 'its own makes an experiment from the chats of the developer with this agent, and strands dev then starts an ' +
312
+ 'optimization on it with the defaults of its plan. Nobody is asked, and you are sent nothing and start nothing. ' +
313
+ 'Each one is a paid run. A new everyTurns starts the count at 0 after the turn that set it.';
314
+ const autoOptimizeReport = async (sessions) => {
315
+ const { everyTurns, turnsSince, building, log } = await sessions().auto.status();
316
+ const accept = sessions().settings()?.autoAcceptOptimizationResults ?? false;
317
+ return {
318
+ autoOptimize: everyTurns === 0
319
+ ? { everyTurns: 0, state: 'off: an optimization starts only when the developer asks for one' }
320
+ : {
321
+ everyTurns,
322
+ turnsSinceTheLastOne: turnsSince,
323
+ state: AUTO_OPTIMIZE_ON,
324
+ ...(building
325
+ ? { now: `The background agent is making the experiment ${building} from the chats. Its log: ${log}` }
326
+ : {}),
327
+ },
328
+ autoAcceptOptimizationResults: accept
329
+ ? 'on: the edits of a finished run are written to the agent source without a diff to answer'
330
+ : 'off: the edits of a finished run show as a diff, and the developer applies or leaves each one',
331
+ choices: { everyTurns: AUTO_OPTIMIZE_TURNS },
332
+ where: 'Both are in /settings, under Strands dev workspace.',
333
+ };
334
+ };
335
+ const autoOptimizeTool = (sessions) => ({
336
+ name: 'strands_dev_auto_optimize',
337
+ description: 'Read or change the two settings that make optimization automatic in this workspace. everyTurns starts an ' +
338
+ 'optimization by itself every that many chat turns, from an experiment made of the chats of the developer with ' +
339
+ 'this agent: what they mean by "optimize every 20 turns from my history". acceptResults writes the edits of a ' +
340
+ 'finished run to the agent source without showing them. With no input it reads both. Change one only when the ' +
341
+ 'developer asks for that change, after you said that each automatic run is paid.',
342
+ inputSchema: {
343
+ type: 'object',
344
+ properties: {
345
+ everyTurns: {
346
+ type: 'integer',
347
+ minimum: 0,
348
+ maximum: AUTO_OPTIMIZE_MAX_TURNS,
349
+ description: 'How many chat turns pass between the automatic optimizations. 0 turns them off.',
350
+ },
351
+ acceptResults: {
352
+ type: 'boolean',
353
+ description: 'Whether the edits of a finished run are written without a diff to answer.',
354
+ },
355
+ },
356
+ additionalProperties: false,
357
+ },
358
+ run: async (input) => {
359
+ const every = input.everyTurns;
360
+ const cadence = autoOptimizeCadence(every);
361
+ if (every !== undefined && every !== null && cadence === undefined)
362
+ throw new Error(`everyTurns must be ${AUTO_OPTIMIZE_TURNS}.`);
363
+ const accept = flag(input, 'acceptResults');
364
+ if (cadence !== undefined || accept !== undefined)
365
+ await sessions().setSettings({
366
+ ...(cadence === undefined ? {} : { autoOptimize: cadence }),
367
+ ...(accept === undefined ? {} : { autoAcceptOptimizationResults: accept }),
368
+ });
369
+ const stopped = await sessions().auto.settingChanged();
370
+ return reply({
371
+ ...(await autoOptimizeReport(sessions)),
372
+ ...(stopped
373
+ ? {
374
+ stopped: `The background agent that was making ${stopped} has stopped, and no optimization starts from it.`,
375
+ }
376
+ : {}),
377
+ });
378
+ },
379
+ });
380
+ const textList = (input, field) => {
381
+ const value = input[field];
382
+ if (value === undefined || value === null)
383
+ return undefined;
384
+ if (!Array.isArray(value) || value.some((item) => typeof item !== 'string' || !item))
385
+ throw new Error(`${field} must be a list of names.`);
386
+ return value;
387
+ };
388
+ const tunedKnobs = (knobs, tune) => {
389
+ const unknown = tune.filter((key) => !knobs.some((knob) => knob.key === key && !knob.unavailable));
390
+ if (unknown.length === 0)
391
+ return;
392
+ const available = knobs.filter((knob) => !knob.unavailable).map((knob) => knob.key);
393
+ throw new Error(`This agent cannot tune ${unknown.join(', ')}. It can tune ${available.join(', ')}.`);
394
+ };
395
+ const plannedSetup = async (sessions, experiment) => {
396
+ const { optimize } = sessions();
397
+ optimize.reset();
398
+ optimize.plan(experiment);
399
+ const planned = await until(optimize, (state) => state.step === 'setup' || state.step === 'failed' ? state : undefined);
400
+ if (planned.step === 'failed')
401
+ throw new Error(planned.message);
402
+ return planned.plan;
403
+ };
404
+ const planTool = (sessions) => ({
405
+ name: 'strands_dev_optimization_plan',
406
+ description: 'Read what an optimization of one experiment could tune, and what it would cost, without starting anything. ' +
407
+ 'Call it before you ask the developer to set up a run, so the knobs, the choices, and the estimate you show ' +
408
+ 'them are this agent’s own and not a guess. A knob with a reason cannot be tuned: show the reason and do not ' +
409
+ 'offer it. Call it again after the developer changes a setting if you want a fresh estimate.',
410
+ inputSchema: {
411
+ type: 'object',
412
+ properties: { experiment: { type: 'string', description: 'The name of a saved experiment.' } },
413
+ required: ['experiment'],
414
+ additionalProperties: false,
415
+ },
416
+ run: async (input) => {
417
+ const { optimize } = sessions();
418
+ const plan = await plannedSetup(sessions, await findExperiment(sessions, requiredText(input, 'experiment')));
419
+ return reply(defined({
420
+ experiment: { name: plan.experiment.name, cases: plan.experiment.caseCount },
421
+ // Knobs with nothing to tune for this agent are left out, so the model cannot offer them.
422
+ knobs: plan.knobs
423
+ .filter(({ unavailable }) => !unavailable)
424
+ .map(({ key, label, detail, enabled, notInCall }) => defined({
425
+ key,
426
+ label,
427
+ detail: detail || undefined,
428
+ onByDefault: enabled === true ? true : undefined,
429
+ notInCall: notInCall === true ? true : undefined,
430
+ })),
431
+ metrics: plan.metrics,
432
+ objective: defined({
433
+ current: plan.objective.expression || undefined,
434
+ constraints: plan.objective.constraints || undefined,
435
+ presets: plan.objectivePresets.map(({ label, objective }) => defined({
436
+ label,
437
+ objective: objective.expression || undefined,
438
+ constraints: objective.constraints || undefined,
439
+ })),
440
+ usageMetrics: EVALS_USAGE_METRICS,
441
+ notation: 'Maximize(X), Minimize(X), WeightedSum(Maximize(X), Minimize(Y, scale=1000)), or ' +
442
+ 'Pareto(Maximize(X), Minimize(Y, scale=1000)). X is an evaluator of the experiment or a usage metric. ' +
443
+ 'An empty objective maximizes the mean of every evaluator.',
444
+ }),
445
+ cases: { split: plan.split, choices: plan.splitChoices, testShare: plan.testShare },
446
+ budget: {
447
+ iterations: { value: plan.iterations, min: EVALS_BUDGET_MINIMUMS.iterations },
448
+ candidatesPerStep: { value: plan.width, min: EVALS_BUDGET_MINIMUMS.width },
449
+ runsPerCase: { value: plan.repetitions, min: EVALS_BUDGET_MINIMUMS.repetitions },
450
+ parallelTrials: { value: plan.workers, min: EVALS_BUDGET_MINIMUMS.workers },
451
+ finalists: { value: plan.decision.finalists, min: EVALS_BUDGET_MINIMUMS.finalists },
452
+ maxRollouts: { value: plan.maxRollouts, min: EVALS_BUDGET_MINIMUMS.maxRollouts },
453
+ rerunPasses: { value: plan.rerunPasses, min: EVALS_BUDGET_MINIMUMS.rerunPasses },
454
+ },
455
+ decision: {
456
+ feasibility: { value: plan.decision.feasibility, choices: plan.decisionChoices.feasibility },
457
+ crashes: { value: plan.decision.crashScore, choices: plan.decisionChoices.crashScore },
458
+ pick: { value: plan.decision.pickRule, choices: plan.decisionChoices.pickRule },
459
+ },
460
+ estimate: defined({ rollouts: plan.rollouts, judgeCalls: plan.judgeCalls, usage: plan.usage }),
461
+ problem: plan.splitProblem ?? plan.budgetProblem ?? plan.objectiveProblem,
462
+ warning: [plan.warning, plan.objectiveWarning, sessions().fileChanges()].filter(Boolean).join(' ') || undefined,
463
+ autoAccept: optimize.autoApplies() ? AUTO_PLAN : undefined,
464
+ }));
465
+ },
466
+ });
467
+ const chosen = (name, value, choices) => {
468
+ if (value === undefined)
469
+ return undefined;
470
+ if (!choices.includes(value))
471
+ throw new Error(`${name} must be one of ${choices.join(', ')}.`);
472
+ return value;
473
+ };
474
+ const budgetValue = (name, setting, value) => {
475
+ if (value === undefined || isEvalsBudgetValue(setting, value))
476
+ return value;
477
+ throw new Error(`${name} must be a whole number of at least ${EVALS_BUDGET_MINIMUMS[setting]}.`);
478
+ };
479
+ const objectiveFor = async (experiment, { objective, constraints }) => {
480
+ if (objective === undefined && constraints === undefined)
481
+ return undefined;
482
+ const { experiment: loaded } = await readEvalsExperimentFile(experiment.path);
483
+ const picked = evalsObjectiveFromRequest(objective, constraints, loaded.evaluators);
484
+ const { problem } = checkEvalsObjective(picked, loaded.evaluators);
485
+ if (problem)
486
+ throw new Error(`${problem} The evaluators of ${experiment.name}: ${loaded.evaluators.join(', ') || 'none'}.`);
487
+ return picked;
488
+ };
489
+ // Plans a fresh run, applies the flags of the skill, and starts it without waiting.
490
+ const startOptimization = async (sessions, experiment, settings, fromAutoOptimize = false) => {
491
+ const { optimize } = sessions();
492
+ const iterations = budgetValue('--max-iterations', 'iterations', settings.iterations);
493
+ const width = budgetValue('--proposals-per-iteration', 'width', settings.width);
494
+ const repetitions = budgetValue('--runs-per-candidate', 'repetitions', settings.repetitions);
495
+ const workers = budgetValue('--max-workers', 'workers', settings.workers);
496
+ const finalists = budgetValue('--n-finalists', 'finalists', settings.finalists);
497
+ const feasibility = chosen('--feasibility-threshold', settings.feasibility, EVALS_DECISION_CHOICES.feasibility);
498
+ const crashScore = chosen('--agent-failure-score', settings.crashScore, EVALS_DECISION_CHOICES.crashScore);
499
+ const maxRollouts = budgetValue('--max-rollouts', 'maxRollouts', settings.maxRollouts);
500
+ const rerunPasses = budgetValue('--rerun-passes', 'rerunPasses', settings.rerunPasses);
501
+ const objective = await objectiveFor(experiment, settings);
502
+ const plan = await plannedSetup(sessions, experiment);
503
+ tunedKnobs(plan.knobs, settings.tune);
504
+ if (settings.tune.includes('model'))
505
+ for (const model of settings.models)
506
+ optimize.pickModel(model, true);
507
+ for (const knob of plan.knobs)
508
+ if (!knob.unavailable && knob.kind !== 'models' && knob.enabled !== settings.tune.includes(knob.key))
509
+ optimize.toggleKnob(knob.key);
510
+ if (iterations !== undefined)
511
+ optimize.setIterations(iterations);
512
+ if (width !== undefined)
513
+ optimize.setWidth(width);
514
+ if (repetitions !== undefined)
515
+ optimize.setRepetitions(repetitions);
516
+ if (workers !== undefined)
517
+ optimize.setWorkers(workers);
518
+ if (objective)
519
+ optimize.setObjective(objective);
520
+ if (feasibility !== undefined)
521
+ optimize.setDecision('feasibility', feasibility);
522
+ if (crashScore !== undefined)
523
+ optimize.setDecision('crashScore', crashScore);
524
+ if (finalists !== undefined)
525
+ optimize.setDecision('finalists', finalists);
526
+ if (maxRollouts !== undefined)
527
+ optimize.setMaxRollouts(maxRollouts);
528
+ if (settings.seed !== undefined)
529
+ optimize.setSeed(settings.seed);
530
+ if (rerunPasses !== undefined)
531
+ optimize.setRerunPasses(rerunPasses);
532
+ if (settings.split !== undefined)
533
+ optimize.setSplit(settings.split);
534
+ optimize.setPassed(settings.passed);
535
+ const ready = optimize.snapshot();
536
+ const problem = ready.step === 'setup' ? (ready.plan.splitProblem ?? ready.plan.budgetProblem) : undefined;
537
+ if (problem)
538
+ throw new Error(problem);
539
+ const started = optimize.start({ fromAutoOptimize });
540
+ if (started === undefined)
541
+ throw new Error('The optimization did not start.');
542
+ return started;
543
+ };
544
+ /**
545
+ * Starts the optimization of auto-optimize on the experiment it made, as the background tool does with no flags: the
546
+ * defaults of its plan.
547
+ */
548
+ export const startEvalsOptimizationWithDefaults = async (sessions, experiment) => startOptimization(sessions, await findExperiment(sessions, experiment), optimizeFlagSettings([]), true);
549
+ const caseNames = async (experiment, names) => {
550
+ const { raw } = await readEvalsExperimentFile(experiment.path);
551
+ const known = raw.cases.map((item, index) => (typeof item.name === 'string' ? item.name : String(index)));
552
+ const unknown = names.filter((name) => !known.includes(name));
553
+ if (unknown.length > 0)
554
+ throw new Error(`${experiment.name} has no case ${unknown.join(', ')}.`);
555
+ };
556
+ const BACKGROUND_DETAIL = 'It goes on in the background, with its progress on a line below the chat input. A notice says when it ' +
557
+ 'finishes; then strands_dev_status and strands_dev_evaluation_results read the result.';
558
+ const OPTIMIZE_DETAIL = `${BACKGROUND_DETAIL} When it finishes, its edits appear on the developer's screen as a diff to apply or leave, ` +
559
+ 'and an applied edit is written and hot-reloaded without you; with auto-accept on, they are written unasked.';
560
+ const backgroundTool = (sessions) => ({
561
+ name: 'strands_dev_run_background',
562
+ description: 'Start a paid strands-evals command in the background and return at once. This call starts the paid run ' +
563
+ 'itself, so call it only after the developer answered yes, in an earlier turn, to the scope you named. ' +
564
+ 'Pass the command and the flags the skill would pass: run evaluates the agent on an experiment ' +
565
+ '(--case NAME, repeatable, runs only those cases), optimize run takes the flags of the optimize skill ' +
566
+ '(--tune, --no-tune-instructions, --objective, --pareto, --constraint, --max-rollouts, --max-iterations, ' +
567
+ '--proposals-per-iteration, --runs-per-candidate, --n-finalists, --max-workers, --feasibility-threshold, ' +
568
+ '--agent-failure-score, --split as TRAIN,VALIDATION,TEST shares, --seed, --rerun-passes, ' +
569
+ '--reflection-model), and generate takes --task-description, --context, and --num-cases of ' +
570
+ 'strands-evals generate and saves experiments/<experiment>/<experiment>.json. strands dev runs it in its ' +
571
+ 'prepared evals environment with ' +
572
+ 'this agent, writes run.log and the records under strands-dev/experiments/<experiment>/, and continues ' +
573
+ 'a run that stopped when strands dev closed. Flags that strands dev sets itself come back as ignored.',
574
+ inputSchema: {
575
+ type: 'object',
576
+ properties: {
577
+ command: { type: 'string', enum: [...BACKGROUND_COMMANDS], description: 'The strands-evals command.' },
578
+ experiment: {
579
+ type: 'string',
580
+ description: 'A saved experiment name, or with generate the name of the new experiment.',
581
+ },
582
+ args: { type: 'array', items: { type: 'string' }, description: 'The flags, one argument per item.' },
583
+ },
584
+ required: ['command', 'experiment'],
585
+ additionalProperties: false,
586
+ },
587
+ run: async (input) => {
588
+ const command = chosen('command', text(input, 'command'), BACKGROUND_COMMANDS);
589
+ const args = textList(input, 'args') ?? [];
590
+ const name = requiredText(input, 'experiment');
591
+ const started = (fields, ignored) => reply(defined({
592
+ status: 'started',
593
+ command,
594
+ experiment: name,
595
+ ...fields,
596
+ ignored: ignored.length > 0 ? ignored : undefined,
597
+ detail: command === 'optimize run' ? OPTIMIZE_DETAIL : BACKGROUND_DETAIL,
598
+ }));
599
+ if (command === 'generate') {
600
+ const { experiments } = sessions();
601
+ await experiments.reload();
602
+ const { settings, ignored } = generateFlagSettings(name, args, experiments.suggested());
603
+ const problem = experiments.generateInBackground(settings);
604
+ if (problem)
605
+ throw new Error(problem);
606
+ const { folder, generations } = experiments.snapshot();
607
+ const log = generations.find((generation) => generation.name === settings.name)?.log;
608
+ return started({ cases: settings.cases, file: join(folder, settings.name, `${settings.name}.json`), log }, ignored);
609
+ }
610
+ const experiment = await findExperiment(sessions, name);
611
+ if (command === 'optimize run') {
612
+ const settings = optimizeFlagSettings(args);
613
+ const run = await startOptimization(sessions, experiment, settings);
614
+ return started({ run, file: experiment.path }, settings.ignored);
615
+ }
616
+ const { cases, ignored } = runFlagCases(args);
617
+ const { evaluate } = sessions();
618
+ await evaluate.show();
619
+ if (runOf(evaluate, experiment.path)?.status === 'running')
620
+ throw new Error(`${experiment.name} is already running. strands_dev_evaluation_results reads its progress.`);
621
+ if (cases.length > 0) {
622
+ await caseNames(experiment, cases);
623
+ evaluate.runOnly(experiment, cases);
624
+ }
625
+ else
626
+ evaluate.run([experiment]);
627
+ return started({ cases: cases.length > 0 ? cases.length : experiment.caseCount, file: experiment.path }, ignored);
628
+ },
629
+ });
630
+ const stopBackgroundTool = (sessions) => ({
631
+ name: 'strands_dev_stop_background',
632
+ description: 'Stop a command that strands_dev_run_background started, only when the developer asks. A stopped ' +
633
+ 'optimization keeps the best candidate so far. Cancelling the chat turn does not stop it.',
634
+ inputSchema: {
635
+ type: 'object',
636
+ properties: {
637
+ command: { type: 'string', enum: [...BACKGROUND_COMMANDS] },
638
+ experiment: { type: 'string', description: 'The experiment of the run.' },
639
+ },
640
+ required: ['command', 'experiment'],
641
+ additionalProperties: false,
642
+ },
643
+ run: async (input) => {
644
+ const command = chosen('command', text(input, 'command'), BACKGROUND_COMMANDS);
645
+ const name = requiredText(input, 'experiment');
646
+ const { experiments, evaluate, optimize } = sessions();
647
+ if (command === 'generate') {
648
+ const job = experiments
649
+ .snapshot()
650
+ .generations.find((generation) => generation.name === name && isGenerating(generation));
651
+ if (!job)
652
+ throw new Error(`No generation of ${name} is running.`);
653
+ experiments.cancel(job.id);
654
+ return reply({ command, experiment: name, status: 'stopped' });
655
+ }
656
+ const experiment = await findExperiment(sessions, name);
657
+ if (command === 'run') {
658
+ await evaluate.show();
659
+ if (runOf(evaluate, experiment.path)?.status !== 'running')
660
+ throw new Error(`No evaluation of ${experiment.name} is running.`);
661
+ evaluate.stop(experiment.path);
662
+ return reply({ command, experiment: experiment.name, status: 'stopping' });
663
+ }
664
+ const running = optimize
665
+ .snapshot()
666
+ .runs?.find((run) => run.experiment === experiment.name && run.state.step === 'running');
667
+ if (!running)
668
+ throw new Error(`No optimization of ${experiment.name} is running.`);
669
+ optimize.stop(running.id);
670
+ return reply({ command, experiment: experiment.name, status: 'stopping' });
671
+ },
672
+ });
673
+ const runRecord = ({ record, state }) => record ||
674
+ (state.step === 'running'
675
+ ? state.progress.record
676
+ : state.step === 'review'
677
+ ? state.review.record
678
+ : state.step === 'failed'
679
+ ? state.record
680
+ : undefined) ||
681
+ undefined;
682
+ // The newest optimization run of the experiment that has a record, else the list of optimization runs.
683
+ const optimizationPlace = ({ runs = [] }, experiment) => {
684
+ const record = runs
685
+ .filter((run) => run.experiment === experiment)
686
+ .map(runRecord)
687
+ .find((found) => found !== undefined);
688
+ return record ? { view: 'optimization', record } : { view: 'opt-runs' };
689
+ };
690
+ const openEvalsUiTool = (sessions) => ({
691
+ name: 'strands_dev_open_evals_ui',
692
+ readOnly: true,
693
+ description: 'Open the evals UI in the browser of the developer: an experiment with its cases, the last report of an experiment, ' +
694
+ 'the latest optimization run of an experiment, or the list of runs when no experiment is given. ' +
695
+ 'Returns what to tell the developer when it cannot open the browser.',
696
+ inputSchema: {
697
+ type: 'object',
698
+ properties: {
699
+ experiment: { type: 'string', description: 'A saved experiment name; omit to open the list of runs.' },
700
+ view: { type: 'string', enum: ['experiment', 'report', 'optimization'], description: 'Default experiment.' },
701
+ case: { type: 'string', description: 'A case name to open in the experiment or report view.' },
702
+ },
703
+ additionalProperties: false,
704
+ },
705
+ run: async (input) => {
706
+ const name = text(input, 'experiment');
707
+ const view = text(input, 'view');
708
+ const item = text(input, 'case');
709
+ const place = async () => {
710
+ if (!name)
711
+ return { view: view === 'optimization' ? 'opt-runs' : 'runs' };
712
+ const experiment = await findExperiment(sessions, name);
713
+ if (view === 'optimization')
714
+ return optimizationPlace(sessions().optimize.snapshot(), experiment.name);
715
+ return {
716
+ view: view === 'report' ? 'report' : 'experiment',
717
+ experiment: experiment.path,
718
+ ...(item ? { case: item } : {}),
719
+ };
720
+ };
721
+ const notice = await sessions().ui.open(await place());
722
+ return reply(notice ? { opened: false, tell: notice.lines } : { opened: true });
723
+ },
724
+ });
725
+ const openFileTool = (sessions) => ({
726
+ name: 'strands_dev_open_file',
727
+ readOnly: true,
728
+ description: 'Open a file in the editor of the developer, the way /config opens the agent: $STRANDS_EDITOR, $VISUAL, or ' +
729
+ '$EDITOR, else the app of the system for the file. A terminal editor takes the screen and gives it back when ' +
730
+ 'it closes. Pass experiment for a saved experiment, or path for any other file. Do not print the file in chat.',
731
+ inputSchema: {
732
+ type: 'object',
733
+ properties: {
734
+ experiment: { type: 'string', description: 'A saved experiment name; opens its file.' },
735
+ path: { type: 'string', description: 'Any file path, absolute or relative to the agent folder.' },
736
+ },
737
+ additionalProperties: false,
738
+ },
739
+ run: async (input) => {
740
+ const experiment = text(input, 'experiment');
741
+ const given = text(input, 'path');
742
+ if (Boolean(experiment) === Boolean(given))
743
+ throw new Error('Give experiment or path, one of them.');
744
+ const path = experiment ? (await findExperiment(sessions, experiment)).path : given;
745
+ try {
746
+ await sessions().openFile(path);
747
+ return reply({ opened: true, file: path });
748
+ }
749
+ catch (error) {
750
+ return reply({
751
+ opened: false,
752
+ file: path,
753
+ detail: `${errorMessage(error)} Give the path${experiment ? ', offer strands_dev_open_evals_ui,' : ''} and ask in chat what to change.`,
754
+ });
755
+ }
756
+ },
757
+ });
758
+ const NOTHING_WAITS = 'No finished optimization has an edit waiting for an answer.';
759
+ const reviewOptimizationTool = (sessions, show) => ({
760
+ name: 'strands_dev_review_optimization',
761
+ description: "Put the diff of a finished optimization back on the developer's screen, where they apply each edit or leave " +
762
+ 'it. Use it when they ask to see a run or its change again while an edit of it still waits for their answer. ' +
763
+ 'It writes nothing and decides nothing.',
764
+ inputSchema: {
765
+ type: 'object',
766
+ properties: {
767
+ run: {
768
+ type: 'string',
769
+ description: 'The run name from strands_dev_status. Leave it out for the latest run with an edit waiting.',
770
+ },
771
+ },
772
+ additionalProperties: false,
773
+ },
774
+ run: async (input) => {
775
+ const wanted = text(input, 'run');
776
+ const waiting = (sessions().optimize.snapshot().runs ?? []).flatMap(({ id, state }) => state.step === 'review' && evalsEditsAwaitingAnswer(state.review) > 0 && !state.review.applied
777
+ ? [{ id, review: state.review }]
778
+ : []);
779
+ const found = wanted ? waiting.find(({ review }) => review.run === wanted) : waiting[0];
780
+ if (!found?.id)
781
+ throw new Error(wanted ? `Run ${wanted} has no edit waiting for an answer.` : NOTHING_WAITS);
782
+ if (!show(found.id))
783
+ throw new Error('The diff could not be put on screen. The developer can open it from its line under the chat input.');
784
+ return reply({
785
+ run: found.review.run,
786
+ shown: true,
787
+ next: "The diff is on the developer's screen again, where they apply it or leave it. Say so in one line. " +
788
+ 'Do not print the edit, and do not ask whether to apply it.',
789
+ });
790
+ },
791
+ });
792
+ const answeredNext = ({ settled, applied, applyError, next }, apply) => {
793
+ if (next)
794
+ return (`The diff of edit ${next.edit} of this run took its place on the developer's screen, ${next.at + 1} of ` +
795
+ `${next.of}: ${next.change}. If their message answered every edit of the run, such as "apply all of ` +
796
+ 'them", answer this one the same way. Otherwise it is theirs to answer: say in one line what you picked ' +
797
+ 'and that the next edit is on screen.');
798
+ if (!settled)
799
+ return 'Another edit of this run still waits behind a question on screen. Say in one line what you picked.';
800
+ if (applyError)
801
+ return 'An edit could not be written: give applyError as it is, and say which edits were applied.';
802
+ if (applied?.length)
803
+ return ('Every edit of this run has its answer, the diff is closed, and the edits in applied are written. The agent ' +
804
+ 'reloads after your reply. Say so in one line, and offer to evaluate the experiment again to check the change.');
805
+ return apply
806
+ ? 'Every edit of this run has its answer and the diff is closed. Say so in one line.'
807
+ : 'Every edit of this run has its answer, the diff is closed, and nothing was written. Say so in one line.';
808
+ };
809
+ const answerReviewTool = (answerReview) => ({
810
+ name: 'strands_dev_answer_review',
811
+ description: "Pick a choice of the optimization diff on the developer's screen, in their place: apply the edit it shows, or " +
812
+ 'leave it as it is. Call it only when their chat message came with that diff as what is on their screen and ' +
813
+ 'the message is their answer to it, with the run and the edit named there. It does what picking the choice on ' +
814
+ 'screen does: the diff closes, the next edit of the run shows, and the accepted edits are written once every ' +
815
+ 'edit has its answer. It refuses when that diff is not the one showing.',
816
+ inputSchema: {
817
+ type: 'object',
818
+ properties: {
819
+ run: { type: 'string', description: 'The run that the diff on screen belongs to.' },
820
+ edit: { type: 'integer', description: 'The edit that the diff on screen shows, by its index in that run.' },
821
+ answer: {
822
+ type: 'string',
823
+ enum: ['apply', 'leave'],
824
+ description: 'apply writes the edit; leave keeps the agent as it is.',
825
+ },
826
+ },
827
+ required: ['run', 'edit', 'answer'],
828
+ additionalProperties: false,
829
+ },
830
+ run: async (input) => {
831
+ const edit = whole(input, 'edit', 0, Number.MAX_SAFE_INTEGER);
832
+ if (edit === undefined)
833
+ throw new Error('edit must be the index of the edit that the diff on screen shows.');
834
+ if (input.answer !== 'apply' && input.answer !== 'leave')
835
+ throw new Error('answer must be apply or leave.');
836
+ const apply = input.answer === 'apply';
837
+ const answered = await answerReview({ run: requiredText(input, 'run'), edit, apply });
838
+ return reply(defined({
839
+ run: answered.run,
840
+ edit,
841
+ picked: apply ? 'Apply this change' : 'Leave it as it is',
842
+ applied: answered.applied,
843
+ applyError: answered.applyError,
844
+ next: answeredNext(answered, apply),
845
+ }));
846
+ },
847
+ });
848
+ const appliedNext = ({ settled, waiting, shown }) => {
849
+ if (settled)
850
+ return 'Evaluate the experiment again, after the developer approves it, to check the change.';
851
+ const still = waiting === 1 ? '1 other edit of this run still waits' : `${waiting} other edits of this run still wait`;
852
+ return (`Their answer is kept, and nothing is written yet: ${still} for the developer's answer, and a run is written ` +
853
+ 'once every edit has one. ' +
854
+ (shown
855
+ ? 'The diff of a waiting edit is on their screen now. Say that in one line.'
856
+ : 'The run is on the status line under the chat input, where clicking it opens the diff. Say that in one line.'));
857
+ };
858
+ const applyTool = (applyEdits) => ({
859
+ name: 'strands_dev_apply_optimization',
860
+ description: 'Answer edits of a finished optimization with apply, for a developer who named them in chat while no diff of ' +
861
+ 'them is on screen. Give the run and the index of each named edit, from the review in strands_dev_status. ' +
862
+ 'Every other edit keeps the answer it has, on screen or none yet. The run is written to the agent source once ' +
863
+ 'every edit has its answer; until then the diff of a waiting edit goes on screen.',
864
+ inputSchema: {
865
+ type: 'object',
866
+ properties: {
867
+ run: { type: 'string', description: 'The run name from strands_dev_status.' },
868
+ edits: { type: 'array', items: { type: 'integer' }, description: 'The indexes of the edits to apply.' },
869
+ },
870
+ required: ['run', 'edits'],
871
+ additionalProperties: false,
872
+ },
873
+ run: async (input) => {
874
+ const edits = Array.isArray(input.edits) ? input.edits : [];
875
+ for (const index of edits)
876
+ if (typeof index !== 'number' || !Number.isInteger(index) || index < 0)
877
+ throw new Error(`There is no edit ${String(index)}.`);
878
+ const applied = await applyEdits({ run: requiredText(input, 'run'), edits: edits });
879
+ if (applied.applyError)
880
+ throw new Error(applied.applyError);
881
+ return reply(defined({
882
+ run: applied.run,
883
+ applied: applied.applied,
884
+ awaitingAnswer: applied.waiting,
885
+ next: appliedNext(applied),
886
+ }));
887
+ },
888
+ });
889
+ const signed = (value) => `${value >= 0 ? '+' : ''}${value.toFixed(2)}`;
890
+ const changedValue = (text) => JSON.stringify(clip(text) ?? '');
891
+ const changedEdit = ({ label, kind, target, before, after, added }) => {
892
+ const where = target ? ` in ${target}` : '';
893
+ return kind === 'text'
894
+ ? ` - ${label}${where}: was ${changedValue(before)}, now ${changedValue(after)}`
895
+ : ` - ${label}${where}: ${before} → ${after}${added ? `; ${added}` : ''}`;
896
+ };
897
+ const testCheckText = (check) => {
898
+ if (!check)
899
+ return '';
900
+ const range = check.range
901
+ ? ` (${Math.round(check.confidence * 100)}% confidence range ${signed(check.range[0])} to ${signed(check.range[1])})`
902
+ : '';
903
+ return ` The test check gave ${signed(check.difference)} on ${plural(check.cases, 'unseen test case')}${range}.`;
904
+ };
905
+ const changeSummary = (change) => `- ${new Date(change.appliedAt).toISOString()}: ${change.auto ? 'auto-accept' : '/optimize'} applied ` +
906
+ `${plural(change.edits.length, 'edit')} from run ${change.run} of the experiment ${change.experiment}. ` +
907
+ (change.auto
908
+ ? 'The developer has auto-accept on, so they were not shown these edits before they were written. '
909
+ : '') +
910
+ `The best candidate scored ${change.baseline.toFixed(2)} → ${change.best.toFixed(2)} on the ${change.measuredOn}.` +
911
+ testCheckText(change.testCheck) +
912
+ (change.error ? ` Apply stopped early: ${change.error}` : '');
913
+ const changesSection = (changes) => changes.length === 0
914
+ ? []
915
+ : [
916
+ [
917
+ 'Changes that strands dev made to this agent in this session. The agent source has them, and strands dev reloaded the agent after each one, so this chat already runs the changed agent:',
918
+ ...changes.flatMap((change) => [changeSummary(change), ...change.edits.map(changedEdit)]),
919
+ ].join('\n'),
920
+ ];
921
+ export const evalsDevChatPart = ({ sessions, history, showReview = (run) => showOptimizeReview(sessions(), run), answerReview = (answer) => answerOptimizeReview(sessions(), answer), applyEdits = (named) => applyOptimizeEdits(sessions(), named), }) => ({
922
+ instructions: [INSTRUCTIONS, ...changesSection(sessions().optimize.appliedChanges())].join('\n\n'),
923
+ skills: [STRANDS_EVALS_SKILL, STRANDS_EVALS_OPTIMIZE_SKILL, ...evalsWorkflowSkills()],
924
+ tools: [
925
+ statusTool(sessions, history),
926
+ sessionConverterTool(history),
927
+ readExperimentTool(sessions),
928
+ evaluationResultsTool(sessions),
929
+ backgroundTool(sessions),
930
+ stopBackgroundTool(sessions),
931
+ openEvalsUiTool(sessions),
932
+ openFileTool(sessions),
933
+ planTool(sessions),
934
+ ...uiTools(() => sessions().ask),
935
+ autoOptimizeTool(sessions),
936
+ reviewOptimizationTool(sessions, showReview),
937
+ answerReviewTool(answerReview),
938
+ applyTool(applyEdits),
939
+ ],
940
+ });
941
+ //# sourceMappingURL=agent-tools.js.map