@turri-dev/cli 0.4.3-next.aea3ca1 → 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 (481) hide show
  1. package/README.md +26 -3
  2. package/dist/banner.js +259 -0
  3. package/dist/capture-cli.js +59 -0
  4. package/dist/chat-commands.js +9 -63
  5. package/dist/chat-models.js +17 -15
  6. package/dist/chat-tab-header.js +90 -0
  7. package/dist/chat-tabs.js +100 -0
  8. package/dist/chat-terminal.js +162 -54
  9. package/dist/chat-waiting.js +0 -20
  10. package/dist/cli-options.js +11 -7
  11. package/dist/cli-root.js +141 -0
  12. package/dist/cli.js +40 -28
  13. package/dist/conform-cli.js +4 -6
  14. package/dist/cultivate-cli.js +65 -97
  15. package/dist/doctor-cli.js +99 -0
  16. package/dist/drift-cli.js +2 -7
  17. package/dist/entry-renderers.js +107 -0
  18. package/dist/extension.js +14 -3211
  19. package/dist/init-config-cli.js +218 -0
  20. package/dist/launch-cli.js +55 -91
  21. package/dist/lineage-cli.js +2 -4
  22. package/dist/loop-cli.js +118 -233
  23. package/dist/panel-view.js +409 -0
  24. package/dist/parse-cli.js +5 -2
  25. package/dist/pi-launch.js +39 -13
  26. package/dist/pi-themes.js +21 -0
  27. package/dist/plain-code-blocks.js +56 -0
  28. package/dist/pointer-hover.js +48 -0
  29. package/dist/print-mode.js +20 -0
  30. package/dist/question-dialog.js +26 -3
  31. package/dist/quiet.js +7 -106
  32. package/dist/regenerate/diff-view.js +6 -87
  33. package/dist/regenerate/jobs-tree.js +7 -18
  34. package/dist/regenerate/side-panel.js +158 -22
  35. package/dist/regenerate/spec-map-view.js +25 -70
  36. package/dist/regenerate-cli.js +7 -11
  37. package/dist/skill-progress.js +25 -0
  38. package/dist/skill-report.js +52 -0
  39. package/dist/terminal-marks.js +21 -0
  40. package/dist/terminal-notifications.js +219 -0
  41. package/dist/terminal-view.js +239 -0
  42. package/dist/turri-versions.js +64 -6
  43. package/docs/README.md +4 -2
  44. package/docs/capture.md +126 -0
  45. package/docs/chats.md +14 -10
  46. package/docs/claude-subscription.md +1 -1
  47. package/docs/config.md +20 -8
  48. package/docs/development.md +30 -61
  49. package/docs/headless.md +3 -1
  50. package/docs/hosting.md +3 -251
  51. package/docs/installation.md +5 -3
  52. package/docs/launch.md +3 -3
  53. package/docs/regenerating.md +1 -1
  54. package/docs/sandbox.md +4 -2
  55. package/docs/sentinel.md +13 -13
  56. package/docs/theming.md +3 -3
  57. package/docs/using.md +14 -6
  58. package/package.json +13 -31
  59. package/dist/ask.d.ts +0 -90
  60. package/dist/ask.js +0 -170
  61. package/dist/background-skills.d.ts +0 -53
  62. package/dist/background-skills.js +0 -121
  63. package/dist/bedrock-region.d.ts +0 -66
  64. package/dist/bedrock-region.js +0 -144
  65. package/dist/brand.d.ts +0 -13
  66. package/dist/btw.d.ts +0 -69
  67. package/dist/btw.js +0 -174
  68. package/dist/chat-commands.d.ts +0 -25
  69. package/dist/chat-idle.d.ts +0 -7
  70. package/dist/chat-idle.js +0 -20
  71. package/dist/chat-models.d.ts +0 -22
  72. package/dist/chat-records.d.ts +0 -50
  73. package/dist/chat-records.js +0 -107
  74. package/dist/chat-scope.d.ts +0 -14
  75. package/dist/chat-scope.js +0 -15
  76. package/dist/chat-skills.d.ts +0 -17
  77. package/dist/chat-skills.js +0 -18
  78. package/dist/chat-terminal.d.ts +0 -24
  79. package/dist/chat-ui.d.ts +0 -33
  80. package/dist/chat-waiting.d.ts +0 -67
  81. package/dist/chats.d.ts +0 -338
  82. package/dist/chats.js +0 -996
  83. package/dist/cli-options.d.ts +0 -24
  84. package/dist/cli.d.ts +0 -9
  85. package/dist/config-edit.d.ts +0 -83
  86. package/dist/config-edit.js +0 -390
  87. package/dist/config.d.ts +0 -415
  88. package/dist/config.js +0 -757
  89. package/dist/conform-cli.d.ts +0 -1
  90. package/dist/conformance-switch.d.ts +0 -25
  91. package/dist/conformance-switch.js +0 -86
  92. package/dist/cultivate-cli.d.ts +0 -1
  93. package/dist/doctor-tool.d.ts +0 -11
  94. package/dist/doctor-tool.js +0 -33
  95. package/dist/drift-cli.d.ts +0 -1
  96. package/dist/environment.d.ts +0 -37
  97. package/dist/environment.js +0 -109
  98. package/dist/extension.d.ts +0 -208
  99. package/dist/genome.d.ts +0 -77
  100. package/dist/genome.js +0 -288
  101. package/dist/graph.d.ts +0 -52
  102. package/dist/graph.js +0 -247
  103. package/dist/host-session.d.ts +0 -112
  104. package/dist/host-session.js +0 -103
  105. package/dist/host.d.ts +0 -40
  106. package/dist/host.js +0 -54
  107. package/dist/identity.d.ts +0 -7
  108. package/dist/identity.js +0 -74
  109. package/dist/init-config.d.ts +0 -169
  110. package/dist/init-config.js +0 -840
  111. package/dist/installed-providers.d.ts +0 -40
  112. package/dist/installed-providers.js +0 -98
  113. package/dist/jellyfish.d.ts +0 -40
  114. package/dist/judge.d.ts +0 -25
  115. package/dist/judge.js +0 -62
  116. package/dist/launch-agent.d.ts +0 -62
  117. package/dist/launch-agent.js +0 -339
  118. package/dist/launch-cli.d.ts +0 -1
  119. package/dist/launch-session.d.ts +0 -68
  120. package/dist/launch-session.js +0 -225
  121. package/dist/launch-tools.d.ts +0 -28
  122. package/dist/launch-tools.js +0 -72
  123. package/dist/launch-track.d.ts +0 -175
  124. package/dist/launch-track.js +0 -497
  125. package/dist/lineage-cli.d.ts +0 -1
  126. package/dist/loop-cli.d.ts +0 -35
  127. package/dist/loop-tools.d.ts +0 -103
  128. package/dist/loop-tools.js +0 -357
  129. package/dist/model-check.d.ts +0 -72
  130. package/dist/model-check.js +0 -162
  131. package/dist/module-report.d.ts +0 -9
  132. package/dist/new-project.d.ts +0 -5
  133. package/dist/new-project.js +0 -31
  134. package/dist/notice.d.ts +0 -115
  135. package/dist/notice.js +0 -61
  136. package/dist/parse-cli.d.ts +0 -1
  137. package/dist/parse-tool.d.ts +0 -9
  138. package/dist/parse-tool.js +0 -33
  139. package/dist/pi-launch.d.ts +0 -1
  140. package/dist/pi-settings.d.ts +0 -4
  141. package/dist/pi.d.ts +0 -248
  142. package/dist/pi.js +0 -889
  143. package/dist/picture-row.d.ts +0 -10
  144. package/dist/plain/check.d.ts +0 -63
  145. package/dist/plain/check.js +0 -236
  146. package/dist/plain/concepts.d.ts +0 -37
  147. package/dist/plain/concepts.js +0 -283
  148. package/dist/plain/cycles.d.ts +0 -21
  149. package/dist/plain/cycles.js +0 -190
  150. package/dist/plain/errors.d.ts +0 -26
  151. package/dist/plain/errors.js +0 -50
  152. package/dist/plain/files.d.ts +0 -47
  153. package/dist/plain/files.js +0 -161
  154. package/dist/plain/graph.d.ts +0 -107
  155. package/dist/plain/graph.js +0 -194
  156. package/dist/plain/highlight.d.ts +0 -43
  157. package/dist/plain/highlight.js +0 -196
  158. package/dist/plain/index.d.ts +0 -18
  159. package/dist/plain/index.js +0 -18
  160. package/dist/plain/liquid.d.ts +0 -22
  161. package/dist/plain/liquid.js +0 -124
  162. package/dist/plain/markdown.d.ts +0 -103
  163. package/dist/plain/markdown.js +0 -330
  164. package/dist/plain/module-concepts.d.ts +0 -32
  165. package/dist/plain/module-concepts.js +0 -80
  166. package/dist/plain/parser.d.ts +0 -163
  167. package/dist/plain/parser.js +0 -930
  168. package/dist/plain/plain.tmLanguage.json +0 -150
  169. package/dist/plain/project.d.ts +0 -48
  170. package/dist/plain/project.js +0 -155
  171. package/dist/plain/spec.d.ts +0 -152
  172. package/dist/plain/spec.js +0 -265
  173. package/dist/plain/stdlib.d.ts +0 -16
  174. package/dist/plain/stdlib.js +0 -48
  175. package/dist/plain/test-plain-file.d.ts +0 -59
  176. package/dist/plain/test-plain-file.js +0 -232
  177. package/dist/plain-files.d.ts +0 -21
  178. package/dist/plain-files.js +0 -156
  179. package/dist/question-dialog.d.ts +0 -55
  180. package/dist/questioning.d.ts +0 -55
  181. package/dist/questioning.js +0 -109
  182. package/dist/quiet.d.ts +0 -34
  183. package/dist/regenerate/activity.d.ts +0 -227
  184. package/dist/regenerate/activity.js +0 -250
  185. package/dist/regenerate/agent-env.d.ts +0 -51
  186. package/dist/regenerate/agent-env.js +0 -311
  187. package/dist/regenerate/agent-shell.d.ts +0 -54
  188. package/dist/regenerate/agent-shell.js +0 -121
  189. package/dist/regenerate/arbiter.d.ts +0 -68
  190. package/dist/regenerate/arbiter.js +0 -133
  191. package/dist/regenerate/audit.d.ts +0 -69
  192. package/dist/regenerate/audit.js +0 -212
  193. package/dist/regenerate/base-folder.d.ts +0 -70
  194. package/dist/regenerate/base-folder.js +0 -186
  195. package/dist/regenerate/cases.d.ts +0 -12
  196. package/dist/regenerate/cases.js +0 -149
  197. package/dist/regenerate/change-view.d.ts +0 -23
  198. package/dist/regenerate/change-view.js +0 -153
  199. package/dist/regenerate/chunk-plan.d.ts +0 -217
  200. package/dist/regenerate/chunk-plan.js +0 -937
  201. package/dist/regenerate/codebase.d.ts +0 -21
  202. package/dist/regenerate/codebase.js +0 -75
  203. package/dist/regenerate/command-check.d.ts +0 -66
  204. package/dist/regenerate/command-check.js +0 -508
  205. package/dist/regenerate/compaction.d.ts +0 -13
  206. package/dist/regenerate/compaction.js +0 -20
  207. package/dist/regenerate/confine.d.ts +0 -69
  208. package/dist/regenerate/confine.js +0 -311
  209. package/dist/regenerate/conform.d.ts +0 -66
  210. package/dist/regenerate/conform.js +0 -132
  211. package/dist/regenerate/conformance-agents.d.ts +0 -388
  212. package/dist/regenerate/conformance-agents.js +0 -1162
  213. package/dist/regenerate/conformance.d.ts +0 -191
  214. package/dist/regenerate/conformance.js +0 -1035
  215. package/dist/regenerate/conversation-writes.d.ts +0 -10
  216. package/dist/regenerate/conversation-writes.js +0 -100
  217. package/dist/regenerate/credentials.d.ts +0 -18
  218. package/dist/regenerate/credentials.js +0 -88
  219. package/dist/regenerate/debug-log.d.ts +0 -56
  220. package/dist/regenerate/debug-log.js +0 -236
  221. package/dist/regenerate/debugger.d.ts +0 -36
  222. package/dist/regenerate/debugger.js +0 -133
  223. package/dist/regenerate/delivery.d.ts +0 -2
  224. package/dist/regenerate/diagnose-job.d.ts +0 -2
  225. package/dist/regenerate/diagnose-job.js +0 -40
  226. package/dist/regenerate/diagnose.d.ts +0 -46
  227. package/dist/regenerate/diagnose.js +0 -92
  228. package/dist/regenerate/diff-view.d.ts +0 -64
  229. package/dist/regenerate/drift.d.ts +0 -120
  230. package/dist/regenerate/drift.js +0 -285
  231. package/dist/regenerate/environment-error.d.ts +0 -167
  232. package/dist/regenerate/environment-error.js +0 -342
  233. package/dist/regenerate/failure-reports.d.ts +0 -28
  234. package/dist/regenerate/failure-reports.js +0 -79
  235. package/dist/regenerate/job-log.d.ts +0 -30
  236. package/dist/regenerate/job-log.js +0 -105
  237. package/dist/regenerate/job-panel.d.ts +0 -122
  238. package/dist/regenerate/job-panel.js +0 -339
  239. package/dist/regenerate/jobs-tree.d.ts +0 -75
  240. package/dist/regenerate/jobs.d.ts +0 -231
  241. package/dist/regenerate/jobs.js +0 -522
  242. package/dist/regenerate/lanes.d.ts +0 -16
  243. package/dist/regenerate/lanes.js +0 -32
  244. package/dist/regenerate/launch.d.ts +0 -256
  245. package/dist/regenerate/launch.js +0 -689
  246. package/dist/regenerate/ledger-view.d.ts +0 -87
  247. package/dist/regenerate/ledger-view.js +0 -325
  248. package/dist/regenerate/ledger.d.ts +0 -368
  249. package/dist/regenerate/ledger.js +0 -357
  250. package/dist/regenerate/lineage.d.ts +0 -105
  251. package/dist/regenerate/lineage.js +0 -485
  252. package/dist/regenerate/list-arguments.d.ts +0 -21
  253. package/dist/regenerate/list-arguments.js +0 -121
  254. package/dist/regenerate/loop.d.ts +0 -423
  255. package/dist/regenerate/loop.js +0 -2079
  256. package/dist/regenerate/masking.d.ts +0 -19
  257. package/dist/regenerate/masking.js +0 -95
  258. package/dist/regenerate/model-names.d.ts +0 -33
  259. package/dist/regenerate/model-names.js +0 -92
  260. package/dist/regenerate/notes.d.ts +0 -159
  261. package/dist/regenerate/notes.js +0 -446
  262. package/dist/regenerate/os-sandbox.d.ts +0 -93
  263. package/dist/regenerate/os-sandbox.js +0 -283
  264. package/dist/regenerate/panel-dock.d.ts +0 -23
  265. package/dist/regenerate/paths.d.ts +0 -110
  266. package/dist/regenerate/paths.js +0 -190
  267. package/dist/regenerate/plain-palette.d.ts +0 -34
  268. package/dist/regenerate/prompt.d.ts +0 -230
  269. package/dist/regenerate/prompt.js +0 -741
  270. package/dist/regenerate/pulse-files.d.ts +0 -14
  271. package/dist/regenerate/pulse-files.js +0 -63
  272. package/dist/regenerate/records.d.ts +0 -132
  273. package/dist/regenerate/records.js +0 -327
  274. package/dist/regenerate/regenerate.d.ts +0 -106
  275. package/dist/regenerate/regenerate.js +0 -660
  276. package/dist/regenerate/regression.d.ts +0 -58
  277. package/dist/regenerate/regression.js +0 -188
  278. package/dist/regenerate/renames.d.ts +0 -42
  279. package/dist/regenerate/renames.js +0 -185
  280. package/dist/regenerate/requires.d.ts +0 -117
  281. package/dist/regenerate/requires.js +0 -377
  282. package/dist/regenerate/resources.d.ts +0 -57
  283. package/dist/regenerate/resources.js +0 -162
  284. package/dist/regenerate/scripts-being-written.d.ts +0 -19
  285. package/dist/regenerate/scripts-being-written.js +0 -30
  286. package/dist/regenerate/self-check.d.ts +0 -29
  287. package/dist/regenerate/self-check.js +0 -119
  288. package/dist/regenerate/services.d.ts +0 -28
  289. package/dist/regenerate/services.js +0 -158
  290. package/dist/regenerate/shell.d.ts +0 -91
  291. package/dist/regenerate/shell.js +0 -320
  292. package/dist/regenerate/side-panel.d.ts +0 -59
  293. package/dist/regenerate/spec-map-view.d.ts +0 -139
  294. package/dist/regenerate/spec-map.d.ts +0 -160
  295. package/dist/regenerate/spec-map.js +0 -596
  296. package/dist/regenerate/spec-steps.d.ts +0 -180
  297. package/dist/regenerate/spec-steps.js +0 -729
  298. package/dist/regenerate/standing.d.ts +0 -28
  299. package/dist/regenerate/standing.js +0 -30
  300. package/dist/regenerate/state.d.ts +0 -21
  301. package/dist/regenerate/state.js +0 -10
  302. package/dist/regenerate/steering.d.ts +0 -56
  303. package/dist/regenerate/steering.js +0 -119
  304. package/dist/regenerate/stop-report.d.ts +0 -43
  305. package/dist/regenerate/stop-report.js +0 -160
  306. package/dist/regenerate/submit-work.d.ts +0 -44
  307. package/dist/regenerate/submit-work.js +0 -76
  308. package/dist/regenerate/test-kinds.d.ts +0 -85
  309. package/dist/regenerate/test-kinds.js +0 -171
  310. package/dist/regenerate/test-scripts.d.ts +0 -235
  311. package/dist/regenerate/test-scripts.js +0 -843
  312. package/dist/regenerate/testing-steps.d.ts +0 -52
  313. package/dist/regenerate/testing-steps.js +0 -129
  314. package/dist/regenerate/testing.d.ts +0 -150
  315. package/dist/regenerate/testing.js +0 -438
  316. package/dist/regenerate/transcript-view.d.ts +0 -21
  317. package/dist/regenerate/unit-gate.d.ts +0 -27
  318. package/dist/regenerate/unit-gate.js +0 -20
  319. package/dist/regenerate/unit-review.d.ts +0 -152
  320. package/dist/regenerate/unit-review.js +0 -361
  321. package/dist/regenerate/web.d.ts +0 -61
  322. package/dist/regenerate/web.js +0 -256
  323. package/dist/regenerate/workspace.d.ts +0 -12
  324. package/dist/regenerate/workspace.js +0 -99
  325. package/dist/regenerate-cli.d.ts +0 -1
  326. package/dist/resume-line.d.ts +0 -5
  327. package/dist/review/live.d.ts +0 -72
  328. package/dist/review/live.js +0 -166
  329. package/dist/rules.d.ts +0 -20
  330. package/dist/rules.js +0 -47
  331. package/dist/run-report.d.ts +0 -88
  332. package/dist/run-report.js +0 -338
  333. package/dist/screen-padding.d.ts +0 -28
  334. package/dist/self-invocation.d.ts +0 -36
  335. package/dist/self-invocation.js +0 -137
  336. package/dist/sentinel-chat.d.ts +0 -19
  337. package/dist/sentinel-chat.js +0 -221
  338. package/dist/sentinel-check.d.ts +0 -36
  339. package/dist/sentinel-check.js +0 -78
  340. package/dist/sentinel.d.ts +0 -107
  341. package/dist/sentinel.js +0 -599
  342. package/dist/settings.d.ts +0 -45
  343. package/dist/settings.js +0 -378
  344. package/dist/setup.d.ts +0 -97
  345. package/dist/setup.js +0 -428
  346. package/dist/skill-progress.d.ts +0 -46
  347. package/dist/skill.d.ts +0 -102
  348. package/dist/skill.js +0 -147
  349. package/dist/skills.d.ts +0 -54
  350. package/dist/skills.js +0 -111
  351. package/dist/spawn-async.d.ts +0 -18
  352. package/dist/spawn-async.js +0 -35
  353. package/dist/stack.d.ts +0 -80
  354. package/dist/stack.js +0 -206
  355. package/dist/stdlib.d.ts +0 -43
  356. package/dist/stdlib.js +0 -118
  357. package/dist/surface.d.ts +0 -5
  358. package/dist/surface.js +0 -18
  359. package/dist/terminal-images.d.ts +0 -2
  360. package/dist/test-plain-files.d.ts +0 -41
  361. package/dist/test-plain-files.js +0 -172
  362. package/dist/tools.d.ts +0 -101
  363. package/dist/tools.js +0 -242
  364. package/dist/turri-versions.d.ts +0 -71
  365. package/genome/rules/bullet-continuation.md +0 -61
  366. package/genome/rules/concise-specs-examples.md +0 -460
  367. package/genome/rules/concise-specs-integration-examples.md +0 -281
  368. package/genome/rules/concise-specs.md +0 -80
  369. package/genome/rules/definitions.md +0 -107
  370. package/genome/rules/examples/integration-embedded-testing/run_conformance_tests_java.sh +0 -161
  371. package/genome/rules/examples/integration-embedded-testing/run_unittests_java.sh +0 -50
  372. package/genome/rules/exported-concepts.md +0 -39
  373. package/genome/rules/func-specs.md +0 -164
  374. package/genome/rules/impl-reqs.md +0 -68
  375. package/genome/rules/import-modules.md +0 -49
  376. package/genome/rules/integration-embedded-testing.md +0 -273
  377. package/genome/rules/integration-embedded.md +0 -171
  378. package/genome/rules/integration-standalone.md +0 -135
  379. package/genome/rules/integrations.md +0 -136
  380. package/genome/rules/linked-resources.md +0 -76
  381. package/genome/rules/module-structure.md +0 -112
  382. package/genome/rules/project-model.md +0 -69
  383. package/genome/rules/required-concepts.md +0 -44
  384. package/genome/rules/requires-modules.md +0 -81
  385. package/genome/rules/semantic-ids.md +0 -49
  386. package/genome/rules/stdlib.md +0 -37
  387. package/genome/rules/test-plain-files.md +0 -138
  388. package/genome/rules/test-reqs.md +0 -57
  389. package/genome/rules/turri-regeneration.md +0 -66
  390. package/genome/skills/analyze-2-func-specs/SKILL.md +0 -116
  391. package/genome/skills/analyze-func-specs/SKILL.md +0 -137
  392. package/genome/skills/break-down-func-spec/SKILL.md +0 -229
  393. package/genome/skills/consolidate-concepts/SKILL.md +0 -192
  394. package/genome/skills/convert-old-syntax/SKILL.md +0 -68
  395. package/genome/skills/convert-old-syntax/references/rubric.md +0 -11
  396. package/genome/skills/debug-specs/SKILL.md +0 -194
  397. package/genome/skills/implement-conformance-testing-script/SKILL.md +0 -247
  398. package/genome/skills/implement-conformance-testing-script/assets/run_conformance_tests_cypress.ps1 +0 -337
  399. package/genome/skills/implement-conformance-testing-script/assets/run_conformance_tests_golang.ps1 +0 -111
  400. package/genome/skills/implement-conformance-testing-script/assets/run_conformance_tests_java.sh +0 -151
  401. package/genome/skills/implement-conformance-testing-script/assets/run_conformance_tests_python.ps1 +0 -103
  402. package/genome/skills/implement-conformance-testing-script/assets/run_conformance_tests_python.sh +0 -146
  403. package/genome/skills/implement-unit-testing-script/SKILL.md +0 -171
  404. package/genome/skills/implement-unit-testing-script/assets/run_unittests_flutter.ps1 +0 -87
  405. package/genome/skills/implement-unit-testing-script/assets/run_unittests_golang.ps1 +0 -73
  406. package/genome/skills/implement-unit-testing-script/assets/run_unittests_java.sh +0 -82
  407. package/genome/skills/implement-unit-testing-script/assets/run_unittests_python.ps1 +0 -81
  408. package/genome/skills/implement-unit-testing-script/assets/run_unittests_python.sh +0 -102
  409. package/genome/skills/implement-unit-testing-script/assets/run_unittests_react.ps1 +0 -87
  410. package/genome/skills/refactor-module/SKILL.md +0 -218
  411. package/genome/skills/resolve-section-ownership/SKILL.md +0 -64
  412. package/genome/skills/resolve-spec-conflict/SKILL.md +0 -102
  413. package/stdlib/backend/common.plain +0 -25
  414. package/stdlib/backend/conformance/common.plain +0 -12
  415. package/stdlib/backend/conformance/go-gin.plain +0 -9
  416. package/stdlib/backend/conformance/go-nethttp.plain +0 -9
  417. package/stdlib/backend/conformance/java-springboot.plain +0 -9
  418. package/stdlib/backend/conformance/python-django.plain +0 -9
  419. package/stdlib/backend/conformance/python-fastapi.plain +0 -9
  420. package/stdlib/backend/conformance/python-flask.plain +0 -9
  421. package/stdlib/backend/conformance/rust-axum.plain +0 -9
  422. package/stdlib/backend/conformance/typescript-express.plain +0 -9
  423. package/stdlib/backend/conformance/typescript-fastify.plain +0 -9
  424. package/stdlib/backend/conformance/typescript-nestjs.plain +0 -9
  425. package/stdlib/backend/go-gin.plain +0 -18
  426. package/stdlib/backend/go-nethttp.plain +0 -18
  427. package/stdlib/backend/java-springboot.plain +0 -19
  428. package/stdlib/backend/python-django.plain +0 -19
  429. package/stdlib/backend/python-fastapi.plain +0 -23
  430. package/stdlib/backend/python-flask.plain +0 -23
  431. package/stdlib/backend/rust-axum.plain +0 -17
  432. package/stdlib/backend/typescript-express.plain +0 -19
  433. package/stdlib/backend/typescript-fastify.plain +0 -19
  434. package/stdlib/backend/typescript-nestjs.plain +0 -19
  435. package/stdlib/cli/common.plain +0 -17
  436. package/stdlib/cli/conformance/common.plain +0 -11
  437. package/stdlib/cli/conformance/go-cobra.plain +0 -9
  438. package/stdlib/cli/conformance/go-flag.plain +0 -9
  439. package/stdlib/cli/conformance/java-picocli.plain +0 -9
  440. package/stdlib/cli/conformance/python-argparse.plain +0 -9
  441. package/stdlib/cli/conformance/python-click.plain +0 -9
  442. package/stdlib/cli/conformance/python-typer.plain +0 -9
  443. package/stdlib/cli/conformance/rust-clap.plain +0 -9
  444. package/stdlib/cli/conformance/typescript-commander.plain +0 -9
  445. package/stdlib/cli/go-cobra.plain +0 -14
  446. package/stdlib/cli/go-flag.plain +0 -14
  447. package/stdlib/cli/java-picocli.plain +0 -15
  448. package/stdlib/cli/python-argparse.plain +0 -18
  449. package/stdlib/cli/python-click.plain +0 -16
  450. package/stdlib/cli/python-typer.plain +0 -16
  451. package/stdlib/cli/rust-clap.plain +0 -14
  452. package/stdlib/cli/typescript-commander.plain +0 -17
  453. package/stdlib/frontend/angular.plain +0 -17
  454. package/stdlib/frontend/common.plain +0 -17
  455. package/stdlib/frontend/conformance/angular.plain +0 -5
  456. package/stdlib/frontend/conformance/common.plain +0 -11
  457. package/stdlib/frontend/conformance/react-vite.plain +0 -5
  458. package/stdlib/frontend/conformance/sveltekit-spa.plain +0 -5
  459. package/stdlib/frontend/conformance/vue-vite.plain +0 -5
  460. package/stdlib/frontend/react-vite.plain +0 -16
  461. package/stdlib/frontend/sveltekit-spa.plain +0 -16
  462. package/stdlib/frontend/vue-vite.plain +0 -16
  463. package/stdlib/lang/go.plain +0 -13
  464. package/stdlib/lang/java.plain +0 -12
  465. package/stdlib/lang/python.plain +0 -18
  466. package/stdlib/lang/rust.plain +0 -12
  467. package/stdlib/lang/typescript.plain +0 -13
  468. package/stdlib/library/common.plain +0 -15
  469. package/stdlib/library/conformance/common.plain +0 -9
  470. package/stdlib/library/conformance/go.plain +0 -9
  471. package/stdlib/library/conformance/java-gradle.plain +0 -9
  472. package/stdlib/library/conformance/java-maven.plain +0 -9
  473. package/stdlib/library/conformance/python.plain +0 -9
  474. package/stdlib/library/conformance/rust.plain +0 -9
  475. package/stdlib/library/conformance/typescript.plain +0 -9
  476. package/stdlib/library/go.plain +0 -12
  477. package/stdlib/library/java-gradle.plain +0 -13
  478. package/stdlib/library/java-maven.plain +0 -13
  479. package/stdlib/library/python.plain +0 -13
  480. package/stdlib/library/rust.plain +0 -12
  481. package/stdlib/library/typescript.plain +0 -15
package/dist/pi.js DELETED
@@ -1,889 +0,0 @@
1
- import { basename, dirname, join, resolve, sep } from "node:path";
2
- import { fileURLToPath } from "node:url";
3
- import { createAgentSession, DefaultResourceLoader, getAgentDir, ModelRegistry, SessionManager, } from "@earendil-works/pi-coding-agent";
4
- import { installedProviders, runtimeWithProviders } from "./installed-providers.js";
5
- import { loadRules, renderRulesBlock } from "./rules.js";
6
- import { debugMode, inheritModel, configModuleOf, readProjectConfig, ROLE_THINKING, roleModel, roleTurnLimitMs, splitModelSpec } from "./config.js";
7
- import { maskToolResults } from "./regenerate/masking.js";
8
- import { withListArguments } from "./regenerate/list-arguments.js";
9
- import { checkAgainstScript, ENVIRONMENT_ERROR_TOOL, EnvironmentError, environmentErrorTool, sandboxGapOf } from "./regenerate/environment-error.js";
10
- import { MODULES_DIR, projectRootOf, sessionsDir } from "./regenerate/paths.js";
11
- import { currentStopSignal, describeToolCall, describeToolResult, JobStoppedError, reportActivity, reportNow, reportAgent, reportTranscript, reportModelEvent, reportUsage, } from "./regenerate/activity.js";
12
- import { debugLogOf, startDebugLog } from "./regenerate/debug-log.js";
13
- import { firstLine, record } from "./regenerate/ledger.js";
14
- let thinkingSource;
15
- /**
16
- * Where sub-agents take their thinking level from: the conversation that started them.
17
- *
18
- * The model is inherited explicitly, by name, all the way down. The thinking level is just
19
- * as much a choice the person made - and left alone pi falls back to its own default, so a
20
- * conversation turned down for speed would hand every render agent a slower one. Read at
21
- * the moment each session starts, so a change mid-conversation applies to the next agent.
22
- */
23
- export function inheritThinkingLevel(source) {
24
- thinkingSource = source;
25
- }
26
- /**
27
- * How hard an agent thinks: the level the config or the model it is given names; else its role's (ROLE_THINKING) - the
28
- * work thinks little, the judgement more; else the conversation's, for an agent with no role.
29
- */
30
- export function agentThinking(named, role, conversation) {
31
- return named ?? (role !== undefined ? ROLE_THINKING[role] : undefined) ?? conversation();
32
- }
33
- function inheritedThinkingLevel() {
34
- try {
35
- return thinkingSource?.();
36
- }
37
- catch {
38
- // The conversation it came from is gone - a reload, a resumed session. pi's default is
39
- // a worse guess than the conversation's level, but a far better one than a failed build.
40
- return undefined;
41
- }
42
- }
43
- let providerSource;
44
- /**
45
- * Where sub-agents take the providers pi's extensions registered from: the conversation that started them.
46
- *
47
- * A sub-agent is started without extensions (see subAgentResources), so its models are only what pi's own
48
- * configuration has - models.json and auth.json. A provider an extension registers - a company's own LLM
49
- * gateway, say - is in the conversation's model registry and nowhere else: the conversation could use its
50
- * models and a render or skill agent told to use them could not find them. So every sub-agent's model
51
- * runtime is given the providers the conversation's registry holds when the agent starts - the provider,
52
- * not the extension that registered it.
53
- */
54
- export function inheritProviders(source) {
55
- providerSource = source;
56
- }
57
- /**
58
- * A model runtime for a sub-agent: pi's configuration, with the providers the conversation's extensions registered - or,
59
- * with no conversation to take them from (a command run headless), those the person's installed pi extensions register.
60
- */
61
- async function subAgentModelRuntime() {
62
- let source;
63
- try {
64
- source = providerSource?.();
65
- }
66
- catch {
67
- // The conversation it came from is gone: the installed ones, then.
68
- }
69
- return runtimeWithProviders(source ?? (await installedProviders()));
70
- }
71
- const RULES_DIR = join(dirname(dirname(fileURLToPath(import.meta.url))), "genome", "rules");
72
- /**
73
- * What a sub-agent session is made of: pi's resources without any extensions.
74
- *
75
- * Left to itself, pi builds every session from the user's configuration - including every
76
- * installed extension. When turri is installed globally, that means each render agent,
77
- * judge and skill executor loads a whole second copy of turri inside itself: its
78
- * tools, its hooks, its job registry, all bound to a session that is thrown away minutes
79
- * later. That copy then outlives its session in module state and breaks the next one. A
80
- * sub-agent is given exactly what it needs instead; for agents that work on specs, that
81
- * includes the ***plain rules, which otherwise only reached them through that stray copy.
82
- *
83
- * Nor any context file. pi puts every AGENTS.md / CLAUDE.md from the agent's folder up - the
84
- * project's, the user's ~/.pi/agent one - into its system prompt; a rendering agent works in
85
- * plain_modules/<module>/code, so it would be given whatever the project says about itself. An
86
- * agent turri starts sees only what turri gives it. The conversation still loads
87
- * them, as pi does.
88
- *
89
- * Nor any of pi's skills. pi lists every skill it finds - the user's, the project's - in the system prompt, for the
90
- * agent to load when one fits; an agent turri starts has one job, and turri runs its gated skills itself,
91
- * giving each step to an agent as its task. The conversation keeps them.
92
- */
93
- export async function subAgentResources(cwd, withRules, system) {
94
- // Less any the project leaves out (rules-off).
95
- const rules = withRules ? renderRulesBlock(loadRules(RULES_DIR, readProjectConfig(projectRootOf(cwd)).rulesOff ?? [])) : "";
96
- const extra = [rules, system ?? ""].filter((part) => part !== "");
97
- const loader = new DefaultResourceLoader({
98
- cwd,
99
- agentDir: getAgentDir(),
100
- noExtensions: true,
101
- noContextFiles: true,
102
- noSkills: true,
103
- appendSystemPrompt: extra.length > 0 ? extra : undefined,
104
- });
105
- await loader.reload();
106
- return loader;
107
- }
108
- function seconds(ms) {
109
- const s = Math.round(ms / 1000);
110
- return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${s % 60}s`;
111
- }
112
- const CALL_PROGRESS_MS = 500;
113
- /** How much of a tool call's arguments and result the transcript keeps: enough to follow, not the whole file. */
114
- const MAX_TOOL_ARGS = 600;
115
- const MAX_TOOL_RESULT = 2000;
116
- function clipText(text, max) {
117
- return text.length <= max ? text : `${text.slice(0, max)}… [${text.length - max} more characters]`;
118
- }
119
- function resultText(result) {
120
- const content = result?.content;
121
- if (!Array.isArray(content))
122
- return "";
123
- return content
124
- .filter((part) => part.type === "text" && typeof part.text === "string")
125
- .map((part) => part.text)
126
- .join("\n");
127
- }
128
- /** Raised when the provider itself failed, rather than the agent producing a poor answer. */
129
- export class ProviderError extends Error {
130
- constructor(message) {
131
- super(message);
132
- this.name = "ProviderError";
133
- }
134
- }
135
- /** Why turri itself ended a session's turn under way: the abort that comes back is its own, not the provider failing. */
136
- const harnessStops = new WeakMap();
137
- /**
138
- * End the agent's turn, turri's own doing - it is going round in a circle, its time is up. The turn ends as any turn
139
- * does: what the agent said stands, and the harness goes on from there. Never a provider error.
140
- */
141
- export function stopTurn(session, reason) {
142
- if (session === undefined || harnessStops.has(session))
143
- return;
144
- harnessStops.set(session, reason);
145
- reportModelEvent({ kind: "stopped", ...modelEventOf(session), reason });
146
- void session.abort();
147
- }
148
- /**
149
- * Run one turn and return the assistant's text, streaming deltas to `onDelta`.
150
- *
151
- * A provider failure - no credits, rate limit, bad key - arrives as an assistant message
152
- * with `stopReason: "error"` and no content. Left alone that looks exactly like an agent
153
- * that chose to say nothing, and any retry loop above will keep going as if the work were
154
- * merely unfinished. It is raised instead.
155
- */
156
- /** For each agent with a shell: where it works, and what it reported the environment lacks, if it did. */
157
- const environmentReports = new WeakMap();
158
- /** The agent's turn ended on report_environment_error: the pulse stops with what it said, as it said it. */
159
- function throwIfEnvironmentReported(session) {
160
- const entry = environmentReports.get(session);
161
- const report = entry?.reported.report;
162
- if (entry === undefined || report === undefined)
163
- return;
164
- entry.reported.report = undefined;
165
- const parts = resolve(entry.cwd).split(sep);
166
- const index = parts.lastIndexOf(MODULES_DIR);
167
- const moduleName = index >= 0 && parts.length > index + 1 ? parts[index + 1] : basename(resolve(entry.cwd));
168
- // A file it names that is on this machine: not missing - turri's sandbox hid it, and the fix is a line of config.
169
- const sandbox = sandboxGapOf([report.missing, report.neededBy, report.shownBy ?? ""].join("\n"), { project: projectRootOf(entry.cwd) });
170
- throw new EnvironmentError({ moduleName, missing: report.missing, neededBy: report.neededBy, ...(report.shownBy !== undefined ? { shownBy: report.shownBy } : {}), source: "agent", ...(sandbox !== undefined ? { sandbox } : {}) });
171
- }
172
- /** The tools a session's turn may use, while one is restricted (ask's `onlyTools`). */
173
- const turnTools = new WeakMap();
174
- /** How many calls a restricted turn may have refused before it is stopped. */
175
- export const REFUSED_BEFORE_STOP = 3;
176
- /**
177
- * `run`, with every tool of the session but `names` refused (guardRepeats refuses them) until it ends. The tools
178
- * themselves are left as they are, so the tools the model is sent - and its prompt cache - stay the same.
179
- */
180
- export async function withOnlyTools(session, names, run) {
181
- turnTools.set(session, new Set(names));
182
- try {
183
- return await run();
184
- }
185
- finally {
186
- turnTools.delete(session);
187
- }
188
- }
189
- export async function ask(session, text, onDelta, turn) {
190
- if (turn?.onlyTools === undefined)
191
- return askUnrestricted(session, text, onDelta);
192
- return withOnlyTools(session, turn.onlyTools, () => askUnrestricted(session, text, onDelta));
193
- }
194
- async function askUnrestricted(session, text, onDelta) {
195
- // Between turns, not during one: the work so far, summed up, once it has got larger than the threshold.
196
- // The summary keeps no images: they go with the next message again.
197
- if (await compactIfDue(session)) {
198
- const images = sessionImages.get(session);
199
- if (images !== undefined)
200
- images.sent = false;
201
- }
202
- // A provider that is overloaded or unreachable for a moment is waited out, longer than pi's own
203
- // retries do, rather than failing the whole run; the agent carries on where it was.
204
- let prompt = text;
205
- for (let attempt = 0;; attempt += 1) {
206
- try {
207
- const reply = await askOnce(session, prompt, onDelta);
208
- throwIfEnvironmentReported(session);
209
- return reply;
210
- }
211
- catch (error) {
212
- if (!(error instanceof ProviderError) || !TRANSIENT_PROVIDER_ERROR.test(error.message) || attempt >= PROVIDER_RETRIES)
213
- throw error;
214
- const wait = providerRetryDelay(attempt);
215
- const shown = `${Math.round(wait / 1000)}s (${attempt + 1} of ${PROVIDER_RETRIES})`;
216
- reportActivity(` the model provider is failing for now - trying again in ${shown}`);
217
- reportNow(`the model provider is failing - trying again in ${shown}`);
218
- reportModelEvent({ kind: "provider_retry", ...modelEventOf(session), error: error.message, attempt: attempt + 1, of: PROVIDER_RETRIES, waitMs: wait });
219
- debugLogOf(session)?.note(`provider failing - trying again in ${shown}: ${error.message.slice(0, 200)}`);
220
- await waitOrStop(wait);
221
- reportNow(undefined);
222
- prompt = "Carry on where you were: the model provider failed part-way through your last turn.";
223
- }
224
- }
225
- }
226
- /**
227
- * How many times, after pi's own retries, a turn whose provider failed for a moment is tried again; the first wait,
228
- * doubled each time up to the longest - 15s, 30s, 1m, 2m, 4m, 5m: an outage of about 13 minutes is waited out.
229
- */
230
- export const PROVIDER_RETRIES = 6;
231
- export const PROVIDER_RETRY_DELAY_MS = Number(process.env.TURRI_PROVIDER_RETRY_DELAY ?? 15) * 1000;
232
- export const PROVIDER_RETRY_MAX_DELAY_MS = 20 * PROVIDER_RETRY_DELAY_MS;
233
- /** The wait before try `attempt + 1`: doubled each time, up to the longest, with a tenth either way so parallel jobs do not all come back at once. */
234
- export function providerRetryDelay(attempt, random = Math.random) {
235
- const base = Math.min(PROVIDER_RETRY_DELAY_MS * 2 ** attempt, PROVIDER_RETRY_MAX_DELAY_MS);
236
- return Math.round(base * (0.9 + 0.2 * random()));
237
- }
238
- /** How long a request to the model may go without anything coming back before the provider is said to be stalling; 0 never. */
239
- export const PROVIDER_STALL_MS = Number(process.env.TURRI_PROVIDER_STALL ?? 120) * 1000;
240
- /** A provider error that passes: overloaded, rate limited, unreachable, timed out. */
241
- const TRANSIENT_PROVIDER_ERROR = /\b(429|500|502|503|504|529)\b|overloaded|high demand|rate.?limit|too many requests|unavailable|fetch failed|network|connection|timed? ?out|ECONNRESET|socket|terminated/i;
242
- /** Wait, unless the job is stopped first. */
243
- async function waitOrStop(ms) {
244
- const stop = currentStopSignal();
245
- if (stop?.aborted)
246
- throw new JobStoppedError();
247
- await new Promise((resolve) => {
248
- const timer = setTimeout(resolve, ms);
249
- stop?.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
250
- });
251
- if (stop?.aborted)
252
- throw new JobStoppedError();
253
- }
254
- async function askOnce(session, text, onDelta) {
255
- let out = "";
256
- let providerError;
257
- // Inside a background job, what the agent is doing is what the person watches - and most
258
- // of the time that is the model, not a tool. A write takes a millisecond; producing the
259
- // file it writes takes as long as the model needs to type it out. So the time from the
260
- // model starting a step to the tool running is shown against the tool, and while it is
261
- // happening the panel says which part it is at.
262
- let stepStarted = Date.now();
263
- let callChars = 0;
264
- let lastCallReport = 0;
265
- // Calls to one tool failing one after another - arguments it refuses, or errors - with nothing going through.
266
- let failing = 0;
267
- let failingTool;
268
- /** When each tool call under way started, by its id: how long it took is recorded as it ends. */
269
- const toolStarted = new Map();
270
- harnessStops.delete(session);
271
- reportNow("waiting for the model");
272
- // Every entry says which agent it is from, and what it runs on - for reading one agent at a time.
273
- const agent = agentOf(session);
274
- const transcript = (entry) => reportTranscript(agent !== undefined ? { ...entry, agent } : entry);
275
- // Its task is in its instructions, not in the conversation: the first turn shows it, for reading back.
276
- const task = pendingTask.get(session);
277
- pendingTask.delete(session);
278
- transcript({ kind: "prompt", text: task !== undefined ? `${task}\n\n${text}` : text });
279
- if (agent !== undefined)
280
- reportAgent({ label: agent.label, ...(agent.model !== undefined ? { model: agent.model } : {}), turns: 1 });
281
- reportModelEvent({ kind: "turn", ...modelEventOf(session) });
282
- // The provider stalling: a request to the model that nothing has come back on - not a token, not an error - for
283
- // long. Said once for each silence; the turn goes on waiting, its own time limit ending it if it must.
284
- let toolsRunning = 0;
285
- let stall;
286
- const watchForStall = (afterMs = PROVIDER_STALL_MS) => {
287
- if (stall !== undefined)
288
- clearTimeout(stall);
289
- stall = toolsRunning > 0 || PROVIDER_STALL_MS <= 0 ? undefined : setTimeout(() => {
290
- reportModelEvent({ kind: "provider_stall", ...modelEventOf(session), waitMs: PROVIDER_STALL_MS });
291
- debugLogOf(session)?.note(`the provider has sent nothing back for ${seconds(PROVIDER_STALL_MS)}`);
292
- }, afterMs);
293
- };
294
- const unsubscribe = session.subscribe((event) => {
295
- if (event.type === "tool_execution_start")
296
- toolsRunning += 1;
297
- if (event.type === "tool_execution_end")
298
- toolsRunning = Math.max(0, toolsRunning - 1);
299
- // pi tries a failed request again itself first: the provider failing is said then, not only once pi gives up.
300
- if (event.type === "auto_retry_start") {
301
- reportModelEvent({ kind: "provider_retry", ...modelEventOf(session), error: event.errorMessage, attempt: event.attempt, of: event.maxAttempts, waitMs: event.delayMs });
302
- watchForStall(event.delayMs + PROVIDER_STALL_MS);
303
- }
304
- else
305
- watchForStall();
306
- if (event.type === "message_update") {
307
- const update = event.assistantMessageEvent;
308
- if (update.type === "text_delta") {
309
- out += update.delta;
310
- onDelta?.(update.delta);
311
- transcript({ kind: "text", text: update.delta });
312
- }
313
- else if (update.type === "thinking_delta") {
314
- transcript({ kind: "thinking", text: update.delta });
315
- }
316
- else if (update.type === "thinking_start") {
317
- reportNow("thinking");
318
- }
319
- else if (update.type === "text_start") {
320
- // Each message of the turn its own paragraph: the agent's words between tool calls never run into each other.
321
- if (out !== "" && !/\s$/.test(out))
322
- out += "\n\n";
323
- reportNow("writing");
324
- }
325
- else if (update.type === "toolcall_start") {
326
- callChars = 0;
327
- reportNow("preparing a tool call");
328
- }
329
- else if (update.type === "toolcall_delta") {
330
- callChars += update.delta.length;
331
- const now = Date.now();
332
- if (now - lastCallReport >= CALL_PROGRESS_MS) {
333
- lastCallReport = now;
334
- const block = update.partial.content[update.contentIndex];
335
- const size = callChars >= 1000 ? `${(callChars / 1000).toFixed(1)}k` : `${callChars}`;
336
- reportNow(`writing ${block?.name ?? "a tool"} call · ${size} chars`, { keepSince: true });
337
- }
338
- }
339
- }
340
- if (event.type === "tool_execution_start") {
341
- toolStarted.set(event.toolCallId, Date.now());
342
- const args = JSON.stringify(event.args ?? {});
343
- transcript({ kind: "tool", text: `${event.toolName} ${clipText(args, MAX_TOOL_ARGS)}`, full: `${event.toolName} ${args}` });
344
- const took = Date.now() - stepStarted;
345
- // Which agent made the call, by its role: several work in one pulse.
346
- const role = agentRoles.get(session);
347
- const line = `${role !== undefined ? `(${role}) ` : ""}${describeToolCall(event.toolName, event.args)}`;
348
- reportActivity(took >= 1000 ? `${line} (model ${seconds(took)})` : line);
349
- reportNow(`running ${event.toolName}`);
350
- }
351
- if (event.type === "tool_execution_end") {
352
- failing = event.isError ? (event.toolName === failingTool ? failing + 1 : 1) : 0;
353
- failingTool = event.isError ? event.toolName : undefined;
354
- if (failing >= FAILURES_BEFORE_STOP && !harnessStops.has(session)) {
355
- // A call its tool refuses never reaches the tool, so no guard on the tools sees it: an agent can
356
- // make the same bad call, worded a little differently, thousands of times. Its turn ends here, and
357
- // the harness goes on from there, as after any turn.
358
- reportActivity(` stopped the agent's turn: ${failing} ${event.toolName} calls failed in a row`);
359
- debugLogOf(session)?.note(`turn stopped: ${failing} ${event.toolName} calls failed in a row`);
360
- stopTurn(session, `${failing} ${event.toolName} calls failed in a row`);
361
- }
362
- const output = resultText(event.result);
363
- const started = toolStarted.get(event.toolCallId);
364
- toolStarted.delete(event.toolCallId);
365
- record({ kind: "tool.call", tool: event.toolName, ms: started !== undefined ? Date.now() - started : 0, ok: !event.isError, resultChars: output.length }, { agent: modelEventOf(session) });
366
- transcript({ kind: "result", text: clipText(output, MAX_TOOL_RESULT), error: event.isError, full: output });
367
- const line = describeToolResult(event.toolName, event.result, event.isError);
368
- if (line !== undefined)
369
- reportActivity(line);
370
- stepStarted = Date.now();
371
- reportNow("waiting for the model");
372
- }
373
- if (event.type === "message_end") {
374
- const message = event.message;
375
- if (message.role === "assistant" && message.usage !== undefined) {
376
- const { input, output, cacheRead, cacheWrite, cost } = message.usage;
377
- const spent = { input, output, cacheRead, cacheWrite, cost: cost?.total ?? 0 };
378
- reportUsage(spent);
379
- if (agent !== undefined)
380
- reportAgent({ label: agent.label, usage: spent });
381
- reportModelEvent({ kind: "call", ...modelEventOf(session), usage: spent, ms: Date.now() - stepStarted });
382
- }
383
- // A provider error counts only if the turn ends on it: a later message that ends well - pi's own retry, the
384
- // stream picked up again - means it recovered, and the turn's work stands.
385
- if (message.role === "assistant" && message.stopReason === "error") {
386
- providerError = message.errorMessage ?? "the provider returned an error";
387
- }
388
- else if (message.role === "assistant") {
389
- providerError = undefined;
390
- }
391
- }
392
- if (event.type === "auto_retry_end" && event.success)
393
- providerError = undefined;
394
- });
395
- // A job asked to stop: abort the turn in progress, and do not start another. Every
396
- // agent a job runs goes through here, so this is where a stop reaches all of them.
397
- const stop = currentStopSignal();
398
- if (stop?.aborted) {
399
- unsubscribe();
400
- reportNow(undefined);
401
- throw new JobStoppedError();
402
- }
403
- const onStop = () => void session.abort();
404
- stop?.addEventListener("abort", onStop, { once: true });
405
- // For the agent's log: the whole prompt and how the turn ended; the session streams the rest.
406
- const debug = debugLogOf(session);
407
- const turnStarted = Date.now();
408
- // A timed turn is ended when the time is up. The agent is not told: a turn cut short is taken up again by the
409
- // harness, and a clock in the prompt only hurries the work. It ends at the next request to the model, not in the
410
- // middle of one: a request aborted in flight is billed whole and uncached, and its answer thrown away. What is running
411
- // then - the model answering, a tool - finishes; past the grace on top of the limit, it is ended where it is.
412
- const limitMs = timedSessions.get(session) ?? 0;
413
- const timed = limitMs > 0;
414
- let outOfTime = false;
415
- let timer;
416
- let backstop;
417
- let stopped = false;
418
- const endTurn = (how) => {
419
- if (stopped)
420
- return;
421
- stopped = true;
422
- reportActivity(` stopped the agent's turn: its ${formatLimit(limitMs)} are up`);
423
- debug?.note(`turn stopped: its ${formatLimit(limitMs)} are up${how}`);
424
- stopTurn(session, `its ${formatLimit(limitMs)} were up`);
425
- };
426
- const atNextRequest = timed
427
- ? session.subscribe((event) => {
428
- if (outOfTime && event.type === "turn_start")
429
- endTurn("");
430
- })
431
- : undefined;
432
- if (timed) {
433
- timer = setTimeout(() => {
434
- outOfTime = true;
435
- backstop = setTimeout(() => endTurn(" - and the grace after it: ended where it was"), TURN_GRACE_MS);
436
- }, limitMs);
437
- }
438
- // What the model is sent, and only that: its task is its system prompt, which the log already holds whole.
439
- debug?.prompt(text);
440
- watchForStall();
441
- try {
442
- // Its images, when its conversation does not hold them: the first turn, and the first after a compaction.
443
- const images = sessionImages.get(session);
444
- const attach = images !== undefined && !images.sent ? images.images : undefined;
445
- // The log holds what the model is sent as text; an image is not text, so the log says it went too.
446
- if (attach !== undefined)
447
- debug?.note(`sent with this message: ${attach.length === 1 ? "1 image" : `${attach.length} images`} (${attach.map((image) => image.mimeType).join(", ")})`);
448
- await session.prompt(text, { expandPromptTemplates: false, ...(attach !== undefined ? { images: attach } : {}) });
449
- if (images !== undefined)
450
- images.sent = true;
451
- }
452
- catch (error) {
453
- debug?.note(`turn failed after ${seconds(Date.now() - turnStarted)}: ${error instanceof Error ? error.message : String(error)}`);
454
- throw error;
455
- }
456
- finally {
457
- if (timer !== undefined)
458
- clearTimeout(timer);
459
- if (backstop !== undefined)
460
- clearTimeout(backstop);
461
- if (stall !== undefined)
462
- clearTimeout(stall);
463
- atNextRequest?.();
464
- unsubscribe();
465
- stop?.removeEventListener("abort", onStop);
466
- reportNow(undefined);
467
- }
468
- // turri ended the turn itself - its time was up, the agent went round in a circle: the abort that ended it is its own.
469
- const stoppedFor = harnessStops.get(session);
470
- harnessStops.delete(session);
471
- if (stoppedFor !== undefined)
472
- out = `${out.trim()}\n\n[the turn was stopped: ${stoppedFor}]`.trim();
473
- if (stop?.aborted) {
474
- debug?.note(`turn stopped on request after ${seconds(Date.now() - turnStarted)}`);
475
- throw new JobStoppedError();
476
- }
477
- // A turn turri ended is ended, whatever the provider was doing then: what comes back of the abort is not the provider failing.
478
- if (providerError !== undefined && stoppedFor === undefined) {
479
- debug?.note(`turn ended with a provider error after ${seconds(Date.now() - turnStarted)}: ${providerError}`);
480
- record({ kind: "provider.error", error: firstLine(providerError, 300), transient: TRANSIENT_PROVIDER_ERROR.test(providerError) }, { agent: modelEventOf(session) });
481
- throw new ProviderError(`${session.model?.id ?? "model"}: ${providerError}`);
482
- }
483
- debug?.note(`turn finished after ${seconds(Date.now() - turnStarted)}`);
484
- return out.trim();
485
- }
486
- /**
487
- * How long one turn of an agent a render starts may take: past it, the turn ends where it is and
488
- * the harness goes on as after any turn - it runs the tests, and judges. The config's `turn-limit:`
489
- * sets it, in seconds, and each role's in `models:`; 0 turns it off.
490
- */
491
- export const DEFAULT_TURN_LIMIT_MS = 120 * 1000;
492
- /** How long past the turn limit what is running then - the model answering, a tool - may take to finish. */
493
- export const TURN_GRACE_MS = Number(process.env.TURRI_TURN_GRACE ?? 60) * 1000;
494
- /** A session's task, in its instructions, until its first turn shows it in the transcript. */
495
- const pendingTask = new WeakMap();
496
- /** A session's images, and whether its conversation holds them now: not at first, nor after a compaction. */
497
- const sessionImages = new WeakMap();
498
- /**
499
- * Refuses, before any agent of a job starts, a named model that reads no images when the job's spec links some -
500
- * rather than once the work is under way. Unnamed, the model is pi's default: `createExecutor` refuses it then.
501
- */
502
- export async function refuseIfModelIsBlind(modelSpec, count) {
503
- if (count === 0)
504
- return;
505
- const chosen = splitModelSpec(modelSpec).model;
506
- const slash = chosen?.indexOf("/") ?? -1;
507
- if (chosen === undefined || slash === -1)
508
- return;
509
- refuseIfBlind(new ModelRegistry(await subAgentModelRuntime()).find(chosen.slice(0, slash), chosen.slice(slash + 1)), count);
510
- }
511
- /** A model that cannot read images, given images to read. */
512
- export class ModelCannotReadImagesError extends Error {
513
- }
514
- /**
515
- * Stops an agent whose model reads no images being given some: it would work blind from the spec's images. Says
516
- * which model, and what to do - a coding model that reads images, or the images described in text instead.
517
- */
518
- export function refuseIfBlind(model, count) {
519
- if (model === undefined || model.input?.includes("image") === true)
520
- return;
521
- throw new ModelCannotReadImagesError(`The spec links ${count === 1 ? "an image" : `${count} images`} (PNG or JPEG), and ${model.provider}/${model.id} cannot read images. ` +
522
- "Set coding-model in config.turri.yaml to a model that reads images, or describe what the image shows in a text file and link that instead.");
523
- }
524
- /**
525
- * What an agent opens with when its task is in its instructions. The task - the spec, how to read it, what to do
526
- * and the rules - is its system prompt, not its first message: compaction sums up the conversation and never the
527
- * system prompt, so what the agent works from stays word for word as it was, however long the work runs, and stays
528
- * in the cached prefix of every call.
529
- */
530
- export const BEGIN = "Begin. Your task is in your instructions.";
531
- /** Tokens of conversation past which a session that keeps working is compacted, when the project does not say. */
532
- export const DEFAULT_COMPACT_AT = 100_000;
533
- const compactions = new WeakMap();
534
- /** Have a session compacted between turns, as `compaction` says: what createExecutor does for an agent given one. */
535
- export function keepCompacted(session, compaction) {
536
- compactions.set(session, compaction);
537
- }
538
- /** A rough count, as pi's own estimate makes it: four characters a token. */
539
- function tokensIn(text) {
540
- return Math.ceil(text.length / 4);
541
- }
542
- function thousands(tokens) {
543
- return tokens >= 1000 ? `${Math.round(tokens / 1000)}k` : `${tokens}`;
544
- }
545
- /**
546
- * Compact a session's work when its conversation - what it has done, not its instructions - has got larger than its
547
- * threshold. An agent that keeps its session through a job re-reads everything it did on every call: this keeps
548
- * that bounded, as pi's own compaction does only when the context window is nearly full. The summary keeps what
549
- * its role needs; its instructions are untouched. A compaction that fails leaves the session as it was.
550
- */
551
- export async function compactIfDue(session) {
552
- const settings = compactions.get(session);
553
- if (settings === undefined)
554
- return false;
555
- let tokens;
556
- try {
557
- tokens = session.getContextUsage()?.tokens;
558
- }
559
- catch {
560
- return false;
561
- }
562
- if (tokens === null || tokens === undefined)
563
- return false;
564
- const conversation = tokens - tokensIn(session.systemPrompt ?? "");
565
- if (conversation < settings.atTokens)
566
- return false;
567
- const agent = agentOf(session);
568
- const who = agent?.label ?? "the agent";
569
- reportActivity(` compacting ${who}'s work: ${thousands(conversation)} tokens of it, past ${thousands(settings.atTokens)}`);
570
- try {
571
- const compactStarted = Date.now();
572
- const result = await session.compact(settings.instructions);
573
- const usage = result.usage;
574
- if (usage !== undefined) {
575
- const spent = { input: usage.input, output: usage.output, cacheRead: usage.cacheRead, cacheWrite: usage.cacheWrite, cost: usage.cost?.total ?? 0 };
576
- reportUsage(spent);
577
- if (agent !== undefined)
578
- reportAgent({ label: agent.label, usage: spent });
579
- reportModelEvent({ kind: "call", ...modelEventOf(session), usage: spent, ms: Date.now() - compactStarted });
580
- }
581
- reportModelEvent({ kind: "compaction", ...modelEventOf(session) });
582
- if (agent !== undefined)
583
- reportAgent({ label: agent.label, compactions: 1 });
584
- reportActivity(` compacted ${who}'s work${result.estimatedTokensAfter !== undefined ? ` to about ${thousands(result.estimatedTokensAfter)} tokens` : ""}`);
585
- debugLogOf(session)?.note(`compacted: ${result.tokensBefore} tokens before${result.estimatedTokensAfter !== undefined ? `, about ${result.estimatedTokensAfter} after` : ""}`);
586
- return true;
587
- }
588
- catch (error) {
589
- reportActivity(` could not compact ${who}'s work - it goes on as it is: ${error instanceof Error ? error.message.slice(0, 160) : String(error)}`);
590
- return false;
591
- }
592
- }
593
- /** The sessions whose turns are timed, and how long each turn may take: the agents a render starts, not the conversation or a skill's. */
594
- const timedSessions = new WeakMap();
595
- /** Which agent a session is, and what it runs on - for its transcript entries. */
596
- const agentLabels = new WeakMap();
597
- /** Each agent's role, to say on its activity lines which agent did what. */
598
- const agentRoles = new WeakMap();
599
- function agentOf(session) {
600
- return agentLabels.get(session);
601
- }
602
- /** Who a model event is from: the agent's model as it runs now, its role and its label - an agent with no label too. */
603
- function modelEventOf(session) {
604
- const agent = agentOf(session);
605
- const role = agentRoles.get(session);
606
- const model = session.model !== undefined ? `${session.model.provider}/${session.model.id}${session.thinkingLevel ? `:${session.thinkingLevel}` : ""}` : agent?.model;
607
- return { ...(model !== undefined ? { model } : {}), ...(role !== undefined ? { role } : {}), ...(agent !== undefined ? { label: agent.label } : {}) };
608
- }
609
- /**
610
- * Have this session's turns timed, as an agent a render starts has: `limitMs` each - its role's in the config - or
611
- * the default.
612
- */
613
- export function timeTurns(session, limitMs) {
614
- timedSessions.set(session, limitMs ?? DEFAULT_TURN_LIMIT_MS);
615
- }
616
- /** How many calls to one tool may fail in a row, nothing going through, before the agent's turn is stopped. */
617
- export const FAILURES_BEFORE_STOP = 10;
618
- /** How many times running the very same tool call is let through before it is refused, and before the turn is stopped. */
619
- export const REPEATS_ALLOWED = 3;
620
- export const REPEATS_BEFORE_STOP = 6;
621
- /** "2 minutes", "90 seconds". */
622
- function formatLimit(ms) {
623
- const seconds = Math.round(ms / 1000);
624
- if (seconds % 60 === 0)
625
- return `${seconds / 60} minute${seconds === 60 ? "" : "s"}`;
626
- return `${seconds} second${seconds === 1 ? "" : "s"}`;
627
- }
628
- /** JSON with every object's keys in order, so two ways of writing the same arguments read the same. */
629
- export function canonicalJson(value) {
630
- return JSON.stringify(value, (_key, item) => item !== null && typeof item === "object" && !Array.isArray(item)
631
- ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
632
- : item);
633
- }
634
- /** Tools that only look: calling one again, with nothing changed since, gives the same answer. */
635
- const LOOKING_TOOLS = new Set(["read", "grep", "find", "ls"]);
636
- /**
637
- * Tools that notice an agent going round in a circle. The same call again and again with nothing in
638
- * between; or a look - read, grep, find, ls - made again with nothing changed since, however many
639
- * other looks came between: the same answer comes back. The first few go through; after that the
640
- * call is refused with what is happening, and if the agent carries on regardless its turn is
641
- * stopped - the harness goes on from there, as after any turn.
642
- *
643
- * With a budget, an agent that has one thing to decide - a verdict, a review, an account - is told
644
- * to decide once it has made that many calls: every tool but the one that hands it over refuses,
645
- * and past twice the budget its turn is stopped. Handing it over starts the count again, and forgets
646
- * the looks: a reviewer kept for the next review reads the files as they are by then.
647
- */
648
- export function guardRepeats(tools, session, budget) {
649
- let last;
650
- let times = 0;
651
- // Looks made since the last call that could change anything, and how often each.
652
- const looks = new Map();
653
- let calls = 0;
654
- // Calls refused in the restricted turn under way, and which turn's set that was.
655
- let refused = 0;
656
- let refusedIn;
657
- /** The agent a refusal is of, for the ledger. */
658
- const guardPlace = () => {
659
- const current = session();
660
- return current !== undefined ? { agent: modelEventOf(current) } : {};
661
- };
662
- return tools.map((tool) => ({
663
- ...tool,
664
- execute: async (...args) => {
665
- const [, params] = args;
666
- const current = session();
667
- const only = current !== undefined ? turnTools.get(current) : undefined;
668
- if (only !== undefined && !only.has(tool.name)) {
669
- if (refusedIn !== only)
670
- (refused = 0), (refusedIn = only);
671
- refused += 1;
672
- record({ kind: "guard.refused", rule: "restricted", tool: tool.name, times: refused }, guardPlace());
673
- if (refused > REFUSED_BEFORE_STOP) {
674
- reportActivity(` stopped the agent's turn: ${refused} calls to tools this turn does not have`);
675
- stopTurn(current, `${refused} calls to tools this turn does not have`);
676
- throw new Error(`Stopped: ${refused} calls to tools this turn does not have.`);
677
- }
678
- throw new Error(`Not run: your work is done and checked - this turn is for ${[...only].join(" and ")} alone, and nothing else is ` +
679
- `run. Call ${[...only].join(" or ")}, then finish.`);
680
- }
681
- calls += 1;
682
- if (budget !== undefined && !budget.finish.includes(tool.name) && calls > budget.calls) {
683
- record({ kind: "guard.refused", rule: "budget", tool: tool.name, times: calls - budget.calls }, guardPlace());
684
- if (calls > budget.calls * 2) {
685
- reportActivity(` stopped the agent's turn: ${calls} tool calls, past its budget of ${budget.calls}`);
686
- stopTurn(session(), `${calls} tool calls, past its budget of ${budget.calls}`);
687
- throw new Error(`Stopped: ${calls} tool calls, past the budget of ${budget.calls}.`);
688
- }
689
- throw new Error(`Not run: you have made ${budget.calls} tool calls, which is all you have. Decide now with what you know: call ` +
690
- `${budget.finish.join(" or ")}.`);
691
- }
692
- let key;
693
- try {
694
- // The same call is the same whatever order its arguments come in: models reorder them freely.
695
- key = `${tool.name} ${canonicalJson(params ?? {})}`;
696
- }
697
- catch {
698
- key = `${tool.name} ${String(Math.random())}`;
699
- }
700
- times = key === last ? times + 1 : 1;
701
- last = key;
702
- let repeats = times;
703
- if (LOOKING_TOOLS.has(tool.name)) {
704
- const seen = (looks.get(key) ?? 0) + 1;
705
- looks.set(key, seen);
706
- repeats = Math.max(repeats, seen);
707
- }
708
- else {
709
- // Anything else may have changed what a look would find.
710
- looks.clear();
711
- }
712
- if (repeats > REPEATS_ALLOWED)
713
- record({ kind: "guard.refused", rule: "repeat", tool: tool.name, times: repeats }, guardPlace());
714
- if (repeats > REPEATS_BEFORE_STOP) {
715
- reportActivity(` stopped the agent's turn: it made the same ${tool.name} call ${repeats} times with nothing changed`);
716
- stopTurn(session(), `the same ${tool.name} call ${repeats} times with nothing changed`);
717
- throw new Error(`Stopped: the same ${tool.name} call ${repeats} times with nothing changed.`);
718
- }
719
- if (repeats > REPEATS_ALLOWED) {
720
- reportActivity(` refused a repeated ${tool.name} call (${repeats} times with nothing changed)`);
721
- throw new Error(`Not run: you have made this exact ${tool.name} call ${repeats} times, with nothing changed since - so it would give ` +
722
- "the same result again. Stop repeating it: use what it already told you, do something different, or finish. " +
723
- `After ${REPEATS_BEFORE_STOP} your turn is stopped.`);
724
- }
725
- const result = await tool.execute(...args);
726
- // The decision handed over ends the round: a session kept for the next one starts it with its whole budget.
727
- if (budget?.finish.includes(tool.name)) {
728
- calls = 0;
729
- last = undefined;
730
- times = 0;
731
- looks.clear();
732
- }
733
- return result;
734
- },
735
- }));
736
- }
737
- /**
738
- * The executor. One session for the whole skill run, so a retry after a failed
739
- * gate arrives as a follow-up turn with the critique in it rather than as a cold
740
- * start that has forgotten what it just wrote.
741
- */
742
- export async function createExecutor(opts) {
743
- // Saved to disk, in the project, for an agent picked back up after the process that ran it is gone - a skill's run -
744
- // and in debug mode, as the record of what each did. Nothing else reads one back: the rest are kept in memory.
745
- const project = projectRootOf(opts.cwd);
746
- const sessionManager = opts.resumeFrom !== undefined
747
- ? SessionManager.open(opts.resumeFrom)
748
- : opts.saveSession === true || debugMode(project)
749
- ? SessionManager.create(opts.cwd, sessionsDir(project))
750
- : SessionManager.inMemory(opts.cwd);
751
- // An agent that writes and runs code - given the harness's run its reports are checked against - can say the machine
752
- // lacks what the work needs: its turn ends, and the pulse stops with it. Observers, explorers and judges cannot.
753
- const hasShell = opts.customTools.some((tool) => tool.name === "bash") && opts.checkEnvironment !== undefined;
754
- const reported = {};
755
- const check = opts.checkEnvironment !== undefined ? checkAgainstScript(opts.checkEnvironment.run, opts.checkEnvironment.script) : undefined;
756
- const withEnvironmentErrors = hasShell ? [...opts.customTools, environmentErrorTool((report) => (reported.report = report), check)] : opts.customTools;
757
- const { session } = await createAgentSession({
758
- cwd: opts.cwd,
759
- modelRuntime: await subAgentModelRuntime(),
760
- tools: hasShell ? [...opts.tools, ENVIRONMENT_ERROR_TOOL] : opts.tools,
761
- // What an agent is shown never holds a credential the project passed: each value is its name (masking.ts).
762
- customTools: guardRepeats(maskToolResults(withListArguments(withEnvironmentErrors)), () => session, opts.budget),
763
- sessionManager,
764
- resourceLoader: await subAgentResources(opts.cwd, opts.rules === true, [opts.system, opts.task].filter((part) => part !== undefined && part !== "").join("\n\n") || undefined),
765
- });
766
- if (opts.task !== undefined)
767
- pendingTask.set(session, opts.task);
768
- if (hasShell)
769
- environmentReports.set(session, { cwd: opts.cwd, reported });
770
- if (opts.compaction !== undefined)
771
- keepCompacted(session, { instructions: opts.compaction.instructions, atTokens: opts.compaction.atTokens ?? compactAtFor(opts.cwd) });
772
- // Its role's own model and thinking, where the config names them; otherwise what it was given.
773
- const config = opts.role !== undefined ? configForCwd(opts.cwd) : undefined;
774
- const fromRole = config !== undefined && opts.role !== undefined ? roleModel(config, opts.role) : undefined;
775
- const chosen = fromRole !== undefined ? (inheritModel(fromRole, splitModelSpec(opts.model)) ?? {}) : splitModelSpec(opts.model);
776
- if (chosen.model !== undefined) {
777
- const model = findModel(session, chosen.model);
778
- if (model === undefined) {
779
- throw new Error(`Model '${chosen.model}' is not a model pi knows: no such id for that provider. \`turri --list-models <search>\` lists the ones it does; one of your own goes in ~/.pi/agent/models.json.`);
780
- }
781
- await session.setModel(model);
782
- }
783
- // After the model: switching models picks a thinking level of its own.
784
- const thinking = agentThinking(chosen.thinking, opts.role, inheritedThinkingLevel);
785
- if (thinking !== undefined)
786
- session.setThinkingLevel(thinking);
787
- if (opts.images !== undefined && opts.images.length > 0) {
788
- refuseIfBlind(session.model, opts.images.length);
789
- sessionImages.set(session, { images: opts.images, sent: false });
790
- }
791
- // After both, so the log's header says what it really runs on.
792
- if (opts.label !== undefined)
793
- startDebugLog(session, { cwd: opts.cwd, label: opts.label, tools: opts.tools });
794
- // An agent a render starts - it has a label - has its turns timed: as long as its role's turns may take.
795
- if (opts.label !== undefined)
796
- timeTurns(session, config !== undefined ? roleTurnLimitMs(config, opts.role) : undefined);
797
- sendReasoningEffort(session);
798
- if (opts.role !== undefined)
799
- agentRoles.set(session, opts.role);
800
- if (opts.label !== undefined) {
801
- const thinking = session.thinkingLevel;
802
- agentLabels.set(session, { label: opts.label, model: session.model !== undefined ? `${session.model.provider}/${session.model.id}${thinking ? `:${thinking}` : ""}` : undefined });
803
- }
804
- return session;
805
- }
806
- /** The config an agent working in `cwd` is under: the project's, with the pulse's module's own file over it. */
807
- function configForCwd(cwd) {
808
- try {
809
- const root = projectRootOf(cwd);
810
- return readProjectConfig(root, configModuleOf(root));
811
- }
812
- catch {
813
- return {};
814
- }
815
- }
816
- /** pi's thinking levels as the reasoning effort OpenAI's models on Bedrock take. */
817
- const BEDROCK_OPENAI_EFFORT = { off: "none", minimal: "low", low: "low", medium: "medium", high: "high", xhigh: "xhigh", max: "xhigh" };
818
- /**
819
- * OpenAI's models on Bedrock are sent the session's thinking level as their reasoning effort - pi sends none for a
820
- * model that is not Anthropic's, and they would think at their own default whatever the config said.
821
- */
822
- function sendReasoningEffort(session) {
823
- const agent = session.agent;
824
- const before = agent.onPayload;
825
- agent.onPayload = async (payload, model) => withReasoningEffort((await before?.(payload, model)) ?? payload, model, session.thinkingLevel);
826
- }
827
- /** A provider request with its thinking level sent as reasoning effort, where the model takes one turri sends itself. */
828
- export function withReasoningEffort(payload, model, thinkingLevel) {
829
- const m = model;
830
- const effort = BEDROCK_OPENAI_EFFORT[thinkingLevel ?? ""];
831
- if (m?.api !== "bedrock-converse-stream" || m.reasoning !== true || !/(^|\.)openai\./.test(m.id ?? "") || effort === undefined)
832
- return payload;
833
- if (payload === null || typeof payload !== "object")
834
- return payload;
835
- const input = payload;
836
- return { ...input, additionalModelRequestFields: { ...(input.additionalModelRequestFields ?? {}), reasoning: { effort } } };
837
- }
838
- function compactAtFor(cwd) {
839
- try {
840
- return readProjectConfig(projectRootOf(cwd)).compactAt ?? DEFAULT_COMPACT_AT;
841
- }
842
- catch {
843
- return DEFAULT_COMPACT_AT;
844
- }
845
- }
846
- function findModel(session, spec) {
847
- const slash = spec.indexOf("/");
848
- if (slash === -1)
849
- throw new Error(`Model must be "provider/model-id", got "${spec}"`);
850
- return new ModelRegistry(session.modelRuntime).find(spec.slice(0, slash), spec.slice(slash + 1));
851
- }
852
- /**
853
- * A judge. Fresh session, one tool, and - deliberately - no access to the
854
- * executor's transcript. A judge that inherits the actor's reasoning inherits
855
- * its rationalisations, so it gets the artifact and the rubric, nothing else.
856
- */
857
- export async function createJudge(opts) {
858
- const modelRuntime = opts.borrowAuthFrom.modelRuntime;
859
- let model;
860
- let modelNote = "executor model";
861
- if (opts.modelSpec) {
862
- const slash = opts.modelSpec.indexOf("/");
863
- if (slash === -1)
864
- throw new Error(`gate model must be "provider/model-id", got "${opts.modelSpec}"`);
865
- const provider = opts.modelSpec.slice(0, slash);
866
- const modelId = opts.modelSpec.slice(slash + 1);
867
- const found = new ModelRegistry(modelRuntime).find(provider, modelId);
868
- if (found) {
869
- model = found;
870
- modelNote = opts.modelSpec;
871
- }
872
- else {
873
- modelNote = `executor model (${opts.modelSpec} not configured)`;
874
- }
875
- }
876
- const { session } = await createAgentSession({
877
- cwd: opts.cwd,
878
- model,
879
- modelRuntime,
880
- tools: [...(opts.extraTools ?? []), "submit_verdict"],
881
- customTools: withListArguments([opts.verdictTool]),
882
- sessionManager: SessionManager.inMemory(opts.cwd),
883
- // Judges assess specs against the rules, so they have them too.
884
- resourceLoader: await subAgentResources(opts.cwd, true, opts.task),
885
- });
886
- if (opts.task !== undefined)
887
- pendingTask.set(session, opts.task);
888
- return { session, modelNote };
889
- }