@strands-agents/cli 0.3.0 → 0.5.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 (245) hide show
  1. package/README.md +367 -1
  2. package/dist/src/agent/configuration.js.map +1 -1
  3. package/dist/src/agent/extension.js +46 -0
  4. package/dist/src/agent/extension.js.map +1 -0
  5. package/dist/src/agent/mcp.js +1 -2
  6. package/dist/src/agent/mcp.js.map +1 -1
  7. package/dist/src/agent/runtime.js +25 -2
  8. package/dist/src/agent/runtime.js.map +1 -1
  9. package/dist/src/cli/acp-events.js +15 -0
  10. package/dist/src/cli/acp-events.js.map +1 -1
  11. package/dist/src/cli/acp-python.js +2 -2
  12. package/dist/src/cli/acp-python.js.map +1 -1
  13. package/dist/src/cli/acp.js +2 -17
  14. package/dist/src/cli/acp.js.map +1 -1
  15. package/dist/src/cli/arguments.js +91 -11
  16. package/dist/src/cli/arguments.js.map +1 -1
  17. package/dist/src/cli/invocation.js +10 -2
  18. package/dist/src/cli/invocation.js.map +1 -1
  19. package/dist/src/cli/run.js +154 -15
  20. package/dist/src/cli/run.js.map +1 -1
  21. package/dist/src/cli/telemetry.js.map +1 -1
  22. package/dist/src/config/settings.js +67 -2
  23. package/dist/src/config/settings.js.map +1 -1
  24. package/dist/src/config/store.js +171 -21
  25. package/dist/src/config/store.js.map +1 -1
  26. package/dist/src/config/watch.js +24 -0
  27. package/dist/src/config/watch.js.map +1 -0
  28. package/dist/src/dev/agent-choices.js +281 -0
  29. package/dist/src/dev/agent-choices.js.map +1 -0
  30. package/dist/src/dev/agent-options.js +467 -0
  31. package/dist/src/dev/agent-options.js.map +1 -0
  32. package/dist/src/dev/base-cli.js +201 -0
  33. package/dist/src/dev/base-cli.js.map +1 -0
  34. package/dist/src/dev/chat-extension.js +42 -0
  35. package/dist/src/dev/chat-extension.js.map +1 -0
  36. package/dist/src/dev/create.js +443 -0
  37. package/dist/src/dev/create.js.map +1 -0
  38. package/dist/src/dev/errors.js +89 -0
  39. package/dist/src/dev/errors.js.map +1 -0
  40. package/dist/src/dev/evals/chat/agent-tools.js +941 -0
  41. package/dist/src/dev/evals/chat/agent-tools.js.map +1 -0
  42. package/dist/src/dev/evals/chat/background-flags.js +231 -0
  43. package/dist/src/dev/evals/chat/background-flags.js.map +1 -0
  44. package/dist/src/dev/evals/chat/command.js +140 -0
  45. package/dist/src/dev/evals/chat/command.js.map +1 -0
  46. package/dist/src/dev/evals/chat/ui-tools.js +252 -0
  47. package/dist/src/dev/evals/chat/ui-tools.js.map +1 -0
  48. package/dist/src/dev/evals/chat/workflow-skills.js +48 -0
  49. package/dist/src/dev/evals/chat/workflow-skills.js.map +1 -0
  50. package/dist/src/dev/evals/host.js +22 -0
  51. package/dist/src/dev/evals/host.js.map +1 -0
  52. package/dist/src/dev/evals/jobs.js +151 -0
  53. package/dist/src/dev/evals/jobs.js.map +1 -0
  54. package/dist/src/dev/evals/layout.js +223 -0
  55. package/dist/src/dev/evals/layout.js.map +1 -0
  56. package/dist/src/dev/evals/model.js +4 -0
  57. package/dist/src/dev/evals/model.js.map +1 -0
  58. package/dist/src/dev/evals/package.js +14 -0
  59. package/dist/src/dev/evals/package.js.map +1 -0
  60. package/dist/src/dev/evals/python/entry-files.js +70 -0
  61. package/dist/src/dev/evals/python/entry-files.js.map +1 -0
  62. package/dist/src/dev/evals/python/strands_dev_evals/__init__.py +0 -0
  63. package/dist/src/dev/evals/python/strands_dev_evals/errors.py +2 -0
  64. package/dist/src/dev/evals/python/strands_dev_evals/harness.py +265 -0
  65. package/dist/src/dev/evals/python/strands_dev_evals/imports.py +61 -0
  66. package/dist/src/dev/evals/python/strands_dev_evals/model_effort.py +120 -0
  67. package/dist/src/dev/evals/python/strands_dev_evals/optimize.py +152 -0
  68. package/dist/src/dev/evals/python/strands_dev_evals/run.py +55 -0
  69. package/dist/src/dev/evals/python/strands_dev_evals/space.py +212 -0
  70. package/dist/src/dev/evals/python/strands_dev_evals/temporary_typescript.py +313 -0
  71. package/dist/src/dev/evals/runs/background-runs.js +182 -0
  72. package/dist/src/dev/evals/runs/background-runs.js.map +1 -0
  73. package/dist/src/dev/evals/runs/environment.js +258 -0
  74. package/dist/src/dev/evals/runs/environment.js.map +1 -0
  75. package/dist/src/dev/evals/runs/evals-process.js +157 -0
  76. package/dist/src/dev/evals/runs/evals-process.js.map +1 -0
  77. package/dist/src/dev/evals/runs/evaluate.js +288 -0
  78. package/dist/src/dev/evals/runs/evaluate.js.map +1 -0
  79. package/dist/src/dev/evals/runs/experiment.js +319 -0
  80. package/dist/src/dev/evals/runs/experiment.js.map +1 -0
  81. package/dist/src/dev/evals/runs/layout-migration.js +302 -0
  82. package/dist/src/dev/evals/runs/layout-migration.js.map +1 -0
  83. package/dist/src/dev/evals/runs/optimize.js +249 -0
  84. package/dist/src/dev/evals/runs/optimize.js.map +1 -0
  85. package/dist/src/dev/evals/runs/typescript-runner-main.js +40 -0
  86. package/dist/src/dev/evals/runs/typescript-runner-main.js.map +1 -0
  87. package/dist/src/dev/evals/runs/typescript-runner.js +192 -0
  88. package/dist/src/dev/evals/runs/typescript-runner.js.map +1 -0
  89. package/dist/src/dev/evals/sessions/auto-optimize.js +259 -0
  90. package/dist/src/dev/evals/sessions/auto-optimize.js.map +1 -0
  91. package/dist/src/dev/evals/sessions/evals-ui.js +232 -0
  92. package/dist/src/dev/evals/sessions/evals-ui.js.map +1 -0
  93. package/dist/src/dev/evals/sessions/evaluate-session.js +252 -0
  94. package/dist/src/dev/evals/sessions/evaluate-session.js.map +1 -0
  95. package/dist/src/dev/evals/sessions/experiments-session.js +305 -0
  96. package/dist/src/dev/evals/sessions/experiments-session.js.map +1 -0
  97. package/dist/src/dev/evals/sessions/optimize-session.js +942 -0
  98. package/dist/src/dev/evals/sessions/optimize-session.js.map +1 -0
  99. package/dist/src/dev/evals/sessions/review-run.js +245 -0
  100. package/dist/src/dev/evals/sessions/review-run.js.map +1 -0
  101. package/dist/src/dev/evals/sessions/session-converter.js +110 -0
  102. package/dist/src/dev/evals/sessions/session-converter.js.map +1 -0
  103. package/dist/src/dev/evals/sessions/sessions.js +81 -0
  104. package/dist/src/dev/evals/sessions/sessions.js.map +1 -0
  105. package/dist/src/dev/evals/shell/arguments.js +26 -0
  106. package/dist/src/dev/evals/shell/arguments.js.map +1 -0
  107. package/dist/src/dev/evals/shell/cli.js +77 -0
  108. package/dist/src/dev/evals/shell/cli.js.map +1 -0
  109. package/dist/src/dev/evals/tuning/apply.js +535 -0
  110. package/dist/src/dev/evals/tuning/apply.js.map +1 -0
  111. package/dist/src/dev/evals/tuning/knobs.js +293 -0
  112. package/dist/src/dev/evals/tuning/knobs.js.map +1 -0
  113. package/dist/src/dev/evals/tuning/objective.js +273 -0
  114. package/dist/src/dev/evals/tuning/objective.js.map +1 -0
  115. package/dist/src/dev/evals/tuning/plan.js +156 -0
  116. package/dist/src/dev/evals/tuning/plan.js.map +1 -0
  117. package/dist/src/dev/evals/tuning/study.js +392 -0
  118. package/dist/src/dev/evals/tuning/study.js.map +1 -0
  119. package/dist/src/dev/failed-turns.js +31 -0
  120. package/dist/src/dev/failed-turns.js.map +1 -0
  121. package/dist/src/dev/file-edits.js +67 -0
  122. package/dist/src/dev/file-edits.js.map +1 -0
  123. package/dist/src/dev/fix-in-new-tab.js +151 -0
  124. package/dist/src/dev/fix-in-new-tab.js.map +1 -0
  125. package/dist/src/dev/picker.js +498 -0
  126. package/dist/src/dev/picker.js.map +1 -0
  127. package/dist/src/dev/prepare.js +526 -0
  128. package/dist/src/dev/prepare.js.map +1 -0
  129. package/dist/src/dev/project-setup.js +209 -0
  130. package/dist/src/dev/project-setup.js.map +1 -0
  131. package/dist/src/dev/runtime.js +55 -0
  132. package/dist/src/dev/runtime.js.map +1 -0
  133. package/dist/src/dev/search.js +466 -0
  134. package/dist/src/dev/search.js.map +1 -0
  135. package/dist/src/dev/telemetry.js +30 -0
  136. package/dist/src/dev/telemetry.js.map +1 -0
  137. package/dist/src/dev/workspace.js +547 -0
  138. package/dist/src/dev/workspace.js.map +1 -0
  139. package/dist/src/model/credential-failure.js +5 -0
  140. package/dist/src/model/credential-failure.js.map +1 -0
  141. package/dist/src/model/effort-fields.js +80 -0
  142. package/dist/src/model/effort-fields.js.map +1 -0
  143. package/dist/src/paths.js +9 -1
  144. package/dist/src/paths.js.map +1 -1
  145. package/dist/src/process-lock.js +89 -0
  146. package/dist/src/process-lock.js.map +1 -0
  147. package/dist/src/project/archive.js +11 -1
  148. package/dist/src/project/archive.js.map +1 -1
  149. package/dist/src/project/export.js +40 -14
  150. package/dist/src/project/export.js.map +1 -1
  151. package/dist/src/project/install.js +33 -0
  152. package/dist/src/project/install.js.map +1 -0
  153. package/dist/src/project/module-loader.js +36 -0
  154. package/dist/src/project/module-loader.js.map +1 -1
  155. package/dist/src/project/portability.js +2 -1
  156. package/dist/src/project/portability.js.map +1 -1
  157. package/dist/src/project/preparation-plan.js +182 -0
  158. package/dist/src/project/preparation-plan.js.map +1 -0
  159. package/dist/src/project/preparation.js +515 -0
  160. package/dist/src/project/preparation.js.map +1 -0
  161. package/dist/src/project/python-runtime.js +234 -0
  162. package/dist/src/project/python-runtime.js.map +1 -0
  163. package/dist/src/project/python.js +44 -11
  164. package/dist/src/project/python.js.map +1 -1
  165. package/dist/src/project/source.js +12 -7
  166. package/dist/src/project/source.js.map +1 -1
  167. package/dist/src/project/state-folder.js +15 -0
  168. package/dist/src/project/state-folder.js.map +1 -0
  169. package/dist/src/project/typescript-backend.js +18 -8
  170. package/dist/src/project/typescript-backend.js.map +1 -1
  171. package/dist/src/project/typescript-worker.js +14 -0
  172. package/dist/src/project/typescript-worker.js.map +1 -1
  173. package/dist/src/project/typescript.js +14 -1
  174. package/dist/src/project/typescript.js.map +1 -1
  175. package/dist/src/project/watch.js +37 -6
  176. package/dist/src/project/watch.js.map +1 -1
  177. package/dist/src/project/worker.py +168 -14
  178. package/dist/src/session/desktop-profile.js +4 -0
  179. package/dist/src/session/desktop-profile.js.map +1 -1
  180. package/dist/src/session/sessions.js +18 -2
  181. package/dist/src/session/sessions.js.map +1 -1
  182. package/dist/src/terminal/npm.js +1 -1
  183. package/dist/src/terminal/npm.js.map +1 -1
  184. package/dist/src/terminal/terminal.js +16 -2
  185. package/dist/src/terminal/terminal.js.map +1 -1
  186. package/dist/src/terminal/text.js +23 -0
  187. package/dist/src/terminal/text.js.map +1 -1
  188. package/dist/src/ui/app.js +17 -6
  189. package/dist/src/ui/app.js.map +1 -1
  190. package/dist/src/ui/chat/commands.js +3 -5
  191. package/dist/src/ui/chat/commands.js.map +1 -1
  192. package/dist/src/ui/chat/controller.js +405 -38
  193. package/dist/src/ui/chat/controller.js.map +1 -1
  194. package/dist/src/ui/chat/conversations.js +88 -10
  195. package/dist/src/ui/chat/conversations.js.map +1 -1
  196. package/dist/src/ui/chat/help.js +8 -0
  197. package/dist/src/ui/chat/help.js.map +1 -1
  198. package/dist/src/ui/chat/panel-state.js +36 -14
  199. package/dist/src/ui/chat/panel-state.js.map +1 -1
  200. package/dist/src/ui/chat/projector.js +10 -0
  201. package/dist/src/ui/chat/projector.js.map +1 -1
  202. package/dist/src/ui/chat/runtime.js +106 -9
  203. package/dist/src/ui/chat/runtime.js.map +1 -1
  204. package/dist/src/ui/chat/screen.js +215 -55
  205. package/dist/src/ui/chat/screen.js.map +1 -1
  206. package/dist/src/ui/chat/state.js +28 -0
  207. package/dist/src/ui/chat/state.js.map +1 -1
  208. package/dist/src/ui/chat/transcript-turn.js +15 -3
  209. package/dist/src/ui/chat/transcript-turn.js.map +1 -1
  210. package/dist/src/ui/chat/transcript.js +7 -5
  211. package/dist/src/ui/chat/transcript.js.map +1 -1
  212. package/dist/src/ui/chat/types.js.map +1 -1
  213. package/dist/src/ui/chat/view.js +84 -27
  214. package/dist/src/ui/chat/view.js.map +1 -1
  215. package/dist/src/ui/clipboard.js +41 -0
  216. package/dist/src/ui/clipboard.js.map +1 -0
  217. package/dist/src/ui/footer.js +19 -0
  218. package/dist/src/ui/footer.js.map +1 -1
  219. package/dist/src/ui/input.js +18 -0
  220. package/dist/src/ui/input.js.map +1 -0
  221. package/dist/src/ui/interaction.js +30 -8
  222. package/dist/src/ui/interaction.js.map +1 -1
  223. package/dist/src/ui/panels/dev.js +60 -0
  224. package/dist/src/ui/panels/dev.js.map +1 -0
  225. package/dist/src/ui/panels/settings.js +15 -1
  226. package/dist/src/ui/panels/settings.js.map +1 -1
  227. package/dist/src/ui/panels/wizard-request-panel.js +356 -0
  228. package/dist/src/ui/panels/wizard-request-panel.js.map +1 -0
  229. package/dist/src/ui/panels/wizard-request.js +251 -0
  230. package/dist/src/ui/panels/wizard-request.js.map +1 -0
  231. package/dist/src/ui/presentation.js +18 -3
  232. package/dist/src/ui/presentation.js.map +1 -1
  233. package/dist/src/ui/run.js +188 -11
  234. package/dist/src/ui/run.js.map +1 -1
  235. package/dist/src/ui/setup/providers.js +17 -0
  236. package/dist/src/ui/setup/providers.js.map +1 -1
  237. package/dist/src/ui/setup/steps.js +1 -1
  238. package/dist/src/ui/setup/steps.js.map +1 -1
  239. package/dist/src/ui/setup/wizard.js +12 -9
  240. package/dist/src/ui/setup/wizard.js.map +1 -1
  241. package/dist/src/ui/startup.js +32 -8
  242. package/dist/src/ui/startup.js.map +1 -1
  243. package/dist/src/ui/update.js +3 -2
  244. package/dist/src/ui/update.js.map +1 -1
  245. package/package.json +1 -1
@@ -0,0 +1,942 @@
1
+ import { existsSync, watch } from 'node:fs';
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { basename, dirname, join, relative } from 'node:path';
4
+ import { errorMessage } from '../../../terminal/text.js';
5
+ import { recordDevEvent } from '../../telemetry.js';
6
+ import { isRecord } from '../../../values.js';
7
+ import { editAgentOptions } from '../../agent-options.js';
8
+ import { baseCliEditProblem, editBaseCliProfile, isProfileBaseCli } from '../../base-cli.js';
9
+ import { userConfigPath } from '../../../config/store.js';
10
+ import {} from '../model.js';
11
+ import { locateEvalsEdit } from '../tuning/apply.js';
12
+ import { dropEvalsOptimizeRecord, isEvalsOptimizeAlive, readEvalsOptimizeRecords, saveEvalsOptimizeRecord, waitForEvalsOptimize, } from '../runs/background-runs.js';
13
+ import { evalsWorkspaceDirectory } from '../runs/evals-process.js';
14
+ import { evalsExperimentHome, evalsOptimizationFiles, evalsOptimizationOf, evalsOptimizationRunName, evalsRunStamp, } from '../layout.js';
15
+ import { evalsWorkspaceReady } from '../runs/layout-migration.js';
16
+ import { readEvalsExperimentFile, evalsCaseCount, evalsJudgeEvaluatorCount } from '../runs/experiment.js';
17
+ import { EvalsExperiments } from './experiments-session.js';
18
+ import { announce, plural, evalsLinkText } from '../host.js';
19
+ import { Store } from '../jobs.js';
20
+ import { readEvalsKnobs, evalsKnobChanges, evalsSpaceVariables, } from '../tuning/knobs.js';
21
+ import { checkEvalsObjective, isEvalsPareto, evalsObjectivePresets, EVALS_USAGE_METRICS } from '../tuning/objective.js';
22
+ import { runEvalsOptimization } from '../runs/optimize.js';
23
+ import { EVALS_DECISION_CHOICES, EVALS_DECISION_DEFAULTS, isEvalsBudgetValue, evalsRolloutCapProblem, EVALS_TEST_SHARES, EVALS_OPTIMIZE_DEFAULTS, evalsCaseSplit, evalsOptimizeWarning, evalsRolloutEstimate, evalsRolloutPhases, evalsSplitChoices, evalsSplitShares, evalsRolloutReserve, evalsSharesProblem, evalsSplitProblem, } from '../tuning/plan.js';
24
+ import { hasEvalsRunResult, readEvalsStudy, readEvalsUsageProfile, tailEvalsRun, evalsRunFolder, evalsStudyReader, } from '../tuning/study.js';
25
+ const DEFAULT_ITERATIONS = 4;
26
+ const SOURCE_SETTLE_MS = 300;
27
+ const RELOAD_WINDOW_MS = 15_000;
28
+ // Auto-accept writes as the agent starts reporting the run, and the reload waits for that turn to end.
29
+ const AUTO_RELOAD_WINDOW_MS = 120_000;
30
+ const WIDTH = 4;
31
+ const REPETITIONS = 1;
32
+ const WORKERS = 4;
33
+ const NO_OBJECTIVE = { expression: '', constraints: '' };
34
+ const objectiveFields = (objective, evaluators) => {
35
+ const { problem, warning } = checkEvalsObjective(objective, evaluators);
36
+ return {
37
+ objective,
38
+ ...(problem ? { objectiveProblem: problem } : {}),
39
+ ...(warning ? { objectiveWarning: warning } : {}),
40
+ };
41
+ };
42
+ const MEASURED_ON = {
43
+ search: 'training cases',
44
+ validation: 'validation cases',
45
+ test: 'test cases',
46
+ };
47
+ /** The writable edits of a finished run that still wait for the developer's yes or no. */
48
+ export const evalsEditsAwaitingAnswer = ({ reviewed, edits = [] }) => reviewed ? 0 : edits.filter(({ unavailable, decided }) => unavailable === undefined && !decided).length;
49
+ const editsToReview = (state) => state.step === 'review' ? evalsEditsAwaitingAnswer(state.review) : 0;
50
+ const BEST_DIFF = 'best.diff';
51
+ const unwritableEdits = (state, folder) => {
52
+ const edits = state.step === 'review' ? state.review.edits.filter(({ unavailable }) => unavailable !== undefined) : [];
53
+ if (edits.length === 0)
54
+ return undefined;
55
+ const reasons = edits.map(({ label, unavailable }) => `${label}: ${unavailable}`).join(' · ');
56
+ const diff = folder === undefined ? undefined : join(folder, BEST_DIFF);
57
+ const text = diff !== undefined && existsSync(diff) ? ` · its text is in ${diff}` : '';
58
+ return `strands dev cannot write ${plural(edits.length, 'edit')} (${reasons})${text}`;
59
+ };
60
+ /** Whether the run has an edit waiting for the developer's answer. */
61
+ export const evalsRunAwaitsReview = ({ runs = [] }, id) => runs.some((run) => run.id === id && editsToReview(run.state) > 0);
62
+ /** What a run is doing, as the line below the chat input and the status of the agent's tools say it. */
63
+ export const EVALS_RUN_PHASES = {
64
+ baseline: 'measuring your agent as it is',
65
+ proposing: 'proposing new versions',
66
+ scoring: 'measuring the new versions',
67
+ validating: 'checking the finalists on the validation cases',
68
+ testing: 'checking the winner on the test cases',
69
+ };
70
+ /** The score of the agent as it was and of the best version, on the cases the review measured them on. */
71
+ const scoreChange = (state) => {
72
+ if (state.step !== 'review')
73
+ return undefined;
74
+ const { baseline, best, measuredOn } = state.review;
75
+ const scores = best === baseline ? baseline.toFixed(2) : `${baseline.toFixed(2)} → ${best.toFixed(2)}`;
76
+ return `score ${scores} on the ${measuredOn}`;
77
+ };
78
+ /** A run of auto-optimize is the second of its two stages, and is named by the experiment that the first one made. */
79
+ const runTitle = (run, name) => run.fromAutoOptimize ? `auto-optimize 2/2 · ${run.experiment}` : name;
80
+ /** A finished run stays listed while an edit of it waits for an answer on screen; with nothing waiting, it goes. */
81
+ export const evalsOptimizeJobs = ({ runs = [] }) => runs.flatMap((run) => {
82
+ const { id, state } = run;
83
+ if (state.step === 'running') {
84
+ // The whole run in rollouts, so the count is full only when the finalists and the test have run too.
85
+ const { phase, rollouts } = state.progress;
86
+ const parts = [
87
+ runTitle(run, state.progress.run),
88
+ ...(phase ? [EVALS_RUN_PHASES[phase]] : []),
89
+ `${rollouts.done}/${rollouts.total} rollouts`,
90
+ ];
91
+ return [{ id, label: parts.join(' · ') }];
92
+ }
93
+ const edits = editsToReview(state);
94
+ return edits > 0 && state.step === 'review'
95
+ ? [{ id, label: `${state.review.run} · ${plural(edits, 'edit')} to review`, waiting: true }]
96
+ : [];
97
+ });
98
+ /** Every edit the screen would have offered, answered with apply: what auto-accept does in the developer's place. */
99
+ const autoAnswered = (review) => ({
100
+ ...review,
101
+ auto: true,
102
+ edits: review.edits.map((edit) => edit.unavailable === undefined ? { ...edit, accepted: true, decided: true } : edit),
103
+ });
104
+ /** The rollouts the plan allows in each part of the run: the same numbers its estimate adds up. */
105
+ const plannedRollouts = (plan) => evalsRolloutPhases({
106
+ split: plan.split,
107
+ repetitions: plan.repetitions,
108
+ iterations: plan.iterations,
109
+ width: plan.width,
110
+ finalists: plan.decision.finalists,
111
+ pareto: isEvalsPareto(plan.objective ?? NO_OBJECTIVE),
112
+ });
113
+ const startingProgress = (plan) => {
114
+ const { search, validation, test } = plannedRollouts(plan);
115
+ return {
116
+ run: 'starting',
117
+ record: '',
118
+ planned: 1 + plan.iterations * plan.width,
119
+ tried: 0,
120
+ rollouts: { done: 0, total: search + validation + test },
121
+ };
122
+ };
123
+ const sentence = (text) => (/[.!?]$/u.test(text.trim()) ? text.trim() : `${text.trim()}.`);
124
+ const testCheck = (test) => test && {
125
+ difference: test.difference,
126
+ cases: test.cases,
127
+ confidence: test.confidence,
128
+ ...(test.ci ? { range: test.ci } : {}),
129
+ };
130
+ const locateBaseCliEdit = (workspace, change) => {
131
+ const edit = change.knob.key === 'instructions'
132
+ ? { option: 'instructions', value: change.after, expected: change.before }
133
+ : (change.edit ?? { option: change.knob.option, value: change.after, expected: change.before });
134
+ const problem = baseCliEditProblem(edit);
135
+ if (problem)
136
+ return { unavailable: problem };
137
+ return {
138
+ target: userConfigPath(),
139
+ write: async () => {
140
+ await editBaseCliProfile(workspace, [edit]);
141
+ },
142
+ };
143
+ };
144
+ export class EvalsOptimize extends Store {
145
+ host;
146
+ experiments;
147
+ evaluators = 1;
148
+ usageProfile;
149
+ evaluatorNames = [];
150
+ resumed;
151
+ carried;
152
+ catalog = [];
153
+ page = { step: 'pick' };
154
+ shown;
155
+ entries = new Map();
156
+ runCount = 0;
157
+ changes = [];
158
+ constructor(host, experiments) {
159
+ super({ step: 'pick', runs: [] });
160
+ this.host = host;
161
+ this.experiments = experiments;
162
+ }
163
+ plan(experiment) {
164
+ void this.planFor(experiment);
165
+ }
166
+ reset() {
167
+ this.showPage({ step: 'pick' });
168
+ this.experiments.refresh();
169
+ }
170
+ toggleKnob(key) {
171
+ this.updatePlan((plan) => ({
172
+ ...plan,
173
+ knobs: plan.knobs.map((knob) => {
174
+ if (knob.key !== key || knob.unavailable)
175
+ return knob;
176
+ if (knob.kind === 'models' && !knob.enabled && (plan.models?.picked.length ?? 0) === 0)
177
+ return knob;
178
+ return { ...knob, enabled: !knob.enabled };
179
+ }),
180
+ }));
181
+ }
182
+ pickModel(id, picked) {
183
+ this.updatePlan((plan) => {
184
+ if (!plan.models || id === plan.models.current)
185
+ return plan;
186
+ const others = picked
187
+ ? [...new Set([...plan.models.picked, id])]
188
+ : plan.models.picked.filter((model) => model !== id);
189
+ return {
190
+ ...plan,
191
+ models: { ...plan.models, picked: others },
192
+ knobs: plan.knobs.map((knob) => knob.kind === 'models'
193
+ ? {
194
+ ...knob,
195
+ enabled: others.length > 0,
196
+ detail: others.length > 0 ? `${plural(others.length, 'other model')} to try` : 'choose models to try',
197
+ }
198
+ : knob),
199
+ };
200
+ });
201
+ }
202
+ setIterations(iterations) {
203
+ this.updatePlan((plan) => isEvalsBudgetValue('iterations', iterations) ? this.estimate({ ...plan, iterations }) : plan);
204
+ }
205
+ setRepetitions(repetitions) {
206
+ this.updatePlan((plan) => isEvalsBudgetValue('repetitions', repetitions) ? this.estimate({ ...plan, repetitions }) : plan);
207
+ }
208
+ setWidth(width) {
209
+ this.updatePlan((plan) => (isEvalsBudgetValue('width', width) ? this.estimate({ ...plan, width }) : plan));
210
+ }
211
+ setWorkers(workers) {
212
+ this.updatePlan((plan) => (isEvalsBudgetValue('workers', workers) ? { ...plan, workers } : plan));
213
+ }
214
+ setMaxRollouts(maxRollouts) {
215
+ this.updatePlan((plan) => isEvalsBudgetValue('maxRollouts', maxRollouts) ? this.estimate({ ...plan, maxRollouts }) : plan);
216
+ }
217
+ setSeed(seed) {
218
+ this.updatePlan((plan) => (Number.isSafeInteger(seed) ? { ...plan, seed } : plan));
219
+ }
220
+ setRerunPasses(rerunPasses) {
221
+ this.updatePlan((plan) => isEvalsBudgetValue('rerunPasses', rerunPasses) ? this.estimate({ ...plan, rerunPasses }) : plan);
222
+ }
223
+ setSplit(shares) {
224
+ if (evalsSharesProblem(shares))
225
+ return;
226
+ this.updatePlan(({ warning: _earlier, ...plan }) => {
227
+ const warning = evalsOptimizeWarning(plan.experiment.caseCount, shares);
228
+ return this.estimate({
229
+ ...plan,
230
+ split: evalsCaseSplit(plan.experiment.caseCount, shares),
231
+ ...(warning ? { warning } : {}),
232
+ });
233
+ });
234
+ }
235
+ /** Flags handed to strands-evals optimize run unchanged, such as --reflection-model. */
236
+ setPassed(passed) {
237
+ this.updatePlan(({ passed: _earlier, ...plan }) => (passed.length > 0 ? { ...plan, passed } : plan));
238
+ }
239
+ setObjective(objective) {
240
+ this.updatePlan(({ objectiveProblem: _problem, objectiveWarning: _warning, ...plan }) => this.estimate({ ...plan, ...objectiveFields(objective, this.evaluatorNames) }));
241
+ }
242
+ setDecision(setting, value) {
243
+ this.updatePlan((plan) => (setting === 'finalists'
244
+ ? isEvalsBudgetValue('finalists', value)
245
+ : plan.decisionChoices[setting].includes(value))
246
+ ? this.estimate({ ...plan, decision: { ...plan.decision, [setting]: value } })
247
+ : plan);
248
+ }
249
+ start({ fromAutoOptimize = false } = {}) {
250
+ const page = this.page;
251
+ if (page.step !== 'setup' || page.plan.objectiveProblem || page.plan.budgetProblem || page.plan.splitProblem)
252
+ return undefined;
253
+ const knobs = this.catalog.map((knob) => ({
254
+ ...knob,
255
+ enabled: page.plan.knobs.find(({ key }) => key === knob.key)?.enabled ?? false,
256
+ }));
257
+ const variables = evalsSpaceVariables(knobs, page.plan.models?.picked ?? []);
258
+ if (variables.length === 0)
259
+ return undefined;
260
+ const startedAt = Date.now();
261
+ const entry = this.addRun(page.plan.experiment.name, startedAt, {
262
+ step: 'running',
263
+ progress: startingProgress(page.plan),
264
+ });
265
+ entry.fromAutoOptimize = fromAutoOptimize;
266
+ this.showPage(entry.state, entry.id);
267
+ recordDevEvent('optimize_run_started');
268
+ void this.run(entry, page.plan, knobs, variables);
269
+ return entry.id;
270
+ }
271
+ stop(id) {
272
+ const entry = this.entries.get(id ?? this.shown ?? '');
273
+ if (entry?.state.step !== 'running' || !entry.abort || entry.stopping)
274
+ return;
275
+ entry.stopping = true;
276
+ entry.abort.abort();
277
+ }
278
+ accept(index, accepted, run) {
279
+ const entry = this.reviewedEntry(run);
280
+ if (entry?.state.step !== 'review' || entry.state.review.applied)
281
+ return;
282
+ if (entry.state.review.edits[index]?.unavailable) {
283
+ if (accepted)
284
+ void this.recheck(entry, true, index);
285
+ return;
286
+ }
287
+ if (!entry.writers.has(index))
288
+ return;
289
+ const { review } = entry.state;
290
+ this.updateRun(entry, {
291
+ step: 'review',
292
+ review: {
293
+ ...review,
294
+ edits: review.edits.map((edit, position) => (position === index ? { ...edit, accepted, decided: true } : edit)),
295
+ },
296
+ });
297
+ }
298
+ apply(run) {
299
+ const entry = this.reviewedEntry(run);
300
+ if (entry)
301
+ void this.applyAccepted(entry);
302
+ }
303
+ autoApplies() {
304
+ return this.host().settings?.().autoAcceptOptimizationResults ?? false;
305
+ }
306
+ finishReview(id) {
307
+ const entry = this.entries.get(id);
308
+ if (entry?.state.step !== 'review')
309
+ return;
310
+ this.updateRun(entry, { step: 'review', review: { ...entry.state.review, reviewed: true } });
311
+ this.settleReview(entry);
312
+ }
313
+ leaveReview(id) {
314
+ const entry = this.entries.get(id);
315
+ if (entry?.state.step !== 'review' || entry.state.review.reviewed)
316
+ return;
317
+ const offered = entry.state.review.edits.filter(({ unavailable }) => unavailable === undefined);
318
+ const answered = offered.filter(({ decided }) => decided).length;
319
+ // With one edit the status line says it all. With several, say where the answers given so far went.
320
+ if (answered === 0 || answered === offered.length)
321
+ return;
322
+ announce(this.host(), 'success', `optimize · run ${entry.state.review.run} · ${answered} of ${offered.length} edits answered · nothing is written until all are · ↓ Enter`);
323
+ }
324
+ /** Called with a run whose review is over, however it ended, so a question still on screen about it can go. */
325
+ onSettled;
326
+ /** Nothing of the run waits on the developer any more: its record goes, and so does a question still asking. */
327
+ settleReview(entry) {
328
+ if (entry.record)
329
+ void dropEvalsOptimizeRecord({ record: entry.record }).catch(() => undefined);
330
+ if (entry.record)
331
+ entry.reminder?.update('success', `optimize · run ${evalsOptimizationRunName(entry.record)} · reviewed`);
332
+ entry.reminder = undefined;
333
+ this.onSettled?.(entry.id);
334
+ }
335
+ resume() {
336
+ this.resumed ??= this.resumeRecords();
337
+ return this.resumed;
338
+ }
339
+ /** Says the last applied notice once to the chat that the write's reload opens, and to no later one. */
340
+ reannounce() {
341
+ const notice = this.carried;
342
+ this.carried = undefined;
343
+ if (notice && Date.now() - notice.at < notice.lasts)
344
+ announce(this.host(), notice.status, notice.text);
345
+ }
346
+ /** Called with a run that has edits to read, so a finished run shows them rather than waiting to be found. */
347
+ onReview;
348
+ /** Points accept and apply at one run without moving the panel to it. */
349
+ focusRun(id) {
350
+ if (this.entries.get(id)?.state.step !== 'review')
351
+ return false;
352
+ this.shown = id;
353
+ return true;
354
+ }
355
+ appliedChanges() {
356
+ return [...this.changes];
357
+ }
358
+ /** Several runs can wait for review at once, and the shown one moves as each finishes, so a walk names its own. */
359
+ reviewedEntry(run) {
360
+ return this.entries.get(run ?? this.shown ?? '');
361
+ }
362
+ addRun(experiment, startedAt, state) {
363
+ this.runCount += 1;
364
+ const entry = {
365
+ id: `run-${this.runCount}`,
366
+ experiment,
367
+ startedAt,
368
+ state,
369
+ abort: undefined,
370
+ stopping: false,
371
+ writers: new Map(),
372
+ changes: [],
373
+ sources: undefined,
374
+ fromAutoOptimize: false,
375
+ };
376
+ this.entries.set(entry.id, entry);
377
+ return entry;
378
+ }
379
+ showPage(page, shown) {
380
+ this.page = page;
381
+ this.shown = shown;
382
+ this.publish();
383
+ }
384
+ updateRun(entry, state) {
385
+ entry.state = state;
386
+ if (this.shown === entry.id)
387
+ this.page = state;
388
+ this.publish();
389
+ }
390
+ publish() {
391
+ const runs = [...this.entries.values()]
392
+ .sort((left, right) => right.startedAt - left.startedAt)
393
+ .map(({ id, experiment, record, fromAutoOptimize, state }) => ({
394
+ id,
395
+ experiment,
396
+ ...(record ? { record } : {}),
397
+ ...(fromAutoOptimize ? { fromAutoOptimize } : {}),
398
+ state,
399
+ }));
400
+ this.set({ ...this.page, runs });
401
+ }
402
+ watchSources(entry) {
403
+ if (entry.sources || entry.state.step !== 'review' || !entry.state.review.edits.some((edit) => edit.unavailable))
404
+ return;
405
+ let timer;
406
+ try {
407
+ entry.sources = watch(dirname(this.host().workspace.entrypoint), { persistent: false }, () => {
408
+ clearTimeout(timer);
409
+ timer = setTimeout(() => void this.recheck(entry, false), SOURCE_SETTLE_MS);
410
+ });
411
+ entry.sources.on('error', () => entry.sources?.close());
412
+ }
413
+ catch {
414
+ entry.sources = undefined;
415
+ }
416
+ }
417
+ async recheck(entry, accept, only) {
418
+ if (entry.state.step !== 'review' || entry.state.review.applied)
419
+ return;
420
+ const indexes = entry.state.review.edits.flatMap((edit, index) => edit.unavailable && (only === undefined || only === index) ? [index] : []);
421
+ const located = await Promise.all(indexes.map(async (index) => {
422
+ const change = entry.changes[index];
423
+ const location = change
424
+ ? await this.locate(change).catch((error) => ({ unavailable: errorMessage(error) }))
425
+ : undefined;
426
+ return { index, location };
427
+ }));
428
+ if (entry.state.step !== 'review')
429
+ return;
430
+ const { review } = entry.state;
431
+ const edits = review.edits.map((edit, index) => {
432
+ const location = located.find((found) => found.index === index)?.location;
433
+ if (!location || !edit.unavailable)
434
+ return edit;
435
+ if (!('write' in location))
436
+ return { ...edit, unavailable: location.unavailable };
437
+ entry.writers.set(index, location.write);
438
+ const { unavailable: _stale, ...rest } = edit;
439
+ return { ...rest, target: location.target, accepted: accept };
440
+ });
441
+ if (!edits.some((edit) => edit.unavailable)) {
442
+ entry.sources?.close();
443
+ entry.sources = undefined;
444
+ }
445
+ this.updateRun(entry, { step: 'review', review: { ...review, edits } });
446
+ }
447
+ updatePlan(change) {
448
+ if (this.page.step === 'setup')
449
+ this.showPage({ step: 'setup', plan: change(this.page.plan) });
450
+ }
451
+ estimate({ usage: _earlier, budgetProblem: _over, splitProblem: _split, ...plan }) {
452
+ const shape = {
453
+ split: plan.split,
454
+ repetitions: plan.repetitions,
455
+ iterations: plan.iterations,
456
+ width: plan.width,
457
+ finalists: plan.decision.finalists,
458
+ pareto: isEvalsPareto(plan.objective),
459
+ };
460
+ const { rollouts, judgeCalls, usage } = evalsRolloutEstimate({
461
+ ...shape,
462
+ evaluators: this.evaluators,
463
+ ...(this.usageProfile ? { profile: this.usageProfile } : {}),
464
+ });
465
+ const reserve = evalsRolloutReserve({ ...shape, rerunPasses: plan.rerunPasses });
466
+ const budgetProblem = evalsRolloutCapProblem(reserve, plan.maxRollouts);
467
+ const splitProblem = evalsSplitProblem(plan.split);
468
+ return {
469
+ ...plan,
470
+ rollouts,
471
+ judgeCalls,
472
+ ...(usage ? { usage } : {}),
473
+ ...(budgetProblem ? { budgetProblem } : {}),
474
+ ...(splitProblem ? { splitProblem } : {}),
475
+ };
476
+ }
477
+ async planFor(summary) {
478
+ try {
479
+ const { experiment, raw } = await readEvalsExperimentFile(summary.path);
480
+ this.catalog = await readEvalsKnobs(this.host().workspace, this.host().dependencies?.harnessDefaults);
481
+ this.usageProfile = await readEvalsUsageProfile(this.workspaceDirectory(), summary.name).catch(() => undefined);
482
+ const model = this.catalog.find((knob) => knob.kind === 'models' && !knob.unavailable);
483
+ const caseCount = experiment.cases.length;
484
+ const split = evalsCaseSplit(caseCount);
485
+ const splitChoices = evalsSplitChoices(caseCount);
486
+ const objectivePresets = evalsObjectivePresets(experiment.evaluators);
487
+ const warning = evalsOptimizeWarning(caseCount);
488
+ this.evaluators = evalsJudgeEvaluatorCount(raw.evaluators);
489
+ this.evaluatorNames = experiment.evaluators;
490
+ this.showPage({
491
+ step: 'setup',
492
+ plan: this.estimate({
493
+ experiment: { ...summary, caseCount },
494
+ knobs: this.catalog,
495
+ ...(typeof model?.current === 'string' ? { models: { current: model.current, picked: [] } } : {}),
496
+ ...objectiveFields(objectivePresets[0]?.objective ?? NO_OBJECTIVE, experiment.evaluators),
497
+ objectivePresets,
498
+ metrics: [...experiment.evaluators, ...EVALS_USAGE_METRICS],
499
+ split,
500
+ splitChoices,
501
+ testShare: EVALS_TEST_SHARES[0],
502
+ decision: EVALS_DECISION_DEFAULTS,
503
+ decisionChoices: EVALS_DECISION_CHOICES,
504
+ repetitions: REPETITIONS,
505
+ width: WIDTH,
506
+ workers: WORKERS,
507
+ iterations: DEFAULT_ITERATIONS,
508
+ maxRollouts: EVALS_OPTIMIZE_DEFAULTS.maxRollouts,
509
+ rerunPasses: EVALS_OPTIMIZE_DEFAULTS.rerunPasses,
510
+ rollouts: 0,
511
+ judgeCalls: 0,
512
+ ...(warning ? { warning } : {}),
513
+ }),
514
+ });
515
+ }
516
+ catch (error) {
517
+ this.showPage({ step: 'failed', message: errorMessage(error) });
518
+ }
519
+ }
520
+ workspaceDirectory() {
521
+ return evalsWorkspaceDirectory(this.host().workspace);
522
+ }
523
+ async resumeRecords() {
524
+ let records;
525
+ try {
526
+ await evalsWorkspaceReady(this.workspaceDirectory());
527
+ records = await readEvalsOptimizeRecords(this.workspaceDirectory());
528
+ }
529
+ catch (error) {
530
+ announce(this.host(), 'error', `optimize · an unfinished run cannot be read: ${errorMessage(error)}`);
531
+ return;
532
+ }
533
+ const known = new Set([...this.entries.values()].map(({ record }) => record));
534
+ await Promise.all(records.filter(({ record }) => !known.has(record)).map((saved) => this.continueRun(saved)));
535
+ }
536
+ async continueRun(saved) {
537
+ let entry;
538
+ try {
539
+ const plan = await this.recordedPlan(saved);
540
+ const knobs = await this.recordedKnobs(saved);
541
+ entry = this.addRun(plan.experiment.name, saved.startedAt, {
542
+ step: 'running',
543
+ progress: startingProgress(plan),
544
+ });
545
+ entry.record = saved.record;
546
+ entry.fromAutoOptimize = saved.fromAutoOptimize ?? false;
547
+ this.publish();
548
+ if (saved.awaitsReview)
549
+ return await this.restoreReview(entry, saved, knobs);
550
+ if (await isEvalsOptimizeAlive(saved))
551
+ return await this.follow(entry, plan, knobs, saved);
552
+ if (await hasEvalsRunResult(saved.record)) {
553
+ await this.finish(entry, saved.record, plan, knobs, false);
554
+ return await this.keepForReview(entry, saved.record, saved);
555
+ }
556
+ announce(this.host(), 'success', `optimize · ${plan.experiment.name} · resumed the run that stopped when strands dev closed`);
557
+ await this.run(entry, plan, knobs, [], saved);
558
+ }
559
+ catch (error) {
560
+ const failed = { step: 'failed', message: errorMessage(error), record: saved.record };
561
+ entry ??= this.addRun(basename(saved.experiment, '.json'), saved.startedAt, failed);
562
+ entry.record = saved.record;
563
+ this.updateRun(entry, failed);
564
+ announce(this.host(), 'error', `optimize · ${basename(saved.experiment, '.json')} could not resume · ask the chat why`);
565
+ await dropEvalsOptimizeRecord(saved);
566
+ }
567
+ }
568
+ async recordedPlan(saved) {
569
+ const caseCount = await evalsCaseCount(saved.experiment).catch(() => 0);
570
+ return {
571
+ experiment: { name: basename(saved.experiment, '.json'), path: saved.experiment, caseCount },
572
+ iterations: saved.iterations,
573
+ width: saved.width ?? WIDTH,
574
+ repetitions: saved.repetitions ?? REPETITIONS,
575
+ workers: saved.workers ?? WORKERS,
576
+ split: evalsCaseSplit(caseCount, saved.split ?? EVALS_OPTIMIZE_DEFAULTS.split),
577
+ maxRollouts: saved.maxRollouts ?? EVALS_OPTIMIZE_DEFAULTS.maxRollouts,
578
+ rerunPasses: saved.rerunPasses ?? EVALS_OPTIMIZE_DEFAULTS.rerunPasses,
579
+ ...(saved.seed === undefined ? {} : { seed: saved.seed }),
580
+ ...(saved.passed ? { passed: saved.passed } : {}),
581
+ decision: saved.decision ?? EVALS_DECISION_DEFAULTS,
582
+ ...(saved.objective ? { objective: saved.objective } : {}),
583
+ };
584
+ }
585
+ async recordedKnobs(saved) {
586
+ const knobs = await readEvalsKnobs(this.host().workspace, this.host().dependencies?.harnessDefaults);
587
+ const space = JSON.parse(await readFile(saved.space, 'utf8'));
588
+ const variables = isRecord(space) && Array.isArray(space.variables) ? space.variables : [];
589
+ const options = new Set(variables.filter(isRecord).map(({ option }) => option));
590
+ return knobs.map((knob) => ({ ...knob, enabled: options.has(knob.option) }));
591
+ }
592
+ async follow(entry, plan, knobs, saved) {
593
+ const abort = new AbortController();
594
+ entry.abort = abort;
595
+ entry.stopping = false;
596
+ const tail = this.track(entry, plan, saved.record);
597
+ try {
598
+ await waitForEvalsOptimize(saved, abort.signal);
599
+ }
600
+ finally {
601
+ await tail.stop();
602
+ entry.abort = undefined;
603
+ }
604
+ await this.finish(entry, saved.record, plan, knobs, abort.signal.aborted);
605
+ await this.keepForReview(entry, saved.record, saved);
606
+ }
607
+ /** Shows the progress of the run as its record grows, until the tail is stopped. */
608
+ track(entry, plan, record) {
609
+ const reader = evalsStudyReader({
610
+ run: evalsOptimizationRunName(record),
611
+ record,
612
+ planned: plannedRollouts(plan),
613
+ });
614
+ const show = () => this.updateRun(entry, {
615
+ step: 'running',
616
+ progress: { ...reader.progress(), planned: 1 + plan.iterations * plan.width },
617
+ });
618
+ const tail = tailEvalsRun(record, (line) => {
619
+ reader.push(line);
620
+ show();
621
+ });
622
+ show();
623
+ return tail;
624
+ }
625
+ async run(entry, plan, knobs, variables, continuing) {
626
+ const abort = new AbortController();
627
+ const startedAt = continuing?.startedAt ?? entry.startedAt;
628
+ const now = new Date(startedAt);
629
+ const shares = continuing ? continuing.split : evalsSplitShares(plan.split);
630
+ entry.abort = abort;
631
+ entry.stopping = false;
632
+ let record;
633
+ let cancelled = false;
634
+ let saving = Promise.resolve();
635
+ let saved;
636
+ const remember = (next) => {
637
+ saved = next;
638
+ saving = saving
639
+ .then(() => saveEvalsOptimizeRecord(next))
640
+ .catch((error) => announce(this.host(), 'error', `optimize · ${plan.experiment.name} · this run cannot continue after a restart: ${errorMessage(error)}`));
641
+ };
642
+ let tail;
643
+ this.updateRun(entry, { step: 'running', progress: startingProgress(plan) });
644
+ try {
645
+ const space = continuing?.space ?? (await this.writeSpace(plan, now, variables));
646
+ await runEvalsOptimization({
647
+ workspace: this.host().workspace,
648
+ experiment: plan.experiment.path,
649
+ settings: {
650
+ iterations: plan.iterations,
651
+ width: plan.width,
652
+ repetitions: plan.repetitions,
653
+ concurrency: plan.workers,
654
+ maxRollouts: plan.maxRollouts,
655
+ rerunPasses: plan.rerunPasses,
656
+ ...(plan.seed === undefined ? {} : { seed: plan.seed }),
657
+ decision: plan.decision,
658
+ ...(shares ? { split: shares } : {}),
659
+ },
660
+ ...(plan.passed ? { evalsArguments: plan.passed } : {}),
661
+ ...(plan.objective ? { objective: plan.objective } : {}),
662
+ space,
663
+ now: () => now,
664
+ background: true,
665
+ detached: true,
666
+ ...(continuing ? { continuing: continuing.record } : {}),
667
+ signal: abort.signal,
668
+ onSpawn: (pid) => {
669
+ if (saved)
670
+ remember({ ...saved, pid });
671
+ },
672
+ onStart: (path) => {
673
+ record = path;
674
+ entry.record = path;
675
+ remember({
676
+ version: 1,
677
+ experiment: plan.experiment.path,
678
+ record: path,
679
+ space,
680
+ iterations: plan.iterations,
681
+ width: plan.width,
682
+ repetitions: plan.repetitions,
683
+ workers: plan.workers,
684
+ ...(shares ? { split: shares } : {}),
685
+ ...(plan.objective ? { objective: plan.objective } : {}),
686
+ decision: plan.decision,
687
+ maxRollouts: plan.maxRollouts,
688
+ rerunPasses: plan.rerunPasses,
689
+ ...(plan.seed === undefined ? {} : { seed: plan.seed }),
690
+ ...(plan.passed ? { passed: plan.passed } : {}),
691
+ startedAt,
692
+ ...(entry.fromAutoOptimize ? { fromAutoOptimize: true } : {}),
693
+ });
694
+ tail = this.track(entry, plan, path);
695
+ },
696
+ }, this.host().dependencies);
697
+ await tail?.stop();
698
+ }
699
+ catch (error) {
700
+ await tail?.stop();
701
+ if (!entry.stopping) {
702
+ await saving;
703
+ if (record)
704
+ await dropEvalsOptimizeRecord({ record });
705
+ this.updateRun(entry, { step: 'failed', message: errorMessage(error), ...(record ? { record } : {}) });
706
+ announce(this.host(), 'error', `optimize · ${plan.experiment.name} stopped · ask the chat why`);
707
+ return;
708
+ }
709
+ cancelled = true;
710
+ }
711
+ finally {
712
+ entry.abort = undefined;
713
+ }
714
+ await saving;
715
+ if (cancelled && !record)
716
+ return this.reportCancelled(entry, plan);
717
+ await this.finish(entry, record, plan, knobs, cancelled);
718
+ await this.keepForReview(entry, record, saved);
719
+ }
720
+ async writeSpace(plan, now, variables) {
721
+ const home = evalsExperimentHome(this.workspaceDirectory(), plan.experiment.path);
722
+ const path = evalsOptimizationFiles(home, evalsRunStamp(now)).space;
723
+ await mkdir(dirname(path), { recursive: true });
724
+ await writeFile(path, `${JSON.stringify({ variables }, null, 2)}\n`);
725
+ return path;
726
+ }
727
+ async finish(entry, record, plan, knobs, cancelled) {
728
+ const name = evalsOptimizationRunName(record);
729
+ let outcome;
730
+ try {
731
+ outcome = await readEvalsStudy(record);
732
+ }
733
+ catch (error) {
734
+ if (cancelled)
735
+ return this.reportCancelled(entry, plan, record);
736
+ this.updateRun(entry, { step: 'failed', message: errorMessage(error), record });
737
+ announce(this.host(), 'error', `optimize · run ${name} could not be read · ask the chat why`);
738
+ return;
739
+ }
740
+ if (outcome.ended === 'stopped' && outcome.error && !cancelled) {
741
+ const log = evalsOptimizationOf(record).log;
742
+ this.updateRun(entry, {
743
+ step: 'failed',
744
+ message: `${sentence(outcome.error)} The full optimizer output is in ${log}.`,
745
+ record,
746
+ });
747
+ announce(this.host(), 'error', `optimize · run ${name} failed · ask the chat why`);
748
+ return;
749
+ }
750
+ // Read as the run ends; a stopped run's best version was never validated, so it is never applied unasked.
751
+ const auto = !cancelled && outcome.ended === 'finished' && this.autoApplies();
752
+ let ready;
753
+ let ended;
754
+ try {
755
+ // Only a run that produced an edit worth applying opens the review; the rest just say they finished.
756
+ ready = await this.enterReview(entry, outcome, record, knobs, auto);
757
+ const folder = await evalsRunFolder(record).catch(() => undefined);
758
+ const unwritten = unwritableEdits(entry.state, folder);
759
+ ended = {
760
+ lead: [`${runTitle(entry, `optimize · run ${name}`)} finished`, scoreChange(entry.state)]
761
+ .filter((part) => part !== undefined)
762
+ .join(' · '),
763
+ ...(unwritten === undefined ? {} : { unwritten }),
764
+ link: evalsLinkText(this.host(), { view: 'optimization', record }, folder),
765
+ };
766
+ // Auto-accept writes the edits next, and that notice is the one of the end: the score with what was written.
767
+ if (!auto || ready === 0) {
768
+ const ending = ready > 0 ? `showing ${plural(ready, 'edit')}` : unwritten === undefined ? 'no edits to apply' : undefined;
769
+ const told = [ended.lead, ending, unwritten].filter((part) => part !== undefined).join(' · ');
770
+ announce(this.host(), 'success', `${told}${ended.link}`);
771
+ }
772
+ }
773
+ catch (error) {
774
+ if (cancelled)
775
+ return this.reportCancelled(entry, plan, record);
776
+ this.updateRun(entry, { step: 'failed', message: errorMessage(error), record });
777
+ announce(this.host(), 'error', `optimize · run ${name} could not be read · ask the chat why`);
778
+ return;
779
+ }
780
+ if (ready === 0)
781
+ return;
782
+ // With auto-accept the edits are answered already, so there is nothing to show: they are written here.
783
+ if (auto)
784
+ await this.applyAccepted(entry, ended);
785
+ else
786
+ this.onReview?.(entry.id);
787
+ }
788
+ /** Puts a finished run in review and counts its writable edits; `auto` answers each with apply. */
789
+ async enterReview(entry, outcome, record, knobs, auto = false) {
790
+ const writers = new Map();
791
+ const edits = [];
792
+ const changes = evalsKnobChanges(knobs, outcome.baseline.params, outcome.best?.params ?? {});
793
+ for (const change of changes) {
794
+ const located = await this.locate(change);
795
+ const writable = 'write' in located;
796
+ if (writable)
797
+ writers.set(edits.length, located.write);
798
+ edits.push({
799
+ knob: change.knob.key,
800
+ kind: change.kind,
801
+ label: change.knob.label,
802
+ before: change.before,
803
+ after: change.after,
804
+ accepted: writable,
805
+ ...(writable ? { target: located.target } : { unavailable: located.unavailable }),
806
+ ...(change.added ? { added: change.added } : {}),
807
+ });
808
+ }
809
+ const baseline = outcome.baseline.score ?? 0;
810
+ const check = testCheck(outcome.test);
811
+ const review = {
812
+ run: evalsOptimizationRunName(record),
813
+ record,
814
+ baseline,
815
+ best: outcome.best?.score ?? baseline,
816
+ measuredOn: MEASURED_ON[outcome.measuredOn],
817
+ edits,
818
+ ...(check ? { testCheck: check } : {}),
819
+ };
820
+ entry.writers = writers;
821
+ entry.changes = changes;
822
+ const ready = edits.filter(({ unavailable }) => unavailable === undefined).length;
823
+ recordDevEvent('optimize_run_finished');
824
+ this.updateRun(entry, { step: 'review', review: auto && ready > 0 ? autoAnswered(review) : review });
825
+ this.watchSources(entry);
826
+ return ready;
827
+ }
828
+ /** Keeps the record of a run with an edit still to answer, so its review comes back when strands dev opens again. */
829
+ async keepForReview(entry, record, saved) {
830
+ if (!saved || editsToReview(entry.state) === 0)
831
+ return dropEvalsOptimizeRecord({ record });
832
+ const { pid: _ended, ...finished } = saved;
833
+ // An unmarked record reads as a run that ended while strands dev was closed, which brings its review back too.
834
+ await saveEvalsOptimizeRecord({ ...finished, awaitsReview: true }).catch(() => undefined);
835
+ if (editsToReview(entry.state) === 0)
836
+ await dropEvalsOptimizeRecord({ record });
837
+ }
838
+ /** Brings back a review strands dev closed on, on the status line rather than over the new chat. */
839
+ async restoreReview(entry, saved, knobs) {
840
+ const name = evalsOptimizationRunName(saved.record);
841
+ const ready = await this.enterReview(entry, await readEvalsStudy(saved.record), saved.record, knobs);
842
+ if (ready === 0) {
843
+ announce(this.host(), 'success', `optimize · run ${name} · its edits no longer fit the agent as it is now`);
844
+ return dropEvalsOptimizeRecord(saved);
845
+ }
846
+ entry.reminder = this.host().context?.report('success', `optimize · run ${name} · ${plural(ready, 'edit')} still to review · ↓ Enter`);
847
+ }
848
+ reportCancelled(entry, plan, record) {
849
+ this.updateRun(entry, {
850
+ step: 'cancelled',
851
+ experiment: plan.experiment.name,
852
+ ...(record ? { run: evalsOptimizationRunName(record) } : {}),
853
+ });
854
+ announce(this.host(), 'success', `optimize · ${plan.experiment.name} cancelled · the agent source is unchanged`);
855
+ }
856
+ async locate(change) {
857
+ const { workspace } = this.host();
858
+ if (await isProfileBaseCli(workspace))
859
+ return locateBaseCliEdit(workspace, change);
860
+ if (change.knob.key === 'instructions')
861
+ return locateEvalsEdit({
862
+ root: workspace.root,
863
+ entrypoint: workspace.entrypoint,
864
+ before: change.before,
865
+ after: change.after,
866
+ });
867
+ const edit = change.edit ?? { option: change.knob.option, value: change.after, expected: change.before };
868
+ return {
869
+ target: relative(workspace.root, workspace.entrypoint) || workspace.entrypoint,
870
+ write: async () => {
871
+ await editAgentOptions(workspace, [edit]);
872
+ },
873
+ };
874
+ }
875
+ /** `ended` is the run that just finished under auto-accept, which this notice then tells the end of as well. */
876
+ async applyAccepted(entry, ended) {
877
+ // A run's edits are written once: the walk on screen and the agent's apply tool can both reach here for one run.
878
+ if (entry.state.step !== 'review' || entry.state.review.applied)
879
+ return;
880
+ const { review } = entry.state;
881
+ const accepted = review.edits.flatMap((edit, index) => {
882
+ const write = entry.writers.get(index);
883
+ return edit.accepted && write ? [{ edit, write }] : [];
884
+ });
885
+ const change = {
886
+ run: review.run,
887
+ experiment: entry.experiment,
888
+ appliedAt: Date.now(),
889
+ baseline: review.baseline,
890
+ best: review.best,
891
+ measuredOn: review.measuredOn,
892
+ ...(review.testCheck ? { testCheck: review.testCheck } : {}),
893
+ edits: accepted.map(({ edit }) => edit),
894
+ ...(review.auto ? { auto: true } : {}),
895
+ };
896
+ const recorded = accepted.length > 0 ? this.changes.push(change) - 1 : undefined;
897
+ const applied = [];
898
+ const written = [];
899
+ let applyError;
900
+ for (const { edit, write } of accepted) {
901
+ const target = edit.target ?? edit.label;
902
+ try {
903
+ await write(edit.after);
904
+ applied.push(target);
905
+ written.push(edit);
906
+ }
907
+ catch (error) {
908
+ applyError = `Could not change ${target}: ${errorMessage(error)} Change it by hand, then run the experiment again from /experiment.`;
909
+ break;
910
+ }
911
+ }
912
+ if (written.length > 0)
913
+ recordDevEvent('optimize_edits_applied');
914
+ if (recorded !== undefined)
915
+ this.changes[recorded] = { ...change, edits: written, ...(applyError ? { error: applyError } : {}) };
916
+ // The writes are awaited, and the review moves on meanwhile (the walk marks it reviewed), so add to what it is now.
917
+ const current = entry.state.step === 'review' ? entry.state.review : review;
918
+ // Writing ends the review, whoever asked for it: the walk on screen, or the agent's apply tool.
919
+ this.updateRun(entry, {
920
+ step: 'review',
921
+ review: { ...current, applied, reviewed: true, ...(applyError ? { applyError } : {}) },
922
+ });
923
+ this.settleReview(entry);
924
+ const did = applied.length > 0 ? `applied ${applied.join(', ')}` : 'changed nothing';
925
+ // Nobody saw these edits before they were written, so the notice says who applied them.
926
+ const changed = review.auto ? `auto-accept ${did}` : did;
927
+ const told = [
928
+ ended?.lead ?? 'optimize',
929
+ changed,
930
+ ended?.unwritten,
931
+ applyError ?? 'run the experiment again from /experiment to check your agent',
932
+ ].filter((part) => part !== undefined);
933
+ const notice = {
934
+ status: applyError ? 'error' : 'success',
935
+ text: `${told.join(' · ')}${ended?.link ?? ''}`,
936
+ };
937
+ if (applied.length > 0)
938
+ this.carried = { ...notice, at: Date.now(), lasts: review.auto ? AUTO_RELOAD_WINDOW_MS : RELOAD_WINDOW_MS };
939
+ announce(this.host(), notice.status, notice.text);
940
+ }
941
+ }
942
+ //# sourceMappingURL=optimize-session.js.map