@turri-dev/cli 0.4.2 → 0.4.3-next.4908c8d

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 (484) hide show
  1. package/README.md +24 -3
  2. package/dist/banner.js +259 -0
  3. package/dist/capture-cli.js +77 -0
  4. package/dist/capture-view.js +99 -0
  5. package/dist/chat-commands.js +9 -63
  6. package/dist/chat-models.js +17 -15
  7. package/dist/chat-tab-header.js +90 -0
  8. package/dist/chat-tabs.js +100 -0
  9. package/dist/chat-terminal.js +170 -61
  10. package/dist/chat-waiting.js +7 -24
  11. package/dist/cli-options.js +11 -7
  12. package/dist/cli-root.js +141 -0
  13. package/dist/cli.js +48 -36
  14. package/dist/conform-cli.js +4 -6
  15. package/dist/cultivate-cli.js +65 -97
  16. package/dist/doctor-cli.js +99 -0
  17. package/dist/drift-cli.js +2 -7
  18. package/dist/entry-renderers.js +107 -0
  19. package/dist/extension.js +14 -3211
  20. package/dist/init-config-cli.js +209 -0
  21. package/dist/launch-cli.js +55 -91
  22. package/dist/lineage-cli.js +2 -4
  23. package/dist/loop-cli.js +118 -233
  24. package/dist/panel-view.js +409 -0
  25. package/dist/parse-cli.js +5 -2
  26. package/dist/pi-launch.js +43 -13
  27. package/dist/pi-themes.js +21 -0
  28. package/dist/plain-code-blocks.js +56 -0
  29. package/dist/pointer-hover.js +48 -0
  30. package/dist/print-mode.js +20 -0
  31. package/dist/question-dialog.js +26 -3
  32. package/dist/quiet.js +7 -106
  33. package/dist/regenerate/diff-view.js +6 -87
  34. package/dist/regenerate/jobs-tree.js +7 -18
  35. package/dist/regenerate/side-panel.js +158 -22
  36. package/dist/regenerate/spec-map-view.js +25 -70
  37. package/dist/regenerate-cli.js +7 -11
  38. package/dist/reopen.js +80 -0
  39. package/dist/resume-line.js +5 -2
  40. package/dist/skill-progress.js +25 -0
  41. package/dist/skill-report.js +52 -0
  42. package/dist/terminal-marks.js +21 -0
  43. package/dist/terminal-notifications.js +219 -0
  44. package/dist/terminal-view.js +275 -0
  45. package/dist/turri-versions.js +64 -6
  46. package/docs/README.md +4 -2
  47. package/docs/capture.md +227 -0
  48. package/docs/chats.md +14 -10
  49. package/docs/claude-subscription.md +1 -1
  50. package/docs/config.md +23 -8
  51. package/docs/development.md +30 -61
  52. package/docs/headless.md +3 -1
  53. package/docs/hosting.md +3 -251
  54. package/docs/installation.md +5 -3
  55. package/docs/launch.md +3 -3
  56. package/docs/regenerating.md +1 -1
  57. package/docs/sandbox.md +4 -2
  58. package/docs/sentinel.md +13 -13
  59. package/docs/theming.md +3 -3
  60. package/docs/using.md +14 -6
  61. package/package.json +15 -33
  62. package/dist/ask.d.ts +0 -90
  63. package/dist/ask.js +0 -170
  64. package/dist/background-skills.d.ts +0 -53
  65. package/dist/background-skills.js +0 -121
  66. package/dist/bedrock-region.d.ts +0 -66
  67. package/dist/bedrock-region.js +0 -144
  68. package/dist/brand.d.ts +0 -13
  69. package/dist/btw.d.ts +0 -69
  70. package/dist/btw.js +0 -174
  71. package/dist/chat-commands.d.ts +0 -25
  72. package/dist/chat-idle.d.ts +0 -7
  73. package/dist/chat-idle.js +0 -20
  74. package/dist/chat-models.d.ts +0 -22
  75. package/dist/chat-records.d.ts +0 -50
  76. package/dist/chat-records.js +0 -107
  77. package/dist/chat-scope.d.ts +0 -14
  78. package/dist/chat-scope.js +0 -15
  79. package/dist/chat-skills.d.ts +0 -17
  80. package/dist/chat-skills.js +0 -18
  81. package/dist/chat-terminal.d.ts +0 -24
  82. package/dist/chat-ui.d.ts +0 -33
  83. package/dist/chat-waiting.d.ts +0 -64
  84. package/dist/chats.d.ts +0 -338
  85. package/dist/chats.js +0 -996
  86. package/dist/cli-options.d.ts +0 -24
  87. package/dist/cli.d.ts +0 -9
  88. package/dist/config-edit.d.ts +0 -83
  89. package/dist/config-edit.js +0 -390
  90. package/dist/config.d.ts +0 -415
  91. package/dist/config.js +0 -757
  92. package/dist/conform-cli.d.ts +0 -1
  93. package/dist/conformance-switch.d.ts +0 -25
  94. package/dist/conformance-switch.js +0 -86
  95. package/dist/cultivate-cli.d.ts +0 -1
  96. package/dist/doctor-tool.d.ts +0 -11
  97. package/dist/doctor-tool.js +0 -33
  98. package/dist/drift-cli.d.ts +0 -1
  99. package/dist/environment.d.ts +0 -37
  100. package/dist/environment.js +0 -109
  101. package/dist/extension.d.ts +0 -208
  102. package/dist/genome.d.ts +0 -77
  103. package/dist/genome.js +0 -288
  104. package/dist/graph.d.ts +0 -52
  105. package/dist/graph.js +0 -247
  106. package/dist/host-session.d.ts +0 -112
  107. package/dist/host-session.js +0 -103
  108. package/dist/host.d.ts +0 -40
  109. package/dist/host.js +0 -54
  110. package/dist/identity.d.ts +0 -7
  111. package/dist/identity.js +0 -74
  112. package/dist/init-config.d.ts +0 -169
  113. package/dist/init-config.js +0 -840
  114. package/dist/installed-providers.d.ts +0 -40
  115. package/dist/installed-providers.js +0 -98
  116. package/dist/jellyfish.d.ts +0 -40
  117. package/dist/judge.d.ts +0 -25
  118. package/dist/judge.js +0 -62
  119. package/dist/launch-agent.d.ts +0 -62
  120. package/dist/launch-agent.js +0 -339
  121. package/dist/launch-cli.d.ts +0 -1
  122. package/dist/launch-session.d.ts +0 -68
  123. package/dist/launch-session.js +0 -225
  124. package/dist/launch-tools.d.ts +0 -28
  125. package/dist/launch-tools.js +0 -72
  126. package/dist/launch-track.d.ts +0 -175
  127. package/dist/launch-track.js +0 -497
  128. package/dist/lineage-cli.d.ts +0 -1
  129. package/dist/loop-cli.d.ts +0 -35
  130. package/dist/loop-tools.d.ts +0 -103
  131. package/dist/loop-tools.js +0 -357
  132. package/dist/model-check.d.ts +0 -72
  133. package/dist/model-check.js +0 -162
  134. package/dist/module-report.d.ts +0 -9
  135. package/dist/new-project.d.ts +0 -5
  136. package/dist/new-project.js +0 -31
  137. package/dist/notice.d.ts +0 -115
  138. package/dist/notice.js +0 -61
  139. package/dist/parse-cli.d.ts +0 -1
  140. package/dist/parse-tool.d.ts +0 -9
  141. package/dist/parse-tool.js +0 -33
  142. package/dist/pi-launch.d.ts +0 -1
  143. package/dist/pi-settings.d.ts +0 -4
  144. package/dist/pi.d.ts +0 -248
  145. package/dist/pi.js +0 -889
  146. package/dist/picture-row.d.ts +0 -10
  147. package/dist/plain/check.d.ts +0 -63
  148. package/dist/plain/check.js +0 -236
  149. package/dist/plain/concepts.d.ts +0 -37
  150. package/dist/plain/concepts.js +0 -283
  151. package/dist/plain/cycles.d.ts +0 -21
  152. package/dist/plain/cycles.js +0 -190
  153. package/dist/plain/errors.d.ts +0 -26
  154. package/dist/plain/errors.js +0 -50
  155. package/dist/plain/files.d.ts +0 -47
  156. package/dist/plain/files.js +0 -161
  157. package/dist/plain/graph.d.ts +0 -107
  158. package/dist/plain/graph.js +0 -194
  159. package/dist/plain/highlight.d.ts +0 -43
  160. package/dist/plain/highlight.js +0 -196
  161. package/dist/plain/index.d.ts +0 -18
  162. package/dist/plain/index.js +0 -18
  163. package/dist/plain/liquid.d.ts +0 -22
  164. package/dist/plain/liquid.js +0 -124
  165. package/dist/plain/markdown.d.ts +0 -103
  166. package/dist/plain/markdown.js +0 -330
  167. package/dist/plain/module-concepts.d.ts +0 -32
  168. package/dist/plain/module-concepts.js +0 -80
  169. package/dist/plain/parser.d.ts +0 -163
  170. package/dist/plain/parser.js +0 -930
  171. package/dist/plain/plain.tmLanguage.json +0 -150
  172. package/dist/plain/project.d.ts +0 -48
  173. package/dist/plain/project.js +0 -155
  174. package/dist/plain/spec.d.ts +0 -152
  175. package/dist/plain/spec.js +0 -265
  176. package/dist/plain/stdlib.d.ts +0 -16
  177. package/dist/plain/stdlib.js +0 -48
  178. package/dist/plain/test-plain-file.d.ts +0 -59
  179. package/dist/plain/test-plain-file.js +0 -232
  180. package/dist/plain-files.d.ts +0 -21
  181. package/dist/plain-files.js +0 -156
  182. package/dist/question-dialog.d.ts +0 -55
  183. package/dist/questioning.d.ts +0 -55
  184. package/dist/questioning.js +0 -109
  185. package/dist/quiet.d.ts +0 -34
  186. package/dist/regenerate/activity.d.ts +0 -227
  187. package/dist/regenerate/activity.js +0 -250
  188. package/dist/regenerate/agent-env.d.ts +0 -51
  189. package/dist/regenerate/agent-env.js +0 -311
  190. package/dist/regenerate/agent-shell.d.ts +0 -54
  191. package/dist/regenerate/agent-shell.js +0 -121
  192. package/dist/regenerate/arbiter.d.ts +0 -68
  193. package/dist/regenerate/arbiter.js +0 -133
  194. package/dist/regenerate/audit.d.ts +0 -69
  195. package/dist/regenerate/audit.js +0 -212
  196. package/dist/regenerate/base-folder.d.ts +0 -70
  197. package/dist/regenerate/base-folder.js +0 -186
  198. package/dist/regenerate/cases.d.ts +0 -12
  199. package/dist/regenerate/cases.js +0 -149
  200. package/dist/regenerate/change-view.d.ts +0 -23
  201. package/dist/regenerate/change-view.js +0 -153
  202. package/dist/regenerate/chunk-plan.d.ts +0 -217
  203. package/dist/regenerate/chunk-plan.js +0 -937
  204. package/dist/regenerate/codebase.d.ts +0 -21
  205. package/dist/regenerate/codebase.js +0 -75
  206. package/dist/regenerate/command-check.d.ts +0 -66
  207. package/dist/regenerate/command-check.js +0 -508
  208. package/dist/regenerate/compaction.d.ts +0 -13
  209. package/dist/regenerate/compaction.js +0 -20
  210. package/dist/regenerate/confine.d.ts +0 -69
  211. package/dist/regenerate/confine.js +0 -311
  212. package/dist/regenerate/conform.d.ts +0 -66
  213. package/dist/regenerate/conform.js +0 -132
  214. package/dist/regenerate/conformance-agents.d.ts +0 -388
  215. package/dist/regenerate/conformance-agents.js +0 -1162
  216. package/dist/regenerate/conformance.d.ts +0 -191
  217. package/dist/regenerate/conformance.js +0 -1035
  218. package/dist/regenerate/conversation-writes.d.ts +0 -10
  219. package/dist/regenerate/conversation-writes.js +0 -100
  220. package/dist/regenerate/credentials.d.ts +0 -18
  221. package/dist/regenerate/credentials.js +0 -88
  222. package/dist/regenerate/debug-log.d.ts +0 -56
  223. package/dist/regenerate/debug-log.js +0 -236
  224. package/dist/regenerate/debugger.d.ts +0 -36
  225. package/dist/regenerate/debugger.js +0 -133
  226. package/dist/regenerate/delivery.d.ts +0 -2
  227. package/dist/regenerate/diagnose-job.d.ts +0 -2
  228. package/dist/regenerate/diagnose-job.js +0 -40
  229. package/dist/regenerate/diagnose.d.ts +0 -46
  230. package/dist/regenerate/diagnose.js +0 -92
  231. package/dist/regenerate/diff-view.d.ts +0 -64
  232. package/dist/regenerate/drift.d.ts +0 -120
  233. package/dist/regenerate/drift.js +0 -285
  234. package/dist/regenerate/environment-error.d.ts +0 -167
  235. package/dist/regenerate/environment-error.js +0 -342
  236. package/dist/regenerate/failure-reports.d.ts +0 -28
  237. package/dist/regenerate/failure-reports.js +0 -79
  238. package/dist/regenerate/job-log.d.ts +0 -30
  239. package/dist/regenerate/job-log.js +0 -105
  240. package/dist/regenerate/job-panel.d.ts +0 -122
  241. package/dist/regenerate/job-panel.js +0 -339
  242. package/dist/regenerate/jobs-tree.d.ts +0 -75
  243. package/dist/regenerate/jobs.d.ts +0 -231
  244. package/dist/regenerate/jobs.js +0 -522
  245. package/dist/regenerate/lanes.d.ts +0 -16
  246. package/dist/regenerate/lanes.js +0 -32
  247. package/dist/regenerate/launch.d.ts +0 -256
  248. package/dist/regenerate/launch.js +0 -689
  249. package/dist/regenerate/ledger-view.d.ts +0 -87
  250. package/dist/regenerate/ledger-view.js +0 -325
  251. package/dist/regenerate/ledger.d.ts +0 -368
  252. package/dist/regenerate/ledger.js +0 -357
  253. package/dist/regenerate/lineage.d.ts +0 -105
  254. package/dist/regenerate/lineage.js +0 -485
  255. package/dist/regenerate/list-arguments.d.ts +0 -21
  256. package/dist/regenerate/list-arguments.js +0 -121
  257. package/dist/regenerate/loop.d.ts +0 -423
  258. package/dist/regenerate/loop.js +0 -2079
  259. package/dist/regenerate/masking.d.ts +0 -19
  260. package/dist/regenerate/masking.js +0 -95
  261. package/dist/regenerate/model-names.d.ts +0 -33
  262. package/dist/regenerate/model-names.js +0 -92
  263. package/dist/regenerate/notes.d.ts +0 -159
  264. package/dist/regenerate/notes.js +0 -446
  265. package/dist/regenerate/os-sandbox.d.ts +0 -93
  266. package/dist/regenerate/os-sandbox.js +0 -283
  267. package/dist/regenerate/panel-dock.d.ts +0 -23
  268. package/dist/regenerate/paths.d.ts +0 -110
  269. package/dist/regenerate/paths.js +0 -190
  270. package/dist/regenerate/plain-palette.d.ts +0 -34
  271. package/dist/regenerate/prompt.d.ts +0 -230
  272. package/dist/regenerate/prompt.js +0 -741
  273. package/dist/regenerate/pulse-files.d.ts +0 -14
  274. package/dist/regenerate/pulse-files.js +0 -63
  275. package/dist/regenerate/records.d.ts +0 -132
  276. package/dist/regenerate/records.js +0 -327
  277. package/dist/regenerate/regenerate.d.ts +0 -106
  278. package/dist/regenerate/regenerate.js +0 -660
  279. package/dist/regenerate/regression.d.ts +0 -58
  280. package/dist/regenerate/regression.js +0 -188
  281. package/dist/regenerate/renames.d.ts +0 -42
  282. package/dist/regenerate/renames.js +0 -185
  283. package/dist/regenerate/requires.d.ts +0 -117
  284. package/dist/regenerate/requires.js +0 -377
  285. package/dist/regenerate/resources.d.ts +0 -57
  286. package/dist/regenerate/resources.js +0 -162
  287. package/dist/regenerate/scripts-being-written.d.ts +0 -19
  288. package/dist/regenerate/scripts-being-written.js +0 -30
  289. package/dist/regenerate/self-check.d.ts +0 -29
  290. package/dist/regenerate/self-check.js +0 -119
  291. package/dist/regenerate/services.d.ts +0 -28
  292. package/dist/regenerate/services.js +0 -158
  293. package/dist/regenerate/shell.d.ts +0 -91
  294. package/dist/regenerate/shell.js +0 -320
  295. package/dist/regenerate/side-panel.d.ts +0 -59
  296. package/dist/regenerate/spec-map-view.d.ts +0 -139
  297. package/dist/regenerate/spec-map.d.ts +0 -160
  298. package/dist/regenerate/spec-map.js +0 -596
  299. package/dist/regenerate/spec-steps.d.ts +0 -180
  300. package/dist/regenerate/spec-steps.js +0 -729
  301. package/dist/regenerate/standing.d.ts +0 -28
  302. package/dist/regenerate/standing.js +0 -30
  303. package/dist/regenerate/state.d.ts +0 -21
  304. package/dist/regenerate/state.js +0 -10
  305. package/dist/regenerate/steering.d.ts +0 -56
  306. package/dist/regenerate/steering.js +0 -119
  307. package/dist/regenerate/stop-report.d.ts +0 -43
  308. package/dist/regenerate/stop-report.js +0 -160
  309. package/dist/regenerate/submit-work.d.ts +0 -44
  310. package/dist/regenerate/submit-work.js +0 -76
  311. package/dist/regenerate/test-kinds.d.ts +0 -85
  312. package/dist/regenerate/test-kinds.js +0 -171
  313. package/dist/regenerate/test-scripts.d.ts +0 -235
  314. package/dist/regenerate/test-scripts.js +0 -843
  315. package/dist/regenerate/testing-steps.d.ts +0 -52
  316. package/dist/regenerate/testing-steps.js +0 -129
  317. package/dist/regenerate/testing.d.ts +0 -150
  318. package/dist/regenerate/testing.js +0 -438
  319. package/dist/regenerate/transcript-view.d.ts +0 -21
  320. package/dist/regenerate/unit-gate.d.ts +0 -27
  321. package/dist/regenerate/unit-gate.js +0 -20
  322. package/dist/regenerate/unit-review.d.ts +0 -152
  323. package/dist/regenerate/unit-review.js +0 -361
  324. package/dist/regenerate/web.d.ts +0 -61
  325. package/dist/regenerate/web.js +0 -256
  326. package/dist/regenerate/workspace.d.ts +0 -12
  327. package/dist/regenerate/workspace.js +0 -99
  328. package/dist/regenerate-cli.d.ts +0 -1
  329. package/dist/resume-line.d.ts +0 -2
  330. package/dist/review/live.d.ts +0 -72
  331. package/dist/review/live.js +0 -166
  332. package/dist/rules.d.ts +0 -20
  333. package/dist/rules.js +0 -47
  334. package/dist/run-report.d.ts +0 -88
  335. package/dist/run-report.js +0 -338
  336. package/dist/screen-padding.d.ts +0 -28
  337. package/dist/self-invocation.d.ts +0 -36
  338. package/dist/self-invocation.js +0 -137
  339. package/dist/sentinel-chat.d.ts +0 -19
  340. package/dist/sentinel-chat.js +0 -221
  341. package/dist/sentinel-check.d.ts +0 -36
  342. package/dist/sentinel-check.js +0 -78
  343. package/dist/sentinel.d.ts +0 -107
  344. package/dist/sentinel.js +0 -599
  345. package/dist/settings.d.ts +0 -45
  346. package/dist/settings.js +0 -378
  347. package/dist/setup.d.ts +0 -97
  348. package/dist/setup.js +0 -428
  349. package/dist/skill-progress.d.ts +0 -46
  350. package/dist/skill.d.ts +0 -102
  351. package/dist/skill.js +0 -147
  352. package/dist/skills.d.ts +0 -54
  353. package/dist/skills.js +0 -111
  354. package/dist/spawn-async.d.ts +0 -18
  355. package/dist/spawn-async.js +0 -35
  356. package/dist/stack.d.ts +0 -80
  357. package/dist/stack.js +0 -206
  358. package/dist/stdlib.d.ts +0 -43
  359. package/dist/stdlib.js +0 -118
  360. package/dist/surface.d.ts +0 -5
  361. package/dist/surface.js +0 -18
  362. package/dist/terminal-images.d.ts +0 -2
  363. package/dist/test-plain-files.d.ts +0 -41
  364. package/dist/test-plain-files.js +0 -172
  365. package/dist/tools.d.ts +0 -101
  366. package/dist/tools.js +0 -242
  367. package/dist/turri-versions.d.ts +0 -71
  368. package/genome/rules/bullet-continuation.md +0 -61
  369. package/genome/rules/concise-specs-examples.md +0 -460
  370. package/genome/rules/concise-specs-integration-examples.md +0 -281
  371. package/genome/rules/concise-specs.md +0 -80
  372. package/genome/rules/definitions.md +0 -107
  373. package/genome/rules/examples/integration-embedded-testing/run_conformance_tests_java.sh +0 -161
  374. package/genome/rules/examples/integration-embedded-testing/run_unittests_java.sh +0 -50
  375. package/genome/rules/exported-concepts.md +0 -39
  376. package/genome/rules/func-specs.md +0 -164
  377. package/genome/rules/impl-reqs.md +0 -68
  378. package/genome/rules/import-modules.md +0 -49
  379. package/genome/rules/integration-embedded-testing.md +0 -273
  380. package/genome/rules/integration-embedded.md +0 -171
  381. package/genome/rules/integration-standalone.md +0 -135
  382. package/genome/rules/integrations.md +0 -136
  383. package/genome/rules/linked-resources.md +0 -76
  384. package/genome/rules/module-structure.md +0 -112
  385. package/genome/rules/project-model.md +0 -69
  386. package/genome/rules/required-concepts.md +0 -44
  387. package/genome/rules/requires-modules.md +0 -81
  388. package/genome/rules/semantic-ids.md +0 -49
  389. package/genome/rules/stdlib.md +0 -37
  390. package/genome/rules/test-plain-files.md +0 -138
  391. package/genome/rules/test-reqs.md +0 -57
  392. package/genome/rules/turri-regeneration.md +0 -66
  393. package/genome/skills/analyze-2-func-specs/SKILL.md +0 -116
  394. package/genome/skills/analyze-func-specs/SKILL.md +0 -137
  395. package/genome/skills/break-down-func-spec/SKILL.md +0 -229
  396. package/genome/skills/consolidate-concepts/SKILL.md +0 -192
  397. package/genome/skills/convert-old-syntax/SKILL.md +0 -68
  398. package/genome/skills/convert-old-syntax/references/rubric.md +0 -11
  399. package/genome/skills/debug-specs/SKILL.md +0 -194
  400. package/genome/skills/implement-conformance-testing-script/SKILL.md +0 -247
  401. package/genome/skills/implement-conformance-testing-script/assets/run_conformance_tests_cypress.ps1 +0 -337
  402. package/genome/skills/implement-conformance-testing-script/assets/run_conformance_tests_golang.ps1 +0 -111
  403. package/genome/skills/implement-conformance-testing-script/assets/run_conformance_tests_java.sh +0 -151
  404. package/genome/skills/implement-conformance-testing-script/assets/run_conformance_tests_python.ps1 +0 -103
  405. package/genome/skills/implement-conformance-testing-script/assets/run_conformance_tests_python.sh +0 -146
  406. package/genome/skills/implement-unit-testing-script/SKILL.md +0 -171
  407. package/genome/skills/implement-unit-testing-script/assets/run_unittests_flutter.ps1 +0 -87
  408. package/genome/skills/implement-unit-testing-script/assets/run_unittests_golang.ps1 +0 -73
  409. package/genome/skills/implement-unit-testing-script/assets/run_unittests_java.sh +0 -82
  410. package/genome/skills/implement-unit-testing-script/assets/run_unittests_python.ps1 +0 -81
  411. package/genome/skills/implement-unit-testing-script/assets/run_unittests_python.sh +0 -102
  412. package/genome/skills/implement-unit-testing-script/assets/run_unittests_react.ps1 +0 -87
  413. package/genome/skills/refactor-module/SKILL.md +0 -218
  414. package/genome/skills/resolve-section-ownership/SKILL.md +0 -64
  415. package/genome/skills/resolve-spec-conflict/SKILL.md +0 -102
  416. package/stdlib/backend/common.plain +0 -25
  417. package/stdlib/backend/conformance/common.plain +0 -12
  418. package/stdlib/backend/conformance/go-gin.plain +0 -9
  419. package/stdlib/backend/conformance/go-nethttp.plain +0 -9
  420. package/stdlib/backend/conformance/java-springboot.plain +0 -9
  421. package/stdlib/backend/conformance/python-django.plain +0 -9
  422. package/stdlib/backend/conformance/python-fastapi.plain +0 -9
  423. package/stdlib/backend/conformance/python-flask.plain +0 -9
  424. package/stdlib/backend/conformance/rust-axum.plain +0 -9
  425. package/stdlib/backend/conformance/typescript-express.plain +0 -9
  426. package/stdlib/backend/conformance/typescript-fastify.plain +0 -9
  427. package/stdlib/backend/conformance/typescript-nestjs.plain +0 -9
  428. package/stdlib/backend/go-gin.plain +0 -18
  429. package/stdlib/backend/go-nethttp.plain +0 -18
  430. package/stdlib/backend/java-springboot.plain +0 -19
  431. package/stdlib/backend/python-django.plain +0 -19
  432. package/stdlib/backend/python-fastapi.plain +0 -23
  433. package/stdlib/backend/python-flask.plain +0 -23
  434. package/stdlib/backend/rust-axum.plain +0 -17
  435. package/stdlib/backend/typescript-express.plain +0 -19
  436. package/stdlib/backend/typescript-fastify.plain +0 -19
  437. package/stdlib/backend/typescript-nestjs.plain +0 -19
  438. package/stdlib/cli/common.plain +0 -17
  439. package/stdlib/cli/conformance/common.plain +0 -11
  440. package/stdlib/cli/conformance/go-cobra.plain +0 -9
  441. package/stdlib/cli/conformance/go-flag.plain +0 -9
  442. package/stdlib/cli/conformance/java-picocli.plain +0 -9
  443. package/stdlib/cli/conformance/python-argparse.plain +0 -9
  444. package/stdlib/cli/conformance/python-click.plain +0 -9
  445. package/stdlib/cli/conformance/python-typer.plain +0 -9
  446. package/stdlib/cli/conformance/rust-clap.plain +0 -9
  447. package/stdlib/cli/conformance/typescript-commander.plain +0 -9
  448. package/stdlib/cli/go-cobra.plain +0 -14
  449. package/stdlib/cli/go-flag.plain +0 -14
  450. package/stdlib/cli/java-picocli.plain +0 -15
  451. package/stdlib/cli/python-argparse.plain +0 -18
  452. package/stdlib/cli/python-click.plain +0 -16
  453. package/stdlib/cli/python-typer.plain +0 -16
  454. package/stdlib/cli/rust-clap.plain +0 -14
  455. package/stdlib/cli/typescript-commander.plain +0 -17
  456. package/stdlib/frontend/angular.plain +0 -17
  457. package/stdlib/frontend/common.plain +0 -17
  458. package/stdlib/frontend/conformance/angular.plain +0 -5
  459. package/stdlib/frontend/conformance/common.plain +0 -11
  460. package/stdlib/frontend/conformance/react-vite.plain +0 -5
  461. package/stdlib/frontend/conformance/sveltekit-spa.plain +0 -5
  462. package/stdlib/frontend/conformance/vue-vite.plain +0 -5
  463. package/stdlib/frontend/react-vite.plain +0 -16
  464. package/stdlib/frontend/sveltekit-spa.plain +0 -16
  465. package/stdlib/frontend/vue-vite.plain +0 -16
  466. package/stdlib/lang/go.plain +0 -13
  467. package/stdlib/lang/java.plain +0 -12
  468. package/stdlib/lang/python.plain +0 -18
  469. package/stdlib/lang/rust.plain +0 -12
  470. package/stdlib/lang/typescript.plain +0 -13
  471. package/stdlib/library/common.plain +0 -15
  472. package/stdlib/library/conformance/common.plain +0 -9
  473. package/stdlib/library/conformance/go.plain +0 -9
  474. package/stdlib/library/conformance/java-gradle.plain +0 -9
  475. package/stdlib/library/conformance/java-maven.plain +0 -9
  476. package/stdlib/library/conformance/python.plain +0 -9
  477. package/stdlib/library/conformance/rust.plain +0 -9
  478. package/stdlib/library/conformance/typescript.plain +0 -9
  479. package/stdlib/library/go.plain +0 -12
  480. package/stdlib/library/java-gradle.plain +0 -13
  481. package/stdlib/library/java-maven.plain +0 -13
  482. package/stdlib/library/python.plain +0 -13
  483. package/stdlib/library/rust.plain +0 -12
  484. package/stdlib/library/typescript.plain +0 -15
package/dist/extension.js CHANGED
@@ -1,3216 +1,19 @@
1
- // Whether the terminal shows images, before anything draws: the banner's jellyfish is a picture or text.
2
- import "./terminal-images.js";
3
- import { moduleOfTestPlainFile, refuseTestPlainFile, testPlainFileRefusal } from "./test-plain-files.js";
4
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
5
- import { basename, dirname, join, relative, resolve, sep } from "node:path";
6
- import { conversationCommand, conversationSettled, conversationWriting } from "./regenerate/conversation-writes.js";
7
- import { fileURLToPath } from "node:url";
8
- import { allocateImageId, Box, getCapabilities, getPngDimensions, isKeyRelease, isKeyRepeat, matchesKey, renderImage, Text, wrapTextWithAnsi } from "@earendil-works/pi-tui";
9
- import { defineTool, getMarkdownTheme, UserMessageComponent } from "@earendil-works/pi-coding-agent";
10
- import { Type } from "typebox";
11
- import { CODING_MODEL_ENV } from "./chat-models.js";
12
- import { AGENT_ROLES, CONFIG_FILE, configForSpec, readConfigFile, configModuleFor, hasProjectConfig, LEGACY_CONFIG_FILE, projectConfigFile, moduleConfigFile, moduleConfigFileIn, configModuleOf, moduleConfigsOf, withConfigModule, modelOnly, modelSpec, projectModels, readProjectConfig, roleModel, splitModelSpec, configLines } from "./config.js";
13
- import { projectDirOf, skillRunDir } from "./regenerate/paths.js";
14
- import { sweepOrphanedGroups } from "./regenerate/shell.js";
15
- import { readScript, scriptAgainstMachine, stackOnMachine, toolchainsBlock } from "./stack.js";
16
- import { sandboxAvailable, sandboxSummary } from "./regenerate/os-sandbox.js";
17
- import { findTestScripts, scriptKindOfSkill } from "./regenerate/test-scripts.js";
18
- import { writingScript } from "./regenerate/scripts-being-written.js";
19
- import { applyBedrockRegion } from "./bedrock-region.js";
20
- import { bannerWarnings } from "./turri-versions.js";
21
- import { CONFORMANCE_OFF_REFUSAL, conformanceBlock, conformanceTestsOn, conformanceTestsOnIn, turnOnConformanceTests } from "./conformance-switch.js";
22
- import { BACKGROUND_NOTE, doneLine, failedTask, ownChanges, runDetails, skillRunDelivery, startedText } from "./background-skills.js";
23
- import { createAskUserTool } from "./tools.js";
24
- import { asksFromScratch, asksWholeChain, driftTool, endWait, fromWorkingDir, haltLaunched, haltTool, loopReply, startWait, toldByWaitingCall, MODEL_PARAM, regenerateTool, stopJob, WAIT_PARAM, whenBuildable, WORKING_DIR_PARAM } from "./loop-tools.js";
25
- import { createWebTools } from "./regenerate/web.js";
26
- import { describeGates, interruptedRun, runSkill } from "./genome.js";
27
- import { unqueue } from "./chat-waiting.js";
28
- import { skillStatus } from "./skill.js";
29
- import { runningLaunched, stopLaunched } from "./regenerate/launch.js";
30
- import { launchTool } from "./launch-tools.js";
31
- import { createSessionLaunches, launchedDir, launchedNote, replacedNote } from "./launch-session.js";
32
- import { describeLaunchLine, launchText } from "./launch-track.js";
33
- import { checkedSpecs } from "./sentinel-check.js";
34
- import { askedForCommandLine, refusal, selfInvocation, TOOLS_NOT_CLI } from "./self-invocation.js";
35
- import { NEW_PROJECT } from "./new-project.js";
36
- import { describeResolution, resolveModel } from "./regenerate/model-names.js";
37
- import { checkPlainFile, formatCheckResults } from "./plain/check.js";
38
- import { checkPlainTool } from "./parse-tool.js";
39
- import { changedFiles, projectFiles } from "./plain-files.js";
40
- import { whyFailed } from "./regenerate/diagnose-job.js";
41
- import { didNotLand } from "./regenerate/failure-reports.js";
42
- import { conformanceRefusal, createWorkLoop, TestingStepsMissing, describeModules, isUpToDate } from "./regenerate/loop.js";
43
- import { brandNeon, brandPink, plainPaint } from "./regenerate/plain-palette.js";
44
- import { halfBlocks, JELLYFISH_FRAME_MS, JELLYFISH_REST, JELLYFISH_SEQUENCE, JELLYFISH_TEXT_FRAMES } from "./jellyfish.js";
45
- import { createJobPanel, didNotPass, keyPressed, PANEL_KEY, spinner } from "./regenerate/job-panel.js";
46
- import { clickToFocus, dockedWidth, narrowChat, shade, shadeChat } from "./regenerate/panel-dock.js";
47
- import { overPictureRow, PICTURE_AT } from "./picture-row.js";
48
- import { padScreen, paddedColumns, paddedRows, SCREEN_PADDING } from "./screen-padding.js";
49
- import { skillAboutLine, skillProgressLine } from "./skill-progress.js";
50
- import { createSidePanel } from "./regenerate/side-panel.js";
51
- import { createSpecMapSource, defaultMapFiles } from "./regenerate/spec-map.js";
52
- import { createSpecMapState } from "./regenerate/spec-map-view.js";
53
- import { createJobsTreeState, selectJob } from "./regenerate/jobs-tree.js";
54
- import { describeDiagnosis, diagnoseFailure } from "./regenerate/diagnose.js";
55
- import { HISTORY_DIR, historyLog } from "./regenerate/lineage.js";
56
- import { defaultBuildDir } from "./regenerate/paths.js";
57
- import { describeTurnIncident, describeUsage, JobStoppedError, onModelEvent } from "./regenerate/activity.js";
58
- import { ledgerWanted, startLedger } from "./regenerate/ledger.js";
59
- import { describePastPulse, describeRuns, earlierPulses, ledgerProjects } from "./regenerate/ledger-view.js";
60
- import { doctorTool } from "./doctor-tool.js";
61
- import { describeSpecConflict } from "./regenerate/stop-report.js";
62
- import { inheritProviders, inheritThinkingLevel } from "./pi.js";
63
- import { LOADING_PROVIDERS } from "./installed-providers.js";
64
- import { machineChange, machineChangeReason, runsBuiltCode, writesPlain } from "./regenerate/command-check.js";
65
- import { beginCapture, captureConsole, describeCaptured, dropNoise } from "./quiet.js";
66
- import { loadRules, renderRulesBlock } from "./rules.js";
67
- import { registerSettings, ruleNames } from "./settings.js";
68
- import { writeSetting } from "./config-edit.js";
69
- import { describeStdlib } from "./stdlib.js";
70
- import { DECLINED, peekKeyListener, runAsk } from "./ask.js";
71
- import { QuestionDialog } from "./question-dialog.js";
72
- import { catalogueLine, chosenCommand, createCommandGate, startPicked, discoverSkills, leftOutNote, startedByCommandOnly } from "./skills.js";
73
- import { supersededByTurri } from "./chat-skills.js";
74
- import { conversationIdentity } from "./identity.js";
75
- import { setSurface, surfaceOf } from "./surface.js";
76
- import { createChats, scopedToChat } from "./chats.js";
77
- import { ignoredGuidance, keepGuidance, landedNote, pulseEndsBlock, SENTINEL, SENTINEL_TOOLS, sentinelBrief, sentinelCheckBrief, sentinelPrompt, sentinelSetting, sentinelStartNotice, specConflictNotice } from "./sentinel.js";
78
- import { noticeDialogs, registerSentinel } from "./sentinel-chat.js";
79
- import { currentChat } from "./chat-scope.js";
80
- import { registerChats } from "./chat-commands.js";
81
- import { turriIdentity } from "./environment.js";
82
- import { answerSideQuestion, askWithAsides, BTW_HOW, runningSkill, skillRunStarted, skillSessionText, transcriptOf } from "./btw.js";
83
- import { createJobRegistry, defaultParallelJobs, describeJob, formatDuration, pulseName, shouldWait, STOPPED_ON_REQUEST, } from "./regenerate/jobs.js";
84
1
  /**
85
- * Makes gated skills reachable from a conversation.
2
+ * turri as a pi extension, for pi to load itself: `turri` builds the session's own extension into pi (pi-launch.ts), and
3
+ * this file is what pi loads when it is given turri's file - an older turri wrote one into every pi. It is the session
4
+ * pi-launch.ts opened in this process, found on the process rather than in this module: pi loads an extension's file
5
+ * through its own loader, which may give it a module of its own.
86
6
  *
87
- * The conversational agent keeps ordinary progressive disclosure - it reads the
88
- * skill descriptions and decides when one applies. What it does not get is the
89
- * choice of how to run it: `cultivate` hands the work to the graph, which owns
90
- * the steps, the gates and the judges. The agent asks for the skill; it does not
91
- * perform it.
7
+ * With no session in the process - a plain pi, or the core reading the person's extensions for their providers - it is
8
+ * nothing: turri starts with `turri`, and a plain pi stays pi.
92
9
  */
93
- const PACKAGE_ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
94
- /**
95
- * Puts a skill step's question to the person, when there is one to ask.
96
- *
97
- * A skill runs inside one tool call, in its own session, so its dialogs are not
98
- * conversation turns and nothing it asks would otherwise reach the transcript. Every
99
- * exchange is therefore reported back, so the interview is visible while it happens and
100
- * survives in the tool's result afterwards.
101
- */
102
- /**
103
- * What a question gets with nobody to answer it - print, json and rpc modes. What is the agent's to decide it decides; the
104
- * person's own files it leaves as they are, as it would have without their yes - a testing script it finds wrong is said,
105
- * not rewritten.
106
- */
107
- export const NO_USER_ANSWER = "No user is available to answer. Decide yourself what is yours to decide - the ***plain you were asked to write, a choice the " +
108
- "***plain leaves open - and say in your report what you assumed. What you asked because it is the person's - their testing " +
109
- "scripts, their config, any file of theirs you would replace or delete - leave as it is: say what you would change and why, " +
110
- "and go on without it.";
111
- export function askUserVia(ctx, onExchange,
112
- /** Given, "/btw ..." typed as an answer is a side question: answered with this, and the question asked again. */
113
- aside,
114
- /** A host's own dialogs (TurriHost.dialogs), the question put in them instead of the terminal's. */
115
- dialogs) {
116
- return async (request) => {
117
- if (dialogs === undefined && !ctx.hasUI) {
118
- return NO_USER_ANSWER;
119
- }
120
- // Declined - ctrl+c at it, the host's decline, or the turn that asked it stopped: the dialog open is closed, no other is
121
- // opened, and it comes back as DECLINED.
122
- const { declining, decline, done } = asking(ctx.signal);
123
- // The question has the keys: ctrl+h is caught here, or it would never reach the shortcut, which only the chat's editor sees.
124
- const unhook = dialogs === undefined ? hookPeekKey(ctx) : () => { };
125
- if (dialogs === undefined)
126
- ctx.ui.setWorkingMessage("waiting for your answer");
127
- try {
128
- const io = dialogs !== undefined ? hostDialogs(dialogs, declining) : terminalDialogs(ctx, declining, decline);
129
- const asking = (asked) => runAsk(asked, io);
130
- const bare = { ...request, said: undefined };
131
- const given = declining.declined ? DECLINED : aside !== undefined ? await askWithAsides(bare, asking, aside) : await asking(bare);
132
- const answer = declining.declined ? DECLINED : given;
133
- // Kept: what was shown with it, and what it said before it.
134
- onExchange(request.question, answer, [request.context, request.said].map((part) => part?.trim() ?? "").filter((part) => part !== "").join("\n\n") || undefined);
135
- return answer;
136
- }
137
- finally {
138
- done();
139
- unhook();
140
- if (dialogs === undefined)
141
- ctx.ui.setWorkingMessage();
142
- }
143
- };
144
- }
145
- /**
146
- * A question being asked, until `done`: declined by `decline` - ctrl+c at it - by the host (`Turri.decline`, through the
147
- * chat's `asking`) or by `turn` being stopped.
148
- */
149
- function asking(turn) {
150
- const declining = { declined: turn?.aborted === true, close: undefined };
151
- const decline = () => {
152
- declining.declined = true;
153
- declining.close?.();
154
- };
155
- turn?.addEventListener("abort", decline, { once: true });
156
- const open = currentChat()?.asking;
157
- open?.add(decline);
158
- return {
159
- declining,
160
- decline,
161
- done: () => {
162
- turn?.removeEventListener("abort", decline);
163
- open?.delete(decline);
164
- },
165
- };
166
- }
167
- /**
168
- * A host's dialogs, for a question that can be declined: the question over at once, its dialog told through its
169
- * `signal` - the host's to close.
170
- */
171
- function hostDialogs(dialogs, declining) {
172
- const until = (asked) => {
173
- if (declining.declined)
174
- return Promise.resolve(undefined);
175
- const over = new AbortController();
176
- return Promise.race([
177
- asked(over.signal),
178
- new Promise((resolve) => (declining.close = () => {
179
- over.abort();
180
- resolve(undefined);
181
- })),
182
- ]);
183
- };
184
- return {
185
- select: (title, options, context, at) => until((signal) => dialogs.select(title, options, context, at, { signal })),
186
- input: (title, context) => until((signal) => dialogs.input(title, context, { signal })),
187
- };
10
+ const SESSION = Symbol.for("@turri-dev/cli/session");
11
+ /** The session pi-launch.ts opened in this process, for an extension pi loads itself. */
12
+ export function setProcessTurri(turri) {
13
+ globalThis[SESSION] = turri;
188
14
  }
189
- /**
190
- * The terminal's dialogs: turri's own, a long brief scrolling above the question and the options always showing
191
- * (question-dialog.ts). ctrl+c declines the question - each one it is pressed at, however many in a row; what asked
192
- * goes on. The turn, and a skill asking in it, is stopped by ctrl+c with no question open.
193
- */
194
- function terminalDialogs(ctx, declining, decline) {
195
- const dialog = (question, context, options, selected) => declining.declined
196
- ? Promise.resolve(undefined)
197
- : ctx.ui.custom((tui, theme, _keybindings, done) => {
198
- const shown = new QuestionDialog({
199
- question,
200
- ...(context !== undefined ? { context } : {}),
201
- ...(options !== undefined ? { options } : {}),
202
- ...(selected !== undefined ? { selected } : {}),
203
- rows: () => paddedRows(tui.terminal.rows),
204
- style: { accent: (text) => theme.fg("accent", text), muted: (text) => theme.fg("muted", text), bold: (text) => theme.bold(text) },
205
- done: (answer) => {
206
- if (questionShown === shown)
207
- questionShown = undefined;
208
- done(answer);
209
- },
210
- requestRender: () => tui.requestRender(),
211
- interrupt: decline,
212
- });
213
- declining.close = () => shown.dismiss();
214
- questionShown = shown;
215
- return shown;
216
- });
217
- return {
218
- select: (title, options, context, at) => dialog(title, context, options, at),
219
- input: (title, context) => dialog(title, context),
220
- };
221
- }
222
- /** The side panel, as a question open in the chat reaches it: set once the extension has its panel. */
223
- let questionPeek;
224
- /**
225
- * The question open in the chat now, if any. The side panel gives the keys back to it: pi would give them to what had the
226
- * focus when the panel first opened, and a panel kept beside the chat outlives that question - the keys would go to a
227
- * dialog already answered, and nothing would take them.
228
- */
229
- let questionShown;
230
- /** A widget with nothing to draw: below the editor, it takes no line. */
231
- const PEEK_KEY_WIDGET = "turri-peek-key";
232
- /**
233
- * While a question is open, ctrl+h opens the side panel over it - the question waits under it. pi gives an extension's
234
- * shortcut only the keys its editor sees, and a question has the focus: the key is caught on the terminal's input
235
- * instead. While the panel shows, its own listener has ctrl+h - to close it - and this lets it be.
236
- */
237
- function hookPeekKey(ctx) {
238
- if (questionPeek === undefined)
239
- return () => { };
240
- const peek = questionPeek;
241
- ctx.ui.setWidget(PEEK_KEY_WIDGET, (tui) => {
242
- const unlisten = tui.addInputListener(peekKeyListener({ open: () => peek.open(ctx), shown: () => peek.shown() }));
243
- return { render: () => [], invalidate() { }, dispose: unlisten };
244
- }, { placement: "belowEditor" });
245
- return () => ctx.ui.setWidget(PEEK_KEY_WIDGET, undefined);
246
- }
247
- /**
248
- * ask_user, for the conversation's agent too - the same dialog a skill's interview uses: options to
249
- * pick from, several at once, "Something else…" to type instead, "Chat about this" to talk it over in
250
- * the chat first - so a question with a handful of answers is picked, not typed.
251
- */
252
- /**
253
- * ask_user, for the conversation. `afterAnswer` may add to what an answer tells the model - a skill the person picked,
254
- * to start at once.
255
- */
256
- export function chatAskUserTool(dialogs, afterAnswer) {
257
- let conversation;
258
- const tool = createAskUserTool((request) => (conversation !== undefined ? askUserVia(conversation, () => { }, undefined, dialogs)(request) : Promise.resolve("No user is available to answer.")), undefined, undefined, undefined, "reply");
259
- return {
260
- ...tool,
261
- promptGuidelines: [
262
- ...(tool.promptGuidelines ?? []),
263
- "When a question to the user has a handful of plausible answers - a choice, yes or no, which of these - ask it with ask_user rather than in your reply.",
264
- ],
265
- async execute(...args) {
266
- conversation = args[4];
267
- const result = await tool.execute(...args);
268
- const answer = result.details?.answer;
269
- const note = answer !== undefined && answer !== "" ? afterAnswer?.(answer) : undefined;
270
- return note !== undefined ? { ...result, content: [...result.content, { type: "text", text: note }] } : result;
271
- },
272
- };
273
- }
274
- /**
275
- * The conversation's system prompt for a turn: pi's, turri's identity - with the host's surface in place of the
276
- * terminal's, when it has one - and turri's blocks; then the host's last word on it.
277
- */
278
- function conversationSystemPrompt(base, host, blocks) {
279
- const prompt = [base, conversationIdentity(host.surface), ...blocks].filter((part) => part !== "").join("\n\n");
280
- return host.systemPrompt !== undefined ? host.systemPrompt(prompt) : prompt;
281
- }
282
- /** Whether the person has been told which of pi's skills turri left out: once a session, not once a chat. */
283
- let leftOutSaid = false;
284
- /** The host each session's jobs report to. */
285
- const hosts = new WeakMap();
286
- /**
287
- * A turri session: its job registry and work loop, the ledger, and its chats, each with turri's extension in it
288
- * (chats.ts). The terminal makes one as it starts (pi-launch.ts), a host with `createTurri` (host.ts); `persist`
289
- * records the open chats for `turri --continue`.
290
- */
291
- export function createTurriCore(host = {}, options = {}) {
292
- dropNoise();
293
- const cwd = process.cwd();
294
- // The AWS region the project's Bedrock models need, before any model is called - a host has no shell to export it in.
295
- applyBedrockRegion(cwd);
296
- let core;
297
- // Finished work is announced twice, to two audiences, because pi treats them differently - see ChatInstance.announce:
298
- // in the chat that asked for it, or the one shown when that is closed.
299
- const jobs = createJobRegistry({
300
- // The loop's plan changed - a module being planned, or planned: the live panel shows it at once.
301
- onNotify: () => {
302
- core?.jobsChanged();
303
- host.onPlanChange?.();
304
- },
305
- // A job that fails is run once more; failing again, it and every job behind it fail, and the
306
- // harness - which can read the skills, the rules, the code, the tests and turri itself -
307
- // works out why, and what has to be done.
308
- retries: 1,
309
- // Modules that share nothing build side by side - as many at once as the machine has room for.
310
- maxRunning: parallelJobs(cwd),
311
- diagnose: async (job, failures, jobLog) => {
312
- const diagnosis = await diagnoseFailure({
313
- job,
314
- failures,
315
- projectDir: cwd,
316
- harnessDir: PACKAGE_ROOT,
317
- jobLog,
318
- // The coding model the job ran on - its model alone: the diagnosis thinks as its role has it.
319
- model: modelSpec(modelOnly(job.model ?? modelSpec(projectModels(readProjectConfig(cwd)).coding))),
320
- });
321
- return diagnosis !== undefined ? describeDiagnosis(diagnosis) : undefined;
322
- },
323
- onChange: (job) => {
324
- core?.jobsChanged();
325
- host.onJobChange?.(job);
326
- },
327
- onFinish: (job) => {
328
- core?.jobsChanged();
329
- host.onJobChange?.(job);
330
- // Queued again as another job: that one says how it went.
331
- if (job.replacedBy !== undefined)
332
- return;
333
- // Gone wrong: the next ctrl+h opens on it - the live panel that showed it is gone with the last pulse.
334
- if (job.status === "failed" || job.status === "stopped" || didNotPass(job))
335
- needsLooking.set(jobs, job.id);
336
- core?.jobFinished(job);
337
- },
338
- });
339
- // The session's launches (docs/launch.md): a codebase's one at a time, the newest commit winning, on the coding model
340
- // of the codebase - and what the sentinel waits on of them.
341
- const launches = createSessionLaunches({
342
- cwd,
343
- jobs,
344
- model: (plainFile) => launchModel(workLoops.get(jobs)?.from.ctx, plainFile),
345
- onChange: (launch) => {
346
- core?.jobsChanged();
347
- try {
348
- host.onLaunch?.(launch);
349
- }
350
- catch {
351
- /* a host that throws still has the launch in the track */
352
- }
353
- core?.launchChanged(launch);
354
- },
355
- });
356
- sessionLaunches.set(jobs, launches);
357
- core = createChats({
358
- cwd,
359
- launches,
360
- host,
361
- jobs,
362
- extension: (pi, link) => turriExtension(pi, core, link),
363
- // A finished pulse goes to the sentinel when the project wants one - read as each pulse finishes - the person asked
364
- // first under `sentinel: ask`, and what they choose for the project written.
365
- sentinel: () => sentinelSetting(cwd),
366
- sentinelStart: (job) => sentinelStartNotice(job, cwd),
367
- setSentinel: (on) => void writeSetting(cwd, "sentinel", on),
368
- ignored: (notice) => keepGuidance(cwd, ignoredGuidance(notice)),
369
- ...(options.persist !== undefined ? { persist: options.persist } : {}),
370
- ...(options.dialogs !== undefined ? { dialogs: options.dialogs } : {}),
371
- });
372
- const session = core;
373
- hosts.set(jobs, host);
374
- // What the model is told of where the person watches the work, deep in the tools too: the host's surface, or the terminal.
375
- setSurface(jobs, host.surface);
376
- // What this session does, as facts, in the project's .turri/ledger - a pulse's own in its project. Said once, in the
377
- // chat shown, when it cannot be written.
378
- if (ledgerWanted()) {
379
- startLedger({
380
- mode: Object.keys(host).length > 0 ? "host" : "chat",
381
- project: cwd,
382
- warn: (message) => session.notify(message, "warning"),
383
- });
384
- }
385
- // What a turri that was killed left running - its commands' process groups - stopped as this one starts.
386
- const orphans = sweepOrphanedGroups();
387
- if (orphans > 0)
388
- session.notify(`Stopped ${orphans} process group${orphans === 1 ? "" : "s"} a turri that was killed left running.`, "info");
389
- // A pulse's provider failing and waited out, or a turn turri ended itself: said in the chat shown as it happens - the
390
- // job panel's activity holds it too, but scrolls by.
391
- onModelEvent((event) => {
392
- const line = describeTurnIncident(event);
393
- if (line !== undefined)
394
- session.notify(event.job !== undefined ? `${event.job}: ${line}` : line, "warning");
395
- });
396
- // Sub-agents think as hard as the chat that started them, not pi's default - and reach the providers its extensions
397
- // registered - a company's own gateway - which they load none of.
398
- inheritThinkingLevel(() => session.instanceInScope()?.thinkingLevel());
399
- inheritProviders(() => session.instanceInScope()?.context()?.modelRegistry);
400
- return core;
401
- }
402
- /** The session pi builds turri's extension into when it is given turri's file rather than a session's factory. */
403
- const SESSION = Symbol.for("turri.session");
404
- /** The session of this process: pi-launch.ts's, or one made as pi first builds the extension (`pi -e src/extension.ts`). */
405
- export function processSession(make = () => createTurriCore()) {
406
- const global = globalThis;
407
- return (global[SESSION] ??= make());
408
- }
409
- // Loaded as nothing while the person's pi extensions are loaded only for their providers (installed-providers.ts): an older
410
- // turri installed into every pi is among them, and would start a session of its own.
411
- const extension = (pi) => (process.env[LOADING_PROVIDERS] === "1" ? undefined : processSession().extension(pi));
15
+ const extension = (pi) => {
16
+ const turri = globalThis[SESSION];
17
+ return turri?.extension(pi);
18
+ };
412
19
  export default extension;
413
- /**
414
- * The session's work loop, for a host to read: made with the first chat's context - the models it plans with - when no
415
- * chat has asked for work yet.
416
- */
417
- export function sessionLoop(session) {
418
- const known = workLoops.get(session.jobs)?.loop;
419
- if (known !== undefined)
420
- return known;
421
- const live = session.shownChat()?.session ?? session.chats().map((info) => session.session(info.id)).find((found) => found !== undefined);
422
- if (live === undefined)
423
- throw new Error("No chat is open yet: the work loop plans with a chat's models.");
424
- return workLoopFor(session.jobs, session.cwd, live.extensionRunner.createContext());
425
- }
426
- /**
427
- * turri's extension, built into one chat of the session: its tools, commands and handlers run in the chat's scope -
428
- * its id on the pulses it asks for - on the session's job registry and work loop.
429
- */
430
- function turriExtension(api, session, link) {
431
- const pi = scopedToChat(api, link.scope);
432
- const { cwd, host, jobs } = session;
433
- // The session's sentinel: its own prompt and tools - the project to read, notices, its guidance - and nothing that
434
- // changes the project or starts work.
435
- const isSentinel = link.role === SENTINEL;
436
- const hostSentinelTools = isSentinel ? (host.sentinel?.tools ?? []) : [];
437
- const sentinelAllowed = new Set([...SENTINEL_TOOLS, ...hostSentinelTools.map((tool) => tool.name)]);
438
- // Its resume: the module brought up again on the session's work loop, as regenerate brings it up.
439
- const resumeModule = async (plainFile) => describeModules(await sessionLoop(session).bringUp(resolve(cwd, plainFile)));
440
- if (isSentinel)
441
- registerSentinel(pi, session, cwd, hostSentinelTools, sentinelAllowed, resumeModule);
442
- const dialogs = link.dialogs ?? host.dialogs;
443
- // turri's own skills, and the project's - .turri/skills, .agents/skills (skills.ts).
444
- const discoveredSkills = discoverSkills(PACKAGE_ROOT, cwd);
445
- // What the background work is doing right now, drawn above the editor while it runs.
446
- const panel = createJobPanel(() => shownJobs(jobs));
447
- // The chat's context, as its tools and handlers were last given it: for its model and its providers.
448
- let lastContext;
449
- const contextNow = () => {
450
- try {
451
- void lastContext?.model;
452
- return lastContext;
453
- }
454
- catch {
455
- // Rebuilt by pi since - a /reload, a /fork: its new extension has the context now.
456
- return undefined;
457
- }
458
- };
459
- // Finished work is announced twice, to two audiences, because pi treats them differently.
460
- // An entry is drawn the moment it is appended: the person sees the job end, now. The agent
461
- // gets the full report as a hidden message that starts a turn of its own - at once when it is
462
- // idle, else as soon as the turn it is in ends (a follow-up, never cutting into a reply or an
463
- // interview) - so it reacts to every job that ends without waiting for the person to speak:
464
- // does what the project's guidance says to do then (launch what was built, say), or says
465
- // what finished. In the chat that asked for the pulse, shown or not.
466
- const announce = (job) => {
467
- announceJob(pi, job);
468
- // A pulse a call of this chat waits for is told in that call's reply: a turn of its own would say it again.
469
- if (toldByWaitingCall(jobs, job) && job.specConflict === undefined)
470
- return;
471
- // A spec that contradicts itself is the person's to settle, now: the agent is started on it.
472
- if (job.specConflict !== undefined) {
473
- void pi.sendMessage({ customType: "turri_spec_conflict", content: specConflictTask(job.specConflict), display: false, details: { jobId: job.id } }, { triggerTurn: true });
474
- return;
475
- }
476
- let launching = false;
477
- try {
478
- launching = readProjectConfig(cwd, job.configModule).launchAfterPulse === true;
479
- }
480
- catch {
481
- /* a config that cannot be read launches nothing */
482
- }
483
- void pi.sendMessage({
484
- customType: "turri_job",
485
- content: pulseEndNote(job, { launching }),
486
- display: false,
487
- details: { jobId: job.id, status: job.status },
488
- }, { triggerTurn: true, deliverAs: "followUp" });
489
- };
490
- // The sentinel's: what a pulse that ended is, told to its agent in a conversation of its own for the pulse. The hidden
491
- // message is the conversation's first entry - a host splits the sentinel's work by pulse on it - so the pulse's end is
492
- // not drawn above it here: the person's chat shows it. Told once what runs holds its commit (chats.ts readyFor).
493
- const brief = async (job, context) => {
494
- const launch = sessionLaunches.get(jobs)?.forPulse(job) ?? { later: [], laterSpecs: [], running: [] };
495
- const content = sentinelBrief(job, {
496
- project: cwd,
497
- ...(context.asked !== undefined ? { asked: context.asked } : {}),
498
- ...(context.focused !== undefined ? { focused: context.focused } : {}),
499
- launch,
500
- reaction: JOB_FINISHED_REACTION,
501
- });
502
- void pi.sendMessage({ customType: "turri_sentinel_pulse", content, display: false, details: { jobId: job.id, status: job.status } }, { triggerTurn: true });
503
- };
504
- // The sentinel's: functional specs a host asked it to check, in what is launched of the module - told, in a
505
- // conversation of its own for the check, its hidden first message `turri_sentinel_check`. It launches nothing.
506
- const briefCheck = async (check, context) => {
507
- const current = sessionLaunches.get(jobs)?.track.current(check.module);
508
- const commit = current?.short;
509
- const content = sentinelCheckBrief(check, {
510
- specs: checkedSpecs(check),
511
- running: runningLaunched(check.module),
512
- ...(commit !== undefined ? { commit } : {}),
513
- ...(current?.status === "failed" ? { failed: { id: current.id, ...(launchText(current) !== "" ? { summary: launchText(current) } : {}) } } : {}),
514
- ...(current !== undefined ? { dir: launchedDir(current) } : {}),
515
- ...(context.focused !== undefined ? { focused: context.focused } : {}),
516
- });
517
- void pi.sendMessage({ customType: "turri_sentinel_check", content, display: false, details: { checkId: check.id, module: check.module, funcIds: check.funcIds } }, { triggerTurn: true });
518
- };
519
- // The sentinel's: its check carried on in the conversation it was in, once its codebase was launched again.
520
- const resume = async (work) => {
521
- const launches = sessionLaunches.get(jobs);
522
- if (launches === undefined)
523
- return;
524
- const content = launches.resumeText(work);
525
- void pi.sendMessage({ customType: "turri_sentinel_resume", content, display: false }, { triggerTurn: true });
526
- };
527
- // A launch this chat is to hear of ended: its agent told how it went, to tell the person.
528
- const launched = (launch) => tellLaunch(pi, jobs, launch);
529
- // A pulse ended, with the sentinel on: said in the chat. One that landed is told to its agent too, to tell the person
530
- // it landed and what the sentinel does with it - and nothing more: the pulse is the sentinel's. ***plain that
531
- // contradicts itself is put to the person at once, by turri itself, as the chat would have been started on it.
532
- const landed = (job, options = {}) => {
533
- announceJob(pi, job);
534
- if (job.specConflict !== undefined)
535
- session.notice(specConflictNotice(job, specConflictTask(job.specConflict)));
536
- if (options.tell !== true || toldByWaitingCall(jobs, job))
537
- return;
538
- // A host that shows the person the pulse's end itself: the chat knows of it - in order, with no turn of its own.
539
- const shown = host.pulseEndsShown === true;
540
- let launching = false;
541
- try {
542
- launching = readProjectConfig(cwd, job.configModule).launchAfterPulse === true;
543
- }
544
- catch {
545
- /* a config that cannot be read launches nothing */
546
- }
547
- void pi.sendMessage({ customType: "turri_job_landed", content: landedNote(job, { shown, launching }), display: false, details: { jobId: job.id, status: job.status } }, shown ? { triggerTurn: false } : { triggerTurn: true, deliverAs: "followUp" });
548
- };
549
- const notices = noticeDialogs(pi, session, link, contextNow);
550
- link.live({
551
- announce,
552
- landed,
553
- brief,
554
- briefCheck,
555
- resume,
556
- launched,
557
- notice: notices.put,
558
- noticeOver: notices.over,
559
- concluded: notices.concluded,
560
- act: (task) => {
561
- void pi.sendMessage({ customType: "turri_notice_answer", content: task, display: false }, { triggerTurn: true, deliverAs: "followUp" });
562
- },
563
- jobsChanged: () => panel.refresh(),
564
- thinkingLevel: () => pi.getThinkingLevel(),
565
- context: contextNow,
566
- });
567
- pi.on("session_start", (_event, ctx) => {
568
- lastContext = ctx;
569
- });
570
- pi.on("before_agent_start", (_event, ctx) => {
571
- lastContext = ctx;
572
- });
573
- // The ***plain rules go into the system prompt in full, every turn. The block is
574
- // identical each time, so it sits inside the cached prefix rather than invalidating it.
575
- // With them, the instruction to do turri's work with its tools rather than its command
576
- // line - enforced below, not only asked for.
577
- const rules = loadRules(join(PACKAGE_ROOT, "genome", "rules"), readProjectConfig(cwd).rulesOff ?? []);
578
- // Laid out again once rules-off changes - /settings changes it as turri runs - and the same block in between.
579
- let rulesKept = { off: (readProjectConfig(cwd).rulesOff ?? []).join(","), block: chatRulesBlock(rules) };
580
- const rulesBlock = () => {
581
- const off = readProjectConfig(cwd).rulesOff ?? [];
582
- if (off.join(",") !== rulesKept.off)
583
- rulesKept = { off: off.join(","), block: chatRulesBlock(loadRules(join(PACKAGE_ROOT, "genome", "rules"), off)) };
584
- return rulesKept.block;
585
- };
586
- // What the project's config.turri.yaml says, read afresh every turn: the agent answers from it, and
587
- // the tools default to it.
588
- // pi's skills that turri has already - its own and the project's, run with cultivate, and any about ***plain from
589
- // another tool - are left out of the list the conversation is offered (chat-skills.ts); the person is told once.
590
- const turriRuns = new Set(discoveredSkills.skills.map((skill) => skill.name));
591
- // What the modules need of this machine: worked out when a turn first asks, and after a turn when a spec changed - never
592
- // as the session starts, which a host would wait on, and never while a message waits to be sent once it is known.
593
- const machine = machineNeeds(cwd);
594
- pi.on("agent_settled", () => machine.refreshSoon());
595
- pi.on("before_agent_start", (event, ctx) => {
596
- const offered = event.systemPromptOptions.skills;
597
- const leftOut = offered.filter((skill) => supersededByTurri(skill, turriRuns));
598
- if (leftOut.length > 0) {
599
- event.systemPromptOptions.skills = offered.filter((skill) => !leftOut.includes(skill));
600
- if (!leftOutSaid && ctx.hasUI) {
601
- leftOutSaid = true;
602
- const names = leftOut.map((skill) => skill.name);
603
- ctx.ui.notify(`turri left out ${names.length} of pi's skills it has already - ${names.slice(0, 6).join(", ")}${names.length > 6 ? ", ..." : ""}: ` +
604
- "the ***plain reference is in its prompt, and it runs its own skills with cultivate.", "info");
605
- }
606
- }
607
- if (isSentinel) {
608
- const prompt = [event.systemPrompt, sentinelPrompt(cwd, { extraTools: hostSentinelTools.map((tool) => tool.name), ...(host.sentinel?.surface !== undefined ? { surface: host.sentinel.surface } : {}) }), projectConfigBlock(cwd), rulesBlock()].join("\n\n");
609
- return { systemPrompt: host.systemPrompt !== undefined ? host.systemPrompt(prompt) : prompt };
610
- }
611
- return {
612
- systemPrompt: conversationSystemPrompt(event.systemPrompt, host, [
613
- TOOLS_NOT_CLI,
614
- NEW_PROJECT,
615
- pulseEndsBlock(session.sentinelOn()),
616
- // Conformance tests - what they are, whether they are on here, and how they are turned on: every turn, read afresh.
617
- conformanceBlock(conformanceTestsOnIn(cwd)),
618
- projectConfigBlock(cwd),
619
- machineBlock(cwd, machine.now()),
620
- rulesBlock(),
621
- ]),
622
- };
623
- });
624
- // The conversation's agent does not run turri again through its shell, unless the person
625
- // asked for the command line in the message it is answering.
626
- let lastUserMessage = "";
627
- /** While a skill runs in this chat: what passes the person's message to its agent. */
628
- let skillMessage;
629
- pi.on("input", (event) => {
630
- if (event.source !== "extension")
631
- lastUserMessage = event.text;
632
- // A skill running in this chat holds its agent for the whole run: what the person types meanwhile is for the
633
- // skill's agent. It stays queued here too, shown waiting, until that agent reads it - or, the run over first, this one.
634
- if (event.source === "interactive" && skillMessage !== undefined && !event.text.startsWith("/"))
635
- skillMessage(event.text);
636
- return { action: "continue" };
637
- });
638
- pi.on("tool_call", (event) => {
639
- // The sentinel reads, and puts what it finds to the person: whatever else it calls is refused.
640
- if (isSentinel && !sentinelAllowed.has(event.toolName)) {
641
- return { block: true, reason: `${event.toolName} is not one of the sentinel's tools: it fixes the project's testing scripts and their config, and nothing else. Put what needs doing to the person with notify_person.` };
642
- }
643
- const command = event.input.command;
644
- // turri changes nothing of the machine's - no install, no system setting - asked or not, through any tool that runs a
645
- // command: its own bash, and a host's - a terminal in its window. The person does that.
646
- if (typeof command === "string") {
647
- const changes = machineChange(command);
648
- if (changes !== undefined)
649
- return { block: true, reason: machineChangeReason(changes) };
650
- // The sentinel's write and edit reach its tooling alone: a host's command does not write ***plain for it.
651
- const plain = isSentinel ? writesPlain(command) : undefined;
652
- if (plain !== undefined)
653
- return { block: true, reason: `${plain} is ***plain: the sentinel never changes it - put what it needs to the person with notify_person.` };
654
- // Nor does a host's terminal start the code in plain_modules for it: what it tests is what is launched.
655
- const built = isSentinel && event.toolName !== "bash" ? runsBuiltCode(command) : undefined;
656
- if (built !== undefined) {
657
- return {
658
- block: true,
659
- reason: `${built} is in plain_modules - the code a pulse may be writing, which nobody launched: the sentinel never runs it, nor starts a server of its own. Test what is launched, from where its brief says; a server that should run and does not is your finding.`,
660
- };
661
- }
662
- }
663
- if (event.toolName === "bash" && typeof command === "string") {
664
- const what = selfInvocation(command);
665
- if (what !== undefined && !askedForCommandLine(lastUserMessage))
666
- return { block: true, reason: refusal(what, surfaceOf(jobs)) };
667
- }
668
- markConversationWrite(event.toolCallId, event.toolName, event.input);
669
- return undefined;
670
- });
671
- // What the conversation writes in the project while a pulse's agent runs a command is its own: the audit after that
672
- // command leaves it, rather than putting it back as the agent's (conversation-writes.ts).
673
- const conversationWrites = new Map();
674
- const markConversationWrite = (id, tool, input) => {
675
- const path = typeof input.path === "string" ? input.path : undefined;
676
- if ((tool === "edit" || tool === "write") && path !== undefined)
677
- conversationWrites.set(id, conversationWriting([resolve(cwd, path)]));
678
- else if (tool === "bash" || tool === "powershell")
679
- conversationWrites.set(id, conversationCommand());
680
- };
681
- pi.on("tool_result", (event) => {
682
- conversationWrites.get(event.toolCallId)?.();
683
- conversationWrites.delete(event.toolCallId);
684
- return undefined;
685
- });
686
- const settleConversation = () => {
687
- for (const done of conversationWrites.values())
688
- done();
689
- conversationWrites.clear();
690
- conversationSettled();
691
- };
692
- pi.on("agent_end", settleConversation);
693
- // A turn's own model calls happen inside pi's agent loop, outside any tool, so the
694
- // capture is bracketed around the turn itself. Without this, every model call writes
695
- // through the terminal the TUI is drawing on and strands a frame in the scrollback.
696
- let turnCapture;
697
- pi.on("agent_start", () => {
698
- turnCapture?.end();
699
- turnCapture = beginCapture();
700
- });
701
- const endTurnCapture = () => {
702
- turnCapture?.end();
703
- turnCapture = undefined;
704
- };
705
- pi.on("agent_end", endTurnCapture);
706
- pi.on("agent_settled", endTurnCapture);
707
- pi.on("session_start", (_event, ctx) => {
708
- if (!ctx.hasUI)
709
- return;
710
- panel.attach({
711
- setWidget: (key, content, options) => {
712
- try {
713
- ctx.ui.setWidget(key, content, options);
714
- }
715
- catch {
716
- /* rebuilt by pi since: its new extension draws the panel */
717
- }
718
- },
719
- getToolsExpanded: () => {
720
- try {
721
- return ctx.ui.getToolsExpanded();
722
- }
723
- catch {
724
- return false;
725
- }
726
- },
727
- });
728
- });
729
- registerBranding(pi, discoveredSkills);
730
- registerInterviewLog(pi);
731
- registerJobTools(pi, jobs, cwd);
732
- // The skills the person starts themselves - a project's, marked command-only: each has its command, and cultivate starts it only
733
- // once its command is typed, or picked among the options the conversation offers with ask_user.
734
- const gate = createCommandGate();
735
- // A skill picked is started at once, with what the person asked for: they never type its command after picking it.
736
- registerCheckPlain(pi, cwd, dialogs, (answer) => {
737
- const chosen = chosenCommand(answer, discoveredSkills.skills);
738
- if (chosen === undefined)
739
- return undefined;
740
- gate.typed(chosen);
741
- return startPicked(chosen, lastUserMessage);
742
- });
743
- registerRegenerate(pi, cwd, jobs);
744
- registerDrift(pi, cwd, jobs);
745
- registerBind(pi, cwd, jobs, (plainFile) => turnOnConformance(session, plainFile));
746
- registerLaunch(pi, cwd, jobs);
747
- registerSideQuestions(pi, cwd, jobs);
748
- // More chats beside this one, in the terminal: /chat, alt+n, alt+1…9 (chat-commands.ts).
749
- if (session.terminal)
750
- registerChats(pi, session);
751
- const { skills } = discoveredSkills;
752
- if (skills.length === 0)
753
- return;
754
- const catalogue = skills.map(catalogueLine).join("\n");
755
- const pendingNote = leftOutNote(discoveredSkills);
756
- // The command puts what was typed in the chat, as the person's message, for the model to run it with what follows as
757
- // its context.
758
- for (const skill of skills.filter((s) => s.commandOnly)) {
759
- pi.registerCommand(skill.name, {
760
- description: `Start ${skill.name}${skill.steps.length > 1 ? ` - ${skill.steps.map((step) => step.name).join(" → ")}` : ""}: /${skill.name} [what you want]`,
761
- handler: async (args) => {
762
- gate.typed(skill.name);
763
- pi.sendUserMessage(`/${skill.name}${args.trim() !== "" ? ` ${args.trim()}` : ""}`, { deliverAs: "followUp" });
764
- },
765
- });
766
- }
767
- // A skill that runs in the background: started, and the turn goes on; its end comes back to this chat once it is idle.
768
- const skillRunEnds = skillRunDelivery(pi, link, contextNow);
769
- pi.on("session_shutdown", (event) => {
770
- if (event.reason !== "quit")
771
- return;
772
- for (const waiting of backgroundSkillQueue.values())
773
- for (const run of waiting.splice(0))
774
- run.drop();
775
- for (const controller of backgroundSkillRuns.values())
776
- controller.abort();
777
- });
778
- const startInBackground = (skill, params, plainFile, ctx) => {
779
- const key = `${cwd}\0${skill.name}`;
780
- const kind = scriptKindOfSkill(skill.name);
781
- const shown = plainFile !== undefined ? relative(cwd, plainFile) || basename(plainFile) : undefined;
782
- if (backgroundSkillRuns.has(key)) {
783
- const waiting = backgroundSkillQueue.get(key) ?? [];
784
- const runningFor = backgroundSkillFor.get(key);
785
- // Another module's run waits its turn - its testing script counted as being written from now, so the modules that
786
- // need it wait for it rather than start with another's. The same module's, or one for none, is the run under way.
787
- if (plainFile === undefined || runningFor === undefined || runningFor === plainFile || waiting.some((run) => run.plainFile === plainFile)) {
788
- return { text: `${skill.name} is running in the background already; what it does comes back to this chat when it ends. Nothing new was started.`, details: { background: true, started: false } };
789
- }
790
- const configModule = configModuleFor(plainFile);
791
- const held = kind !== undefined ? writingScript({ project: projectDirOf(plainFile), kind, ...(configModule !== undefined ? { configModule } : {}) }) : () => { };
792
- waiting.push({
793
- plainFile,
794
- // Started before the hold is let go: the module is never seen with no script being written in between.
795
- start: () => {
796
- try {
797
- startInBackground(skill, params, plainFile, ctx);
798
- }
799
- catch (error) {
800
- const why = `did not start: ${error instanceof Error ? error.message : String(error)}`;
801
- skillRunEnds.put({ skill: skill.name, ok: false, line: `${skill.name} ${why}.`, task: failedTask(skill.name, why, undefined, kind), ...runDetails(kind, shown) });
802
- }
803
- finally {
804
- held();
805
- }
806
- },
807
- drop: held,
808
- });
809
- backgroundSkillQueue.set(key, waiting);
810
- return {
811
- text: `${skill.name} is running in the background for ${relative(cwd, runningFor) || basename(runningFor)}; the run for ${shown} starts once it ends, and what it does comes back to this chat then.${kind !== undefined ? ` Until it has written its ${kind === "unit" ? "unit testing script" : "conformance testing script"}, the modules that need it wait for it.` : ""} Do not start it again.`,
812
- details: { background: true, ...runDetails(kind, shown) },
813
- };
814
- }
815
- const model = skill.model === "coding" ? jobModel(ctx, undefined, plainFile) : conversationModel(ctx);
816
- const configModule = plainFile !== undefined ? configModuleFor(plainFile) : undefined;
817
- // While it writes a testing script, the modules that need it wait for it rather than fail for want of it.
818
- const written = kind !== undefined ? writingScript({ project: plainFile !== undefined ? projectDirOf(plainFile) : cwd, kind, ...(configModule !== undefined ? { configModule } : {}) }) : () => { };
819
- const controller = new AbortController();
820
- backgroundSkillRuns.set(key, controller);
821
- backgroundSkillFor.set(key, plainFile);
822
- const context = [
823
- conversationContext(ctx, params.context),
824
- shown !== undefined ? `It is for ${shown}${configModule !== undefined ? `, built with ${moduleConfigFile(configModule)} over ${CONFIG_FILE}` : ""}.` : undefined,
825
- BACKGROUND_NOTE,
826
- ]
827
- .filter((part) => part !== undefined && part.trim() !== "")
828
- .join("\n\n");
829
- const filesBefore = projectFiles(cwd);
830
- const writes = ["write", "edit", "bash"].some((tool) => skill.allowedTools.includes(tool));
831
- const quiet = { step: () => { }, artifact: () => { }, gate: () => { }, judge: () => { }, outcome: () => { } };
832
- const about = runDetails(kind, shown);
833
- const end = (ended) => skillRunEnds.put(ended.ok
834
- ? { skill: skill.name, ok: true, line: doneLine(skill.name, ended.changed, kind), ...about }
835
- : { skill: skill.name, ok: false, line: `${skill.name} ${ended.why}.`, task: failedTask(skill.name, ended.why, ended.output, kind), ...about });
836
- void captureConsole(() => withConfigModule(configModule, () => runSkill({
837
- skillDir: skill.dir,
838
- signal: controller.signal,
839
- cwd,
840
- runDir: skillRunDir(cwd, skill.name),
841
- report: quiet,
842
- context,
843
- ...(model !== undefined ? { model } : {}),
844
- // Nobody is asked: a gate that cannot be satisfied stands.
845
- escalate: async () => false,
846
- })))
847
- .then(({ result }) => {
848
- // Its own: the chat went on meanwhile, and what it wrote is not the run's.
849
- const changed = ownChanges(changedFiles(filesBefore, projectFiles(cwd, filesBefore.keys())), kind);
850
- if (!result.ok)
851
- end({ ok: false, why: "stopped at a review gate, with no approved artifact", output: result.output });
852
- else if (writes && changed.length === 0)
853
- end({ ok: false, why: "ended having changed no file in the project", output: result.output });
854
- else
855
- end({ ok: true, changed });
856
- })
857
- .catch((error) => {
858
- // Stopped as turri quits: nobody is left to tell.
859
- if (error instanceof JobStoppedError)
860
- return;
861
- end({ ok: false, why: `failed: ${error instanceof Error ? error.message : String(error)}` });
862
- })
863
- .finally(() => {
864
- backgroundSkillRuns.delete(key);
865
- backgroundSkillFor.delete(key);
866
- // The next module's run, waiting its turn, starts before this one's hold is let go.
867
- backgroundSkillQueue.get(key)?.shift()?.start();
868
- written();
869
- });
870
- return {
871
- text: startedText(skill.name, { ...(model !== undefined ? { model } : {}), ...(shown !== undefined ? { plainFile: shown } : {}), ...(kind !== undefined ? { kind } : {}) }),
872
- details: { background: true, ...about },
873
- };
874
- };
875
- pi.registerTool({
876
- name: "cultivate",
877
- label: "Cultivate",
878
- description: "Execute one of this project's gated skills end to end. The skill's steps, review gates and " +
879
- "judges are enforced by the harness, so a gated skill's result has already passed review when it comes back; a skill " +
880
- "without gates is not reviewed. Every result says which files the run changed in the project.\n\n" +
881
- `Available skills:\n${catalogue}${pendingNote}`,
882
- promptSnippet: "cultivate: run a gated skill - its steps and review gates enforced by turri",
883
- promptGuidelines: [
884
- "When a request matches a skill listed in cultivate's description, call cultivate instead of doing the work yourself. Doing it by hand skips the review gates.",
885
- "A skill marked as started only by the person runs only from its command: a message that is its command - /<name> what they want - is the person starting it, and so is an option starting with it that they picked in your ask_user. Call cultivate for it at once, with what they said as context. Never call cultivate for one otherwise.",
886
- // pi lists .agents/skills among its own skills too: read and followed by hand, a skill's gates would be skipped.
887
- "A skill cultivate lists may also be among your own skills, from the project's .agents/skills: run it with cultivate all the same, never by reading its SKILL.md and following it.",
888
- "cultivate returns the reviewed artifact and a trace of every gate decision. Report the artifact to the user; do not rewrite it.",
889
- "A skill that runs in the background returns at once: go on with the turn, without waiting or telling the person to wait. Its end comes back to this chat by itself - a line when it did its work, a message to act on when it did not.",
890
- "If cultivate fails, say so and stop. Never carry out the skill's work yourself in the conversation - the gates and the judges are the point of running it, and an unreviewed hand-run silently drops them.",
891
- "Always pass `context` to cultivate, summarising what the user has already told you.",
892
- ],
893
- parameters: Type.Object({
894
- skill: Type.String({
895
- description: `Skill name. One of: ${skills.map((s) => s.name).join(", ")}`,
896
- }),
897
- context: Type.Optional(Type.String({
898
- description: "Everything the user has already told you that this skill would otherwise ask for - what " +
899
- "they are building, for whom, any decisions already made, names they have used. The skill " +
900
- "runs in its own session and cannot see this conversation, so whatever you leave out it " +
901
- "will ask again.",
902
- })),
903
- resume: Type.Optional(Type.Boolean({
904
- description: "Continue the run of this skill that was interrupted here - by a restart, a crash - from the step " +
905
- "it was in, with its session as it was. Use when the user wants to carry on where they left off.",
906
- })),
907
- fresh: Type.Optional(Type.Boolean({
908
- description: "Start a new run even though an interrupted one exists here, discarding it.",
909
- })),
910
- plainFile: Type.Optional(Type.String({
911
- description: "The module the skill's work is for - its .plain file, e.g. backend.plain: a testing script is written for that module, named in its config, " +
912
- "on its coding model. Omitted: the project's.",
913
- })),
914
- }),
915
- async execute(_id, params, signal, onUpdate, ctx) {
916
- const skill = skills.find((s) => s.name === params.skill);
917
- if (!skill) {
918
- return {
919
- content: [{ type: "text", text: `Unknown skill '${params.skill}'. Available: ${skills.map((s) => s.name).join(", ")}` }],
920
- details: {},
921
- };
922
- }
923
- if (!gate.mayStart(skill))
924
- return { content: [{ type: "text", text: startedByCommandOnly(skill.name) }], details: { notStarted: true } };
925
- // The conformance testing script is for conformance tests: none is written while they are off.
926
- if (scriptKindOfSkill(skill.name) === "conformance" && !conformanceTestsOnIn(cwd)) {
927
- return {
928
- content: [{ type: "text", text: `${skill.name} writes the conformance testing script, for conformance tests. ${CONFORMANCE_OFF_REFUSAL}` }],
929
- details: { notStarted: true },
930
- };
931
- }
932
- const plainFile = params.plainFile !== undefined && params.plainFile.trim() !== "" ? resolve(cwd, params.plainFile.trim()) : undefined;
933
- if (plainFile !== undefined && !existsSync(plainFile)) {
934
- return { content: [{ type: "text", text: `There is no ${params.plainFile} here. Nothing was started.` }], details: { notStarted: true } };
935
- }
936
- // A skill that runs in the background, in a chat - where its end can come back to: started, and the turn goes on.
937
- if (skill.background && !shouldWait(ctx.mode, undefined)) {
938
- gate.started(skill.name);
939
- const started = startInBackground(skill, params, plainFile, ctx);
940
- return { content: [{ type: "text", text: started.text }], details: started.details };
941
- }
942
- // A new run clears the run folder. An interrupted one is not thrown away by accident:
943
- // whether to pick it up or start over is the user's call.
944
- const runDir = skillRunDir(cwd, skill.name);
945
- const interrupted = interruptedRun(runDir, skill.name);
946
- if (interrupted !== undefined && params.resume !== true && params.fresh !== true) {
947
- return {
948
- content: [
949
- {
950
- type: "text",
951
- text: `There is an interrupted run of ${skill.name} here${interrupted.step ? `, stopped in its ${interrupted.step} step` : ""} ` +
952
- `(last active ${interrupted.updatedAt}). Ask the user whether to continue it or start over, then call ` +
953
- "cultivate again with resume: true or fresh: true. Nothing has been started.",
954
- },
955
- ],
956
- details: { interrupted },
957
- };
958
- }
959
- // Its command is used up: started again later, it is typed again.
960
- gate.started(skill.name);
961
- // What the person said to it while it ran, its agent having read it: told to this chat's agent with the result.
962
- const heard = [];
963
- const messages = {
964
- open: (tell) => {
965
- skillMessage = tell;
966
- },
967
- read: (text) => {
968
- heard.push(text);
969
- const session = link.session();
970
- // Read by the skill's agent, not this one: out of this chat's queue, and into its chat where it was read.
971
- void (session !== undefined ? unqueue(session, text) : Promise.resolve(false)).then((taken) => {
972
- if (taken)
973
- pi.appendEntry(SKILL_MESSAGE_ENTRY, { text, skill: skill.name });
974
- });
975
- },
976
- };
977
- const trace = [`skill: ${skill.name}`, ...describeGates(skill).map((l) => ` ${l}`)];
978
- // While it runs, what its agent is doing leads: pi shows a running tool's first lines, and the trace's first
979
- // lines are the gates, which say nothing about now. The result keeps the trace alone.
980
- const live = { started: Date.now(), step: "", stepStarted: Date.now(), recent: [], saying: "" };
981
- const show = () => {
982
- const elapsed = (since) => {
983
- const s = Math.round((Date.now() - since) / 1000);
984
- return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${s % 60}s`;
985
- };
986
- const words = live.saying.replace(/\s+/g, " ").trim();
987
- const view = [
988
- `${skill.name}${live.step !== "" ? ` · ${live.step}, ${elapsed(live.stepStarted)}` : ""} · ${elapsed(live.started)} in all`,
989
- ...live.recent.map((line) => ` ${line}`),
990
- ...(words !== "" ? [` says: ${words.length > 160 ? `…${words.slice(-159)}` : words}`] : []),
991
- "",
992
- ];
993
- onUpdate?.({ content: [{ type: "text", text: [...view, ...trace].join("\n") }], details: {} });
994
- };
995
- const push = (line) => {
996
- trace.push(line);
997
- show();
998
- };
999
- const ticker = setInterval(show, 5000);
1000
- ticker.unref?.();
1001
- // Above the input, while it runs: every phase by name, the one it is in, and how far through - and under it, what that phase does.
1002
- const phases = skill.steps.map((step) => step.name);
1003
- const progress = { current: -1, attempt: 1 };
1004
- if (ctx.hasUI) {
1005
- ctx.ui.setWidget("turri-skill", (tui, theme) => {
1006
- // The spinner on the phase it is in moves.
1007
- const redraw = setInterval(() => tui.requestRender(), 1000);
1008
- redraw.unref?.();
1009
- const style = {
1010
- heading: (text) => theme.bold(theme.fg("accent", text)),
1011
- done: (text) => theme.fg("success", text),
1012
- now: (text) => theme.bold(theme.fg("accent", text)),
1013
- muted: (text) => theme.fg("muted", text),
1014
- };
1015
- return {
1016
- render: (width) => {
1017
- const about = skill.steps[progress.current]?.about;
1018
- const now = { skill: skill.name, phases, current: progress.current, attempt: progress.attempt, frame: spinner(Date.now()), ...(about !== undefined ? { about } : {}) };
1019
- const under = skillAboutLine(now, width, style);
1020
- return [skillProgressLine(now, width, style), ...(under !== undefined ? [under] : [])];
1021
- },
1022
- invalidate: () => { },
1023
- dispose: () => clearInterval(redraw),
1024
- };
1025
- });
1026
- }
1027
- const report = {
1028
- step: (name, attempt) => {
1029
- progress.current = phases.indexOf(name);
1030
- progress.attempt = attempt;
1031
- live.step = skillStatus(skill, name, attempt).slice(skill.name.length + 2);
1032
- live.stepStarted = Date.now();
1033
- push(`step ${name} (attempt ${attempt})`);
1034
- },
1035
- activity: (line) => {
1036
- live.recent = [...live.recent, line].slice(-6);
1037
- show();
1038
- },
1039
- said: (delta, fresh) => {
1040
- live.saying = fresh ? "" : live.saying + delta;
1041
- show();
1042
- },
1043
- artifact: (path, body) => push(` ${path}: ${body.split("\n")[0]}${body.includes("\n") ? " ..." : ""}`),
1044
- gate: (name, judges) => push(judges === 0 ? `gate ${name}: no artifact` : `gate ${name}: ${judges} judges`),
1045
- livePass: (step, scope, findings) => push(` review ${step}: ${scope} - ${findings === 0 ? "clean" : `${findings} to fix`}`),
1046
- liveReview: (name, passes, findings) => push(findings === 0
1047
- ? `gate ${name}: reviewer read along in ${passes} passes, nothing outstanding`
1048
- : `gate ${name}: ${findings} unresolved from the reviewer`),
1049
- judge: (index, model, verdict, violations) => push(` judge ${index + 1} (${model}): ${verdict}${violations ? ` (${violations} violations)` : ""}`),
1050
- outcome: (name, decision, critique) => {
1051
- push(` ${decision} <- gate ${name}`);
1052
- if (critique)
1053
- for (const line of critique.split("\n"))
1054
- push(` ${line}`);
1055
- },
1056
- };
1057
- // What the run changes in the project's ***plain - its specs, resources, scripts - is said with its result: a skill
1058
- // that writes nothing is not taken for one that did its work. Only those: a launch or a running app changes other
1059
- // files while it runs, and they are not its doing.
1060
- const filesBefore = projectFiles(cwd);
1061
- // A side question asked while it runs is told what it has done so far.
1062
- const ran_ = skillRunStarted({ skill: skill.name, dir: skill.dir, step: () => live.step, trace: () => [...trace], runDir });
1063
- // A testing script being written - here to its end, in print mode - holds the modules it is for, as in the background:
1064
- // a pulse started meanwhile, by a regenerate called beside it, would run against the script as it was.
1065
- const kind = scriptKindOfSkill(skill.name);
1066
- const configModule = plainFile !== undefined ? configModuleFor(plainFile) : undefined;
1067
- const written = kind !== undefined ? writingScript({ project: plainFile !== undefined ? projectDirOf(plainFile) : cwd, kind, ...(configModule !== undefined ? { configModule } : {}) }) : () => { };
1068
- const ended = () => {
1069
- written();
1070
- ran_();
1071
- };
1072
- const ran = await captureConsole(() => runSkill({
1073
- skillDir: skill.dir,
1074
- // The chat's turn stopped - ctrl+c, esc - stops the run with it.
1075
- signal,
1076
- cwd,
1077
- runDir,
1078
- resume: params.resume === true && interrupted !== undefined,
1079
- report,
1080
- context: conversationContext(ctx, params.context),
1081
- messages,
1082
- askUser: askUserVia(ctx, (question, answer, said) => {
1083
- // What the skill's agent said before asking stays in the run's record, not only in the dialog.
1084
- for (const line of (said ?? "").trim().split("\n").filter((line) => line.trim() !== ""))
1085
- push(` ${line}`);
1086
- push(` Q: ${question}`);
1087
- push(` A: ${answer}`);
1088
- recordExchange(pi, { skill: skill.name, question, answer, ...(said !== undefined && said.trim() !== "" ? { said: said.trim() } : {}) });
1089
- }, (question) => askOnTheSide(pi, ctx, cwd, jobs, question), dialogs),
1090
- model: skill.model === "coding" ? jobModel(ctx, undefined, plainFile) : conversationModel(ctx),
1091
- // Renders queued by a step land in the same registry as everything else, so
1092
- // pulses sees them without knowing a skill started them.
1093
- // Asked per job as it is queued, so a model chosen mid-interview applies from then on.
1094
- renderQueue: workLoopFor(jobs, cwd, ctx),
1095
- // The person answers the skill's agent while it runs, so it can take "render these with ..." too.
1096
- // parse too: a skill parses what it wrote with the same check the conversation has.
1097
- sharedTools: [checkPlainTool(cwd), ...createWebTools()],
1098
- // The conversation's own regenerate, drift, halt and conform, on its loop: a skill waits for nothing, and regenerates on the model chosen.
1099
- loopTools: [
1100
- regenerateTool({ cwd, jobs, loop: () => workLoopFor(jobs, cwd, ctx), model: (_skill, plainFile, named) => jobModel(ctx, named, plainFile), wait: () => false }),
1101
- driftTool({ cwd, jobs, loop: () => workLoopFor(jobs, cwd, ctx) }),
1102
- haltTool({ jobs, workLoop: () => workLoops.get(jobs)?.loop, ...(sessionLaunches.get(jobs) !== undefined ? { launches: sessionLaunches.get(jobs).track } : {}) }),
1103
- conformTool({ cwd, jobs, loop: () => workLoopFor(jobs, cwd, ctx), model: (_skill, plainFile, named) => jobModel(ctx, named, plainFile), wait: () => false }),
1104
- ],
1105
- // The escalation becomes a real dialog - the host's own, when it has them. Without one there is nobody to ask,
1106
- // so the gate stands.
1107
- escalate: async ({ question, critique }) => {
1108
- if (dialogs !== undefined) {
1109
- const through = "Let it through";
1110
- // Declined, as any question in the host's dialogs can be: the gate stands.
1111
- const asked = asking(signal);
1112
- try {
1113
- const answer = await hostDialogs(dialogs, asked.declining).select(`Review gate: ${skill.name} - ${question}`, [through, "Keep the gate"], critique);
1114
- return !asked.declining.declined && answer === through;
1115
- }
1116
- finally {
1117
- asked.done();
1118
- }
1119
- }
1120
- if (!ctx.hasUI) {
1121
- push(" no UI available for human review - gate stands");
1122
- return false;
1123
- }
1124
- return ctx.ui.confirm(`Review gate: ${skill.name}`, `${critique}\n\n${question}`);
1125
- },
1126
- }))
1127
- .catch((error) => {
1128
- if (!(error instanceof JobStoppedError))
1129
- throw error;
1130
- return undefined;
1131
- })
1132
- .finally(() => {
1133
- ended();
1134
- clearInterval(ticker);
1135
- if (ctx.hasUI)
1136
- ctx.ui.setWidget("turri-skill", undefined);
1137
- });
1138
- if (ran === undefined) {
1139
- const text = [`${skill.name}: stopped by the person, in its ${live.step || "first"} step. It can be continued with resume: true.`, "", "<trace>", ...trace, "</trace>"].join("\n");
1140
- return { content: [{ type: "text", text }], details: { stopped: true } };
1141
- }
1142
- const { result, output: captured } = ran;
1143
- const noise = describeCaptured(captured);
1144
- if (noise !== null)
1145
- push(noise);
1146
- const changes = changedFiles(filesBefore, projectFiles(cwd, filesBefore.keys()));
1147
- // A skill that only reads and reports - an analysis - changes nothing, and its result is its verdict.
1148
- const writes = ["write", "edit", "bash"].some((tool) => skill.allowedTools.includes(tool));
1149
- const changed = changes.length > 0
1150
- ? `It changed ${changes.length} file${changes.length === 1 ? "" : "s"} in the project: ${changes.join(", ")}.`
1151
- : writes
1152
- ? "It changed no file in the project - whatever it said it wrote is not there. Say so to the user; do not report the work as done."
1153
- : "It only reads: what it found is the artifact below.";
1154
- // A skill that edits the specs with the file tools builds nothing: the change is the conversation's to render.
1155
- // A test plain file is its module's: the module is what regenerate is called for, its scenarios' tests brought up with it.
1156
- const specsChanged = changes.filter((path) => path.endsWith(".plain"));
1157
- const named = specsChanged.map((path) => {
1158
- const owner = moduleOfTestPlainFile(resolve(cwd, path));
1159
- return owner === undefined ? path : `${path} (a test plain file of ${owner.plainFile !== undefined ? relative(cwd, owner.plainFile) : owner.module})`;
1160
- });
1161
- const unrendered = specsChanged.length > 0
1162
- ? `${named.join(", ")} changed, and nothing is regenerated from that yet: call regenerate for ${named.length === 1 ? "its module" : "their modules"}, and the code and its conformance tests are brought up to the spec.`
1163
- : "";
1164
- const gated = skill.steps.some((step) => step.gate !== undefined);
1165
- const said = heard.length > 0 ? ["", `While it ran, the person said to it - its agent read and acted on each:`, ...heard.map((text) => `- ${text.replace(/\s+/g, " ").trim()}`)] : [];
1166
- const text = result.ok
1167
- ? [
1168
- gated ? `${skill.name}: passed all gates.` : `${skill.name}: finished. It has no review gates, so nothing checked its work: read what it changed before you report it.`,
1169
- changed,
1170
- ...(unrendered !== "" ? [unrendered] : []),
1171
- ...said,
1172
- "",
1173
- "<artifact>",
1174
- result.output,
1175
- "</artifact>",
1176
- "",
1177
- "<trace>",
1178
- ...trace,
1179
- "</trace>",
1180
- ].join("\n")
1181
- : [`${skill.name}: stopped at a gate. No approved artifact.`, changed, ...said, "", "<trace>", ...trace, "</trace>"].join("\n");
1182
- return { content: [{ type: "text", text }], details: { ok: result.ok, artifacts: result.artifacts } };
1183
- },
1184
- });
1185
- }
1186
- function registerRegenerate(pi, cwd, jobs) {
1187
- pi.registerTool(regenerateTool({
1188
- cwd,
1189
- jobs,
1190
- loop: (ctx) => workLoopFor(jobs, cwd, ctx),
1191
- model: (ctx, plainFile, named) => jobModel(ctx, named, plainFile),
1192
- wait: (ctx, asked) => shouldWait(ctx.mode, asked),
1193
- }));
1194
- // /regenerate: the same as the tool, from the person - a module brought up to its spec as it is now, cut into pulses
1195
- // by the planner: one functional spec at a time, a few together or the whole module in one, as it judges.
1196
- pi.registerCommand("regenerate", {
1197
- description: "Regenerate a module from its ***plain as it is now, in pulses the planner cuts - named functional specs though they did not change, or all of it from scratch, its whole chain too when asked: /regenerate [module | file.plain] [module:func-id ...] [from scratch [whole chain]]",
1198
- handler: async (args, ctx) => {
1199
- const command = `/regenerate ${args.trim()}`.trim();
1200
- await echoCommand(pi, command);
1201
- const say = (text, level) => shownAfterCommand(pi, ctx, command, text, level, true);
1202
- const picked = await commandModule(cwd, ctx, args, say, { verb: "regenerate", outcome: "regenerated" });
1203
- if (picked === undefined)
1204
- return;
1205
- const { plainFile } = picked;
1206
- // Functional specs named first, each as module:func-id, as on the command line.
1207
- const { funcIds: again, rest } = funcIdsNamedFirst(picked.rest);
1208
- const words = rest.join(" ").trim();
1209
- // From scratch - started over, its code deleted - asked in the person's words: started at once, as asked.
1210
- const scratch = asksFromScratch(words);
1211
- // The whole chain with it - "from scratch, the whole chain" - every module it requires built again from the bottom.
1212
- const chain = scratch && asksWholeChain(words);
1213
- const module = basename(plainFile).replace(/\.plain$/, "");
1214
- // Nothing but the functional specs and from scratch: the planner cuts the work as it judges, so other words are not dropped unsaid.
1215
- if (words !== "" && !scratch) {
1216
- say(`/regenerate takes functional specs, each as module:func-id, and "from scratch" with "whole chain" - not "${words}". Nothing was started.`, "warning");
1217
- return;
1218
- }
1219
- if (scratch && again.length > 0) {
1220
- say("Name functional specs or ask for it from scratch, not both: from scratch regenerates every one of them.", "warning");
1221
- return;
1222
- }
1223
- const loop = workLoopFor(jobs, cwd, ctx);
1224
- const model = jobModel(ctx, undefined, plainFile);
1225
- const request = { ...(model !== undefined ? { model } : {}) };
1226
- // Said at once, and kept in the chat: what follows takes a while - the planner is an agent - and the person sees it
1227
- // began, not a chat that stays empty until the first pulse starts. The plan is said under it once it is made.
1228
- say(scratch
1229
- ? `Deleting ${module}'s code${chain ? " and its whole chain's" : ""} and then starting regeneration…`
1230
- : again.length > 0
1231
- ? `Planning ${again.join(", ")} again…`
1232
- : `Planning ${module}'s pulses…`, "info");
1233
- await nextFrame();
1234
- // Planned in the background: pi reads what is typed next only once a command returns, and planning takes the
1235
- // planner's time - the chat, and switching to another, stay free meanwhile. The plan is said once it is made.
1236
- const target = plainFile;
1237
- void (async () => {
1238
- try {
1239
- // Refused when its config cannot be told, or would build it with no testing script.
1240
- const statuses = await whenBuildable(target, () => scratch
1241
- ? loop.fromScratch(target, { ...request, chain })
1242
- : again.length > 0
1243
- ? loop.regenerateAgain(target, again, request)
1244
- : loop.bringUp(target, request));
1245
- // Nothing to do: say how to build it again anyway.
1246
- const upToDate = statuses.length > 0 && statuses.every(isUpToDate);
1247
- const hint = upToDate
1248
- ? `\nTo regenerate parts of it anyway, name their functional specs - /regenerate ${basename(target)} ${module}:<func-id> - or start over with /regenerate ${basename(target)} from scratch.`
1249
- : "";
1250
- // Pulses started: the agent says so, and that the person need not wait - a plan alone leaves the chat silent.
1251
- shownAfterCommand(pi, ctx, command, describeModules(statuses) + hint, "info", true, upToDate ? undefined : COMMAND_STARTED_REACTION);
1252
- }
1253
- catch (error) {
1254
- say(error instanceof Error ? error.message : String(error), "error");
1255
- }
1256
- })().catch(() => {
1257
- // The chat let go while it planned - closed, or rebuilt: there is nobody to say it to.
1258
- });
1259
- },
1260
- });
1261
- }
1262
- /**
1263
- * The module a /regenerate or /conform is for, and the words after it: the one its first words name, else the one
1264
- * `module:` names, else the folder's top modules to pick from - checked to parse. Undefined, said why, when there is
1265
- * none to take, or the person picked none.
1266
- */
1267
- async function commandModule(cwd, ctx, args, say, words) {
1268
- const all = args.trim().split(/\s+/).filter((word) => word !== "");
1269
- const [first = ""] = all;
1270
- const { named, rest } = moduleNamedFirst(cwd, all);
1271
- if (named === undefined && first.endsWith(".plain")) {
1272
- say(`There is no ${first} here.`, "error");
1273
- return undefined;
1274
- }
1275
- let plainFile = named;
1276
- if (plainFile === undefined) {
1277
- const modules = defaultMapFiles(cwd);
1278
- if (modules.length === 0) {
1279
- say(`No .plain file to ${words.verb}: name one - /${words.verb} app.plain - or set module: in config.turri.yaml.`, "warning");
1280
- return undefined;
1281
- }
1282
- if (modules.length === 1 || !ctx.hasUI)
1283
- plainFile = modules[0];
1284
- else {
1285
- const label = (file) => relative(cwd, file) || basename(file);
1286
- const picked = await ctx.ui.select(`${words.verb === "regenerate" ? "Regenerate" : "Conform"} which module?`, modules.map(label));
1287
- plainFile = modules.find((file) => label(file) === picked);
1288
- if (plainFile === undefined)
1289
- return undefined;
1290
- }
1291
- }
1292
- const check = checkPlainFile(plainFile);
1293
- if (!check.ok) {
1294
- say(`${relative(cwd, plainFile) || plainFile} does not parse, so nothing can be ${words.outcome} from it yet:\n${formatCheckResults([check])}`, "error");
1295
- return undefined;
1296
- }
1297
- return { plainFile, rest };
1298
- }
1299
- /** The functional specs a command's words name first, each as module:func-id - a comma after one allowed - and the words after them. */
1300
- export function funcIdsNamedFirst(words) {
1301
- const rest = [...words];
1302
- const funcIds = [];
1303
- while (rest.length > 0 && /^[^\s:]+:[a-z0-9-]+,?$/.test(rest[0]))
1304
- funcIds.push(rest.shift().replace(/,$/, ""));
1305
- return { funcIds, rest };
1306
- }
1307
- /** Whether a /conform's words after its functional specs ask for a pulse a functional spec - "one by one", "separately". */
1308
- export function asksOneByOne(words) {
1309
- return /\b(one[\s-]+(by|at)[\s-]+(one|a[\s-]+time)|separately|each[\s-]+(on[\s-]+its[\s-]+own|alone))\b/i.test(words);
1310
- }
1311
- /**
1312
- * What a slash command showed the person: kept in the chat, where they read it, and put in the conversation as well -
1313
- * unseen there - so that when they speak of it next ("fix it"), the agent knows what they saw. A command runs outside
1314
- * the agent's turns, and a notification is gone in seconds and reaches no model. Given `react`, the agent is started on
1315
- * it too - at once when it is idle, else once its turn ends - told what to do with it.
1316
- */
1317
- export function shownAfterCommand(pi, ctx, command, text, level,
1318
- /** The command is in the chat already, above it (echoCommand): the text alone. */
1319
- echoed = false, react) {
1320
- try {
1321
- pi.appendEntry(COMMAND_OUTCOME, { command, text, level, ...(echoed ? { echoed } : {}) });
1322
- }
1323
- catch {
1324
- // Shown for a moment all the same.
1325
- if (ctx.hasUI)
1326
- ctx.ui.notify(text, level);
1327
- }
1328
- const content = `The person ran ${command}, and was shown:\n${text}${react !== undefined ? `\n\n${react}` : ""}`;
1329
- if (react === undefined)
1330
- void pi.sendMessage({ customType: COMMAND_OUTCOME, content, display: false });
1331
- else
1332
- void pi.sendMessage({ customType: COMMAND_OUTCOME, content, display: false }, { triggerTurn: true, deliverAs: "followUp" });
1333
- }
1334
- /**
1335
- * What a slash command found for the agent alone - guidance the person need not see: put in the conversation unseen,
1336
- * and the agent started on it - at once when it is idle, else once its turn ends - told what to do with it.
1337
- */
1338
- export function toldAfterCommand(pi, command, text, react) {
1339
- const content = `The person ran ${command}. Not shown to them:\n${text}\n\n${react}`;
1340
- void pi.sendMessage({ customType: COMMAND_OUTCOME, content, display: false }, { triggerTurn: true, deliverAs: "followUp" });
1341
- }
1342
- /**
1343
- * What the agent does once /regenerate or /conform has started pulses: a command's output alone leaves the chat silent,
1344
- * and the person wondering whether to wait. It says what runs, and that they need not - and starts nothing itself.
1345
- */
1346
- export const COMMAND_STARTED_REACTION = "My pulses are running from the person's command, in the background. Tell the person, in a line or two, what " +
1347
- "runs and what is planned - and that the two of us can go on with the ***plain, or anything else, meanwhile: they need " +
1348
- "not wait for it. Start nothing for it: no regenerate, no check, no launch - its end is told when it comes.";
1349
- /**
1350
- * What the agent does when /conform found a step of adding tests still to take: takes it at once, asking nothing - the
1351
- * /conform was the person's yes - and says what it writes as the way there, never as a failure: the person saw none.
1352
- */
1353
- export const CONFORM_STEPS_REACTION = "That is what conform needs before it can start - the steps of adding tests still to take - not an error: nothing " +
1354
- "failed, and the person saw none of it. Their /conform is their yes to conformance tests here, so take the steps now, " +
1355
- "in that order and only what is missing, asking nothing: the test reqs first; then the conformance testing script, " +
1356
- "started with its skill before anything else - it runs in the background, so the scenarios are written while it does; " +
1357
- "then the scenarios of the functional specs they named, or, naming none, of each functional spec that needs them by " +
1358
- "the rules on test plain files. Then call regenerate for the module: the work loop writes and runs their tests once the " +
1359
- "code is built. Tell the person in a line or two, as the way to their conformance tests and not as a refusal, what you " +
1360
- "are writing, and for each functional spec why it needs scenarios - or, when none does, that and why.";
1361
- /**
1362
- * What the agent does when /conform started nothing for a reason that is not a step of adding tests - a functional spec
1363
- * named that is not there, words it does not take: answers it at once - why, and what would let it start - rather than
1364
- * leave the person with a refusal and a silent chat.
1365
- */
1366
- export const CONFORM_REFUSED_REACTION = "Nothing was started from the person's /conform, for the reason shown. Tell them in a line or two why, and what would " +
1367
- "let it start - a functional spec they named that is not there, ***plain that does not parse or would have to change its " +
1368
- "meaning to be tested - and offer to do what is yours to do; start nothing.";
1369
- export const COMMAND_OUTCOME = "turri_command_outcome";
1370
- /** Longer than a frame of the TUI's (16ms): an entry appended before it is drawn by its end. */
1371
- const ONE_FRAME_MS = 20;
1372
- /**
1373
- * What the person typed, put in the chat the moment they send it - before the command does anything - and drawn before
1374
- * it goes on: a command's work can hold the event loop (a long requires chain parsed), and the chat stays as it was
1375
- * until it lets go. What the command says comes under it.
1376
- */
1377
- export async function echoCommand(pi, command) {
1378
- try {
1379
- pi.appendEntry(COMMAND_OUTCOME, { command });
1380
- }
1381
- catch {
1382
- return;
1383
- }
1384
- await nextFrame();
1385
- }
1386
- /** Until the TUI has drawn what was just put in the chat. */
1387
- export const nextFrame = () => new Promise((resolve) => setTimeout(resolve, ONE_FRAME_MS));
1388
- /**
1389
- * The module a /regenerate's first words name, and the words after it - all of them when none is named. A name typed
1390
- * with spaces for its underscores - "d365_function executor" - is the module d365_function_executor: the most words
1391
- * that name one win.
1392
- */
1393
- export function moduleNamedFirst(cwd, words) {
1394
- for (let count = words.length; count >= 1; count -= 1) {
1395
- const named = plainFileNamed(cwd, words.slice(0, count).join("_"));
1396
- if (named !== undefined)
1397
- return { named, rest: words.slice(count) };
1398
- }
1399
- return { rest: words };
1400
- }
1401
- /** The .plain file a /regenerate argument names - a path, or a module's name in the folder - if it names one. */
1402
- function plainFileNamed(cwd, word) {
1403
- for (const candidate of [word, `${word}.plain`]) {
1404
- const path = resolve(cwd, candidate);
1405
- // A test plain file names no module: it is refused where the module is taken.
1406
- if (path.endsWith(".plain") && existsSync(path) && testPlainFileRefusal(path) === undefined)
1407
- return path;
1408
- }
1409
- return undefined;
1410
- }
1411
- /** What is left to regenerate: the drift between a module's code and its spec - planning nothing, starting nothing. */
1412
- function registerDrift(pi, cwd, jobs) {
1413
- pi.registerTool(driftTool({ cwd, jobs, loop: (ctx) => workLoopFor(jobs, cwd, ctx) }));
1414
- }
1415
- function registerBind(pi, cwd, jobs, turnOn) {
1416
- pi.registerTool(conformTool({
1417
- cwd,
1418
- jobs,
1419
- loop: (ctx) => workLoopFor(jobs, cwd, ctx),
1420
- model: (ctx, plainFile, named) => jobModel(ctx, named, plainFile),
1421
- wait: (ctx, asked) => shouldWait(ctx.mode, asked),
1422
- }));
1423
- // /conform: the same as the tool, from the person - a module's conformance tests written and run now, for the
1424
- // functional specs named or every one with scenarios, in one pulse unless asked for one a functional spec. Asking for
1425
- // them is asking for them on: off, they are turned on first. What would start nothing is found before anything is
1426
- // said, and the chat's agent answers it at once.
1427
- pi.registerCommand("conform", {
1428
- description: "Write and run a module's conformance tests now - the functional specs named, or every one with scenarios - in one pulse, or one a functional spec when asked; those written already written again, named, or from scratch - the tests folder at the tip of its chain taken out, started again from the module it requires, or from nothing with whole chain; turned on first when they are off: /conform [module | file.plain] [module:func-id ...] [from scratch [whole chain]] [one by one]",
1429
- handler: async (args, ctx) => {
1430
- const command = `/conform ${args.trim()}`.trim();
1431
- await echoCommand(pi, command);
1432
- /** Nothing started: shown, and the agent told to answer it now. */
1433
- const refuse = (text) => shownAfterCommand(pi, ctx, command, text, "error", true, CONFORM_REFUSED_REACTION);
1434
- const picked = await commandModule(cwd, ctx, args, (text, level) => (level === "info" ? shownAfterCommand(pi, ctx, command, text, level, true) : refuse(text)), {
1435
- verb: "conform",
1436
- outcome: "conformance tested",
1437
- });
1438
- if (picked === undefined)
1439
- return;
1440
- const { plainFile } = picked;
1441
- const { funcIds, rest } = funcIdsNamedFirst(picked.rest);
1442
- const words = rest.join(" ").trim();
1443
- const separately = asksOneByOne(words);
1444
- // From scratch - the tests written again, the code untouched - asked in the person's words; the whole chain's with it.
1445
- const scratch = asksFromScratch(words) ? (asksWholeChain(words) ? "chain" : "module") : undefined;
1446
- // Nothing but the functional specs, from scratch and one by one: other words are not dropped unsaid.
1447
- if (words !== "" && !separately && scratch === undefined) {
1448
- refuse(`/conform takes functional specs, each as module:func-id, "from scratch" with "whole chain" and "one by one" - not "${words}". Nothing was started.`);
1449
- return;
1450
- }
1451
- if (scratch !== undefined && funcIds.length > 0) {
1452
- refuse("Name functional specs or ask for the conformance tests from scratch, not both: from scratch writes every one of them again. Nothing was started.");
1453
- return;
1454
- }
1455
- // Off: turned on - written where the module's value comes from, every chat's tools switched - and said with what follows.
1456
- let turnedOn;
1457
- try {
1458
- if (!conformanceTestsOn(plainFile))
1459
- turnedOn = `Conformance tests are on now - conformance-tests: true, written in ${turnOn(plainFile)}.`;
1460
- }
1461
- catch (error) {
1462
- refuse(`Conformance tests could not be turned on: ${error instanceof Error ? error.message : String(error)}. Nothing was started.`);
1463
- return;
1464
- }
1465
- const withTurnedOn = (text) => (turnedOn !== undefined ? `${turnedOn}\n${text}` : text);
1466
- // What would start nothing - no scenarios, a functional spec not there, a step of adding tests skipped - read from the
1467
- // ***plain alone, before anything is said.
1468
- let refusal;
1469
- try {
1470
- refusal = whenBuildable(plainFile, () => conformanceRefusal(plainFile, funcIds.length > 0 ? funcIds : undefined));
1471
- }
1472
- catch (error) {
1473
- refusal = { text: error instanceof Error ? error.message : String(error), stepsMissing: false };
1474
- }
1475
- // A step of adding tests still to take - the test reqs, the script, the scenarios: the chat's to take, so told to it
1476
- // alone, as what conform needs first. The person sees it take them, and conformance turned on, if it was.
1477
- if (refusal?.stepsMissing === true) {
1478
- if (turnedOn !== undefined)
1479
- shownAfterCommand(pi, ctx, command, turnedOn, "info", true);
1480
- toldAfterCommand(pi, command, refusal.text, CONFORM_STEPS_REACTION);
1481
- return;
1482
- }
1483
- if (refusal !== undefined) {
1484
- refuse(withTurnedOn(refusal.text));
1485
- return;
1486
- }
1487
- const module = basename(plainFile).replace(/\.plain$/, "");
1488
- const model = jobModel(ctx, undefined, plainFile);
1489
- const starting = scratch !== undefined
1490
- ? `Writing ${module}'s conformance tests${scratch === "chain" ? " and its whole chain's" : ""} again from scratch…`
1491
- : `Starting ${funcIds.length > 0 ? `the conformance tests of ${funcIds.join(", ")}` : `${module}'s conformance tests`}…`;
1492
- shownAfterCommand(pi, ctx, command, withTurnedOn(starting), "info", true);
1493
- await nextFrame();
1494
- // In the background, as /regenerate: a codebase built on the module may be stopped and deleted first.
1495
- void (async () => {
1496
- try {
1497
- const statuses = await whenBuildable(plainFile, () => workLoopFor(jobs, cwd, ctx).conformance(plainFile, {
1498
- ...(funcIds.length > 0 ? { funcIds } : {}),
1499
- ...(model !== undefined ? { model } : {}),
1500
- ...(separately ? { separately: true } : {}),
1501
- ...(scratch !== undefined ? { fromScratch: scratch } : {}),
1502
- }));
1503
- // Nothing to write: said in the loop's words - "up to date" alone speaks of the code, not its tests.
1504
- const upToDate = statuses.length > 0 && statuses.every(isUpToDate);
1505
- const note = statuses.find((status) => status.conformanceNote !== undefined)?.conformanceNote;
1506
- const text = upToDate ? `${(note ?? `the conformance tests of ${module} are written for it as built: there is nothing to write`).replace(/^./, (c) => c.toUpperCase())}.` : describeModules(statuses);
1507
- shownAfterCommand(pi, ctx, command, text, "info", true, upToDate ? undefined : COMMAND_STARTED_REACTION);
1508
- }
1509
- catch (error) {
1510
- if (error instanceof TestingStepsMissing)
1511
- toldAfterCommand(pi, command, error.message, CONFORM_STEPS_REACTION);
1512
- else
1513
- refuse(error instanceof Error ? error.message : String(error));
1514
- }
1515
- })().catch(() => {
1516
- // The chat let go meanwhile: there is nobody to say it to.
1517
- });
1518
- },
1519
- });
1520
- }
1521
- /**
1522
- * conform, for the conversation and for a skill that names it in its allowed-tools - the skill's on the conversation's
1523
- * loop, its pulses scheduled like any other.
1524
- */
1525
- function conformTool(options) {
1526
- const { cwd } = options;
1527
- return defineTool({
1528
- name: "conform",
1529
- label: "Conform",
1530
- description: "Write and run the black-box conformance tests of a module's functional specs - the ones named, or every one with " +
1531
- "scenarios - on the code as it is built, in a pulse of their own - every functional spec tested in one, as far as a size " +
1532
- "guardrail lets, or one a functional spec when the user asks for that: each implements exactly the functional spec's " +
1533
- "conformance and acceptance scenarios, at least one test each, by the spec's test reqs, runs them with the whole suite " +
1534
- "the module inherits, and, where one fails, fixes the test or the code, whichever is wrong. What they are written for is " +
1535
- "recorded apart from the code. The work loop starts these pulses by itself for every functional spec with scenarios whose " +
1536
- "tests are behind, once the module's code is built; conform starts them now, or for the functional specs named - those alone: the module's others stay behind until conform names none, or the module is regenerated. " +
1537
- "A functional spec named whose tests are written already has them written again - deleted and written anew from its " +
1538
- "scenarios, its code untouched; with from_scratch, the module's whole tests folder is taken out and written again, at " +
1539
- "the tip of each chain it is built in, as regenerate from scratch does its code. A " +
1540
- "functional spec with no scenarios - no test plain file - is refused: there is nothing to test until scenarios " +
1541
- "are written. So is one the spec does not have, and a module with scenarios that skipped a step of adding tests - " +
1542
- "no test reqs, or no conformance testing script: the refusal names the next step. While conformance tests " +
1543
- "are off it is refused too: they make each change take about twice as long, and turning them on is the person's - " +
1544
- "with /conform - never yours.",
1545
- promptSnippet: "conform: write and run the conformance tests of functional specs with scenarios",
1546
- promptGuidelines: [
1547
- "What is tested is the scenarios: a functional spec's conformance and acceptance scenarios, in its test plain file, tests/<module>/<func-id>.plain. When the user asks for conformance tests, decide in a sentence or two which scenarios to write, write them with the file tools - a test plain file's ***conformance tests*** and ***acceptance tests***, each scenario a # <scenario-id> heading and its text - then call regenerate for the module. Every scenario written is tested once the code is built: the loop starts the conformance pulse by itself. Never edit config.turri.yaml for it, and never name a functionality in funcIds to get them.",
1548
- "Call conform when the user asks for the conformance tests to be written or run now, for a module or some of its functional specs with scenarios.",
1549
- "What the user asks for comes first: for a module already regenerated, while a module built on it is being regenerated, conform stops that pulse, deletes the codebase built on it, writes the tests, and the module above is regenerated from it after - say so. For a module not regenerated yet, its tests are written once its code is built, before anything is built on it.",
1550
- "Conformance tests go in one pulse for all the functional specs tested. Set one_by_one only when the user asks for a pulse a functional spec - one at a time, separately, or the like.",
1551
- "Name a functional spec whose tests are written only when the user asks for its tests to be written again: they are deleted and written anew. Set from_scratch only when the user asks for a module's conformance tests - or its whole chain's - to be written again from scratch, never to fix tests that did not pass. Name funcIds or set from_scratch, not both.",
1552
- 'from_scratch works where the module\'s code lives - the tip of each chain it is built in, never a module in the middle - and takes that codebase\'s whole tests folder out, committed first so its lineage keeps it. "module" starts it again from a copy of the tests of the module the tip requires, and writes the tip\'s own tests anew on them; "chain" starts it from nothing, every functional spec of the chain written anew. Neither touches the code, nor any other codebase.',
1553
- ],
1554
- parameters: Type.Object({
1555
- plain_file: Type.String({ description: "A .plain file of the module" }),
1556
- working_dir: WORKING_DIR_PARAM,
1557
- funcIds: Type.Optional(Type.Array(Type.String(), {
1558
- description: "The functional specs to test, each as module:func-id (todo:add-task) - each with scenarios; one whose tests are written has them written again. Omitted: every one with scenarios",
1559
- })),
1560
- from_scratch: Type.Optional(Type.Union([Type.Literal("module"), Type.Literal("chain")], {
1561
- description: "Only when the user asks for it: the tests folder where the module's code lives - the tip of its chain - taken out, committed first so its lineage keeps it, and written again from a copy of the tests of the module the tip requires; the code untouched. " +
1562
- '"chain": written again from nothing - every functional spec of the chain\'s tests',
1563
- })),
1564
- one_by_one: Type.Optional(Type.Boolean({ description: "Only when the user asks for it: a pulse a functional spec. Omitted: every functional spec tested in one pulse, as far as the size guardrail lets" })),
1565
- model: MODEL_PARAM,
1566
- wait: WAIT_PARAM,
1567
- }),
1568
- async execute(_id, given, _signal, _onUpdate, ctx) {
1569
- const params = fromWorkingDir(cwd, given);
1570
- const plainFile = resolve(params.base, params.plain_file);
1571
- refuseTestPlainFile(plainFile);
1572
- return whenBuildable(plainFile, async () => {
1573
- // Off: the person's to turn on, never the chat's - it is told to say why it wants them, and they decide.
1574
- if (!conformanceTestsOn(plainFile))
1575
- return { content: [{ type: "text", text: CONFORMANCE_OFF_REFUSAL }], details: { refused: true } };
1576
- const model = options.model(ctx, plainFile, params.model);
1577
- const loop = options.loop(ctx);
1578
- const wait = options.wait(ctx, params.wait);
1579
- const waiting = wait ? { jobs: options.jobs, wait: startWait(options.jobs) } : undefined;
1580
- let statuses;
1581
- try {
1582
- statuses = await loop.conformance(plainFile, {
1583
- ...(params.funcIds !== undefined ? { funcIds: params.funcIds } : {}),
1584
- ...(model !== undefined ? { model } : {}),
1585
- ...(params.one_by_one === true ? { separately: true } : {}),
1586
- ...(params.from_scratch !== undefined ? { fromScratch: params.from_scratch } : {}),
1587
- });
1588
- }
1589
- catch (error) {
1590
- if (waiting !== undefined)
1591
- endWait(waiting.jobs, waiting.wait);
1592
- throw error;
1593
- }
1594
- return loopReply(loop, statuses, wait, waiting);
1595
- });
1596
- },
1597
- });
1598
- }
1599
- /** The config a spec is built with - its project's, with its module's own file over it - or, with no spec, the session folder's. */
1600
- function configOf(plainFile) {
1601
- return plainFile !== undefined ? configForSpec(resolve(process.cwd(), plainFile)) : readProjectConfig(process.cwd(), configModuleOf(process.cwd()));
1602
- }
1603
- /**
1604
- * How many jobs the chat runs at once: `parallel-jobs:` in the session folder's config.turri.yaml - the only place it
1605
- * is set - else half this machine's cores, between one and four.
1606
- */
1607
- export function parallelJobs(cwd) {
1608
- return readProjectConfig(cwd).parallelJobs ?? defaultParallelJobs();
1609
- }
1610
- /**
1611
- * This machine, for the chat's agent, read afresh every turn: which wall is up under the agents' commands, whether the
1612
- * machine has the toolchains the project's modules name, and what in its testing scripts it lacks - for the person to
1613
- * install or fix; the agents install nothing. `modules`: what the modules need, when it is known already - working it
1614
- * out parses every spec of the project.
1615
- */
1616
- export function machineBlock(cwd, modules = stackOnMachine(cwd)) {
1617
- const wall = sandboxAvailable();
1618
- const walls = wall.kind === "none"
1619
- ? `behind the command check and the audit alone - no OS sandbox: ${wall.why}${wall.fix !== undefined ? ` (to give it one: ${wall.fix})` : ""}`
1620
- : `behind the command check, ${wall.kind === "seatbelt" ? "Seatbelt" : "bubblewrap"} and the audit`;
1621
- const needing = modules.filter(({ needs }) => needs.length > 0);
1622
- const scripts = findTestScripts(cwd);
1623
- const misfits = [scripts.unit, scripts.prepare, scripts.conformance].flatMap((script) => {
1624
- if (script === undefined)
1625
- return [];
1626
- const text = readScript(script);
1627
- const found = text !== undefined ? scriptAgainstMachine(text) : [];
1628
- return found.length > 0 ? [`- ${relative(cwd, script)} does not fit this machine: it ${found.join("; ")} - the person's to fix.`] : [];
1629
- });
1630
- return [
1631
- "<this machine>",
1632
- `The agents' commands run on this machine, with its toolchains, ${walls}. The testing scripts run here too, unfenced, in the person's environment. Nothing is installed by an agent: what the machine lacks is the person's to install.`,
1633
- ...needing.map(({ module, needs, missing }) => `- ${module}: its implementation reqs need ${needs.map((need) => `${need.toolchain} (${need.words.join(", ")})`).join(", ")}${missing.length > 0 ? ` - this machine LACKS ${missing.map((need) => need.toolchain).join(", ")}` : " - this machine has them"}.`),
1634
- ...misfits,
1635
- "</this machine>",
1636
- "",
1637
- toolchainsBlock(),
1638
- ].join("\n");
1639
- }
1640
- /**
1641
- * What the project's modules need of this machine, kept between turns - working it out parses every spec, seconds on a
1642
- * project of long requires chains. Worked out when the first turn asks - not as the session starts: a host's thread
1643
- * would be held up opening a chat no one may write in - and again, once known, when a turn has settled and a spec
1644
- * changed since: a turn is told what was known last, at most a turn behind.
1645
- */
1646
- export function machineNeeds(cwd, work = stackOnMachine) {
1647
- let known;
1648
- /** The project's specs as they are on disk: their names and when each last changed. */
1649
- const stamp = () => {
1650
- try {
1651
- return readdirSync(cwd)
1652
- .filter((name) => name.endsWith(".plain"))
1653
- .sort()
1654
- .map((name) => `${name}\0${statSync(join(cwd, name)).mtimeMs}`)
1655
- .join("\n");
1656
- }
1657
- catch {
1658
- return "";
1659
- }
1660
- };
1661
- const refresh = () => {
1662
- const now = stamp();
1663
- if (known?.stamp === now)
1664
- return;
1665
- known = { stamp: now, modules: work(cwd) };
1666
- };
1667
- return {
1668
- /** What is known - worked out now only when nothing is yet. */
1669
- now() {
1670
- if (known === undefined)
1671
- refresh();
1672
- return known.modules;
1673
- },
1674
- /** Worked out again, if it is known and a spec changed - once the chat has drawn what it is drawing. */
1675
- refreshSoon() {
1676
- if (known === undefined)
1677
- return;
1678
- setTimeout(() => {
1679
- try {
1680
- refresh();
1681
- }
1682
- catch {
1683
- // Told what was known last.
1684
- }
1685
- }, ONE_FRAME_MS);
1686
- },
1687
- };
1688
- }
1689
- /** Whether a folder holds a project's config: config.turri.yaml, a module's own, or the config.turri.yaml read until there is one. */
1690
- function hasConfig(dir) {
1691
- return hasProjectConfig(dir);
1692
- }
1693
- /**
1694
- * The project's config.turri.yaml, for the chat's agent: what it says, and what that means for the
1695
- * tools - so a question about the project's settings is answered from the file, not from the
1696
- * tools' defaults.
1697
- */
1698
- export function projectConfigBlock(root) {
1699
- // The session's folder, and the projects one folder down - specs kept in plain/, with its own
1700
- // config.turri.yaml and plain_modules - which its specs are built in when named from here.
1701
- const projects = [
1702
- ...(hasConfig(root) ? [root] : []),
1703
- ...readdirSync(root, { withFileTypes: true })
1704
- .filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules" && entry.name !== "plain_modules")
1705
- .map((entry) => join(root, entry.name))
1706
- .filter(hasConfig),
1707
- ];
1708
- if (projects.length === 0)
1709
- return "";
1710
- const describe = (dir) => {
1711
- const modules = moduleConfigsOf(dir);
1712
- const where = dir === root ? "" : ` (paths relative to ${relative(root, dir)}${sep})`;
1713
- const at = (name) => (dir === root ? name : join(relative(root, dir), name));
1714
- return [
1715
- ...settings(readProjectConfig(dir), withConfigModule(undefined, () => findTestScripts(dir)), dir === root ? `${projectConfigFile(dir)}, for the specs here:` : `${join(relative(root, dir), projectConfigFile(dir))}, for the specs in ${relative(root, dir)}${sep} - built in ${join(relative(root, dir), "plain_modules")}:`, where, modules.length > 0 ? "project of module files" : "project"),
1716
- // A module's own file: over the project's, for it and every module built on it that has no file of its own.
1717
- ...modules.flatMap((module) => [
1718
- "",
1719
- ...settings(readProjectConfig(dir, module), withConfigModule(module, () => findTestScripts(dir)), `${at(moduleConfigFileIn(dir, module))}, over ${projectConfigFile(dir)}, for ${module}.plain and every module built on it that has no file of its own - what it sets itself, and the testing scripts it builds with; the rest is ${projectConfigFile(dir)}'s:`, where, "module", readConfigFile(join(dir, moduleConfigFileIn(dir, module)))),
1720
- ]),
1721
- ];
1722
- };
1723
- const settings = (config, scripts, heading, where,
1724
- /** The project's file, and whether modules have files of their own - whose scripts are theirs - or a module's. */
1725
- of,
1726
- /** A module's file as written: only what it sets itself is said - an inherited setting said again reads as its own. */
1727
- own) => {
1728
- const perModule = of === "project of module files";
1729
- const sets = (set) => own === undefined || set;
1730
- return [
1731
- heading,
1732
- ...[
1733
- config.module !== undefined && of !== "module" ? `- module: ${config.module}${where} - the module to build when the user does not name one.` : undefined,
1734
- of !== "module"
1735
- ? "- conformance tests: written for every functional spec with scenarios - the conformance and acceptance scenarios of its test plain file - once the module's code is built, before anything is built on it. A functional spec with an empty test plain file is not tested. To have one tested, write its scenarios with the file tools, then call regenerate."
1736
- : undefined,
1737
- !sets(own?.review !== undefined)
1738
- ? undefined
1739
- : config.review === true
1740
- ? "- review: true - the code and its tests are reviewed once they pass: two reviews at most, the arbiter weighing the second."
1741
- : `- review: ${config.review === false ? "false" : "not set, so off"} - the code and its tests are not reviewed: a pulse lands once its tests pass.`,
1742
- ...(() => {
1743
- // Each as it holds, with what it inherits: judge from coding, coding from harness.
1744
- const models = projectModels(config);
1745
- const shown = (choice) => modelSpec(choice) ?? "";
1746
- return [
1747
- models.coding !== undefined && sets(own?.codingModel !== undefined || own?.models?.coding !== undefined || own?.models?.default !== undefined) ? `- coding-model: ${shown(models.coding)}${config.codingModel === undefined ? " (from harness-model)" : ""} - what pulses run on, unless a call names another model.` : undefined,
1748
- models.judge !== undefined && sets(own?.judgeModel !== undefined || own?.models?.judge !== undefined) ? `- judge-model: ${shown(models.judge)}${config.judgeModel === undefined ? " (from coding-model)" : ""} - the judge and the test review in a conformance run.` : undefined,
1749
- models.harness !== undefined && of !== "module" ? `- harness-model: ${shown(models.harness)} - the model you start with.` : undefined,
1750
- // The other roles' own, where models: names them.
1751
- ...AGENT_ROLES.filter((role) => role !== "coding" && role !== "chat").flatMap((role) => {
1752
- const named = roleModel(config, role);
1753
- return named !== undefined && sets(own?.models?.[role] !== undefined) ? [`- models: ${role}: ${shown(named)}`] : [];
1754
- }),
1755
- ...(() => {
1756
- const limits = AGENT_ROLES.flatMap((role) => (config.models?.[role]?.turnLimit !== undefined ? [`${role} ${config.models[role].turnLimit}s`] : []));
1757
- const all = config.models?.default?.turnLimit ?? config.turnLimit;
1758
- return (all !== undefined || limits.length > 0) && sets(own?.turnLimit !== undefined || own?.models !== undefined) ? [`- turn limits: ${all !== undefined ? `${all}s each` : "two minutes each"}${limits.length > 0 ? `; ${limits.join(", ")}` : ""}.`] : [];
1759
- })(),
1760
- ];
1761
- })(),
1762
- `- unit testing script: ${scripts.unit !== undefined ? relative(root, scripts.unit) : perModule ? "none for the whole project - each module's file below names its own" : "none found - every build stops until there is one"}`,
1763
- `- conformance testing script: ${scripts.conformance !== undefined ? relative(root, scripts.conformance) : perModule ? "none for the whole project - see each module's file" : "none found"}`,
1764
- scripts.prepare !== undefined ? `- prepare script: ${relative(root, scripts.prepare)} - run on the build before every conformance testing script run, which runs only once it passes` : undefined,
1765
- !sets(own?.testingScriptsRunOn !== undefined)
1766
- ? undefined
1767
- : config.testingScriptsRunOn === "copy"
1768
- ? "- testing-scripts-run-on: copy - the testing scripts run on this machine, on a fresh copy of each module's code; `testing-scripts-run-on: in-place` (the default) runs them on the code in place."
1769
- : "- testing-scripts-run-on: in-place - the testing scripts run on this machine on the code in place, from the project, against the host codebase; `testing-scripts-run-on: copy` runs them on a fresh copy of each module's code.",
1770
- ].filter((line) => line !== undefined),
1771
- ];
1772
- };
1773
- return [
1774
- `<project config>`,
1775
- `A project's ${CONFIG_FILE} sets how its modules are built - and a module's own config.turri.<module>.yaml, over it, how that`,
1776
- "module is built, and every module built on it that has no file of its own: its testing scripts, toolchains, models and conformance -",
1777
- "a backend and a frontend each with their own scripts. Nobody chooses it: each module is built with its own file, else the one of",
1778
- "a module it requires, else the project's alone - two among the modules it requires is an error to fix. A project with no",
1779
- `${CONFIG_FILE} yet is read from its ${LEGACY_CONFIG_FILE} (and config.<module>.yaml). Change a setting with the settings tool,`,
1780
- "never by editing these files; answer questions about the project's settings from what follows, and say when a pulse will",
1781
- "differ from it because the user asked. Name a spec by its path from here - plain/hubspot.plain - and it is built in its own project.",
1782
- ...projects.flatMap((dir) => ["", ...describe(dir)]),
1783
- `</project config>`,
1784
- ].join("\n");
1785
- }
1786
- /**
1787
- * The model the spawned agents should use.
1788
- *
1789
- * Without this they fall back to whatever pi is configured to default to, which is not
1790
- * necessarily the model the conversation is on - switching model mid-session would leave
1791
- * every tool still building with the old one, silently.
1792
- */
1793
- function conversationModel(ctx, override) {
1794
- if (override !== undefined)
1795
- return override;
1796
- return ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined;
1797
- }
1798
- /**
1799
- * The chat's model, read now - it can change while a skill runs - or, from a context that has
1800
- * gone stale since, the model it had when it was last readable.
1801
- */
1802
- /**
1803
- * The model a launch runs on: the coding model of the codebase - a launch follows steps, and a small model thinking little
1804
- * does that well. Without a chat's context yet, the config's as it names it.
1805
- */
1806
- function launchModel(ctx, plainFile) {
1807
- try {
1808
- if (ctx !== undefined)
1809
- return projectModel(ctx, plainFile) ?? chatModelOf(ctx);
1810
- }
1811
- catch {
1812
- /* a name the chat cannot resolve: the config's, as it is */
1813
- }
1814
- return modelSpec(projectModels(configForSpec(plainFile)).coding);
1815
- }
1816
- function chatModelOf(ctx) {
1817
- try {
1818
- const now = conversationModel(ctx);
1819
- lastChatModel = now ?? lastChatModel;
1820
- return now;
1821
- }
1822
- catch {
1823
- return lastChatModel;
1824
- }
1825
- }
1826
- let lastChatModel;
1827
- /**
1828
- * Conformance tests turned on, for the session: `conformance-tests: true` written where the module's value comes from
1829
- * (conformance-switch.ts) - what /conform does when they are off, and a host's turnOnConformance. Every chat is told at
1830
- * its next turn. `plainFile`, absolute or from the project, picks the module whose own file
1831
- * is written when that names the key. Returns the file written, from the project. Starts no conformance pulse.
1832
- */
1833
- export function turnOnConformance(core, plainFile) {
1834
- const file = turnOnConformanceTests(core.cwd, plainFile !== undefined && plainFile.trim() !== "" ? resolve(core.cwd, plainFile) : undefined);
1835
- return file;
1836
- }
1837
- /** The skills running in the background, by project and skill - one at a time each, whichever chat started it - with what stops them. */
1838
- const backgroundSkillRuns = new Map();
1839
- /** The .plain file each run in `backgroundSkillRuns` is for. */
1840
- const backgroundSkillFor = new Map();
1841
- /** The runs for other modules waiting their turn, by project and skill: each started as the one before it ends, or dropped as turri quits. */
1842
- const backgroundSkillQueue = new Map();
1843
- /**
1844
- * The model a pulse's agents run on: the one named on the call, checked now so a wrong name fails here and not minutes
1845
- * later in the background; else the coding model - `--coding-model`, or the module's config - else the conversation's.
1846
- */
1847
- function jobModel(ctx, named, plainFile) {
1848
- const model = jobModelOf(ctx, named, plainFile);
1849
- // The AWS region worked out again, with every model a job ran on this session: the config's may have changed since,
1850
- // and one named on a call counts as the config's do - two needing two regions are said, not flipped between.
1851
- if (model !== undefined)
1852
- jobModels.add(model);
1853
- applyBedrockRegion(plainFile !== undefined ? projectDirOf(plainFile) : process.cwd(), { also: [...jobModels] });
1854
- return model;
1855
- }
1856
- /** Every model a job ran on in this session. */
1857
- const jobModels = new Set();
1858
- function jobModelOf(ctx, named, plainFile) {
1859
- if (named !== undefined && named.trim() !== "") {
1860
- const resolved = resolveModel(named, ctx.modelRegistry);
1861
- if (!resolved.ok)
1862
- throw new Error(describeResolution(resolved));
1863
- return resolved.model;
1864
- }
1865
- return projectModel(ctx, plainFile) ?? chatModelOf(ctx);
1866
- }
1867
- /**
1868
- * The coding model this session starts from, and where it was given: `turri
1869
- * --coding-model`, or `coding-model:` in the project's config.turri.yaml - read afresh, so an edit to the
1870
- * file holds for the next render.
1871
- */
1872
- function codingModelDefault(plainFile) {
1873
- const flag = process.env[CODING_MODEL_ENV]?.trim();
1874
- if (flag)
1875
- return { named: flag, from: "--coding-model" };
1876
- // The coding model inherits what it leaves out from the harness model.
1877
- const named = modelSpec(projectModels(configOf(plainFile)).coding);
1878
- return named !== undefined ? { named, from: CONFIG_FILE } : undefined;
1879
- }
1880
- /**
1881
- * The default coding model, resolved as a name the person said would be. One that cannot be used
1882
- * says so, and where it came from, rather than running on something else.
1883
- */
1884
- function projectModel(ctx, plainFile) {
1885
- const given = codingModelDefault(plainFile);
1886
- if (given === undefined)
1887
- return undefined;
1888
- // The model is looked up by name; how hard it thinks goes along with it as it was given.
1889
- const { model, thinking } = splitModelSpec(given.named);
1890
- if (model === undefined)
1891
- return modelSpec({ thinking });
1892
- const resolved = resolveModel(model, ctx.modelRegistry);
1893
- if (!resolved.ok) {
1894
- throw new Error(`${given.from} names the coding model "${model}", which cannot be used here.\n\n${describeResolution(resolved)}`);
1895
- }
1896
- return modelSpec({ model: resolved.model, thinking });
1897
- }
1898
- /**
1899
- * Run the work now, or start it as a background job and hand back an id.
1900
- *
1901
- * Background only makes sense where the session outlives the turn. In print, json and rpc
1902
- * modes the process is gone the moment the answer is written, taking the job with it, so
1903
- * those wait by default.
1904
- */
1905
- /** The one work loop of a conversation's jobs: every tool that builds brings its modules up through it. */
1906
- const workLoops = new WeakMap();
1907
- /** A session's launches, by its jobs: the launch track every chat's launch tool and every pulse's launch share. */
1908
- const sessionLaunches = new WeakMap();
1909
- function workLoopFor(jobs, cwd, ctx) {
1910
- let shared = workLoops.get(jobs);
1911
- if (shared === undefined) {
1912
- const from = { ctx };
1913
- const loop = createWorkLoop({
1914
- registry: jobs,
1915
- cwd,
1916
- modelFor: (plainFile) => projectModel(from.ctx, plainFile) ?? chatModelOf(from.ctx),
1917
- // The planner reasons about the whole of the work: it runs on the chat's model.
1918
- plannerModel: () => chatModelOf(from.ctx),
1919
- // A pulse landed: its commit kept for the sentinel - and, under launch-after-pulse, launched in the background, the
1920
- // codebase's next pulse not waiting on it.
1921
- landed: (input) => sessionLaunches.get(jobs)?.landed(input),
1922
- });
1923
- shared = { loop, from };
1924
- workLoops.set(jobs, shared);
1925
- }
1926
- shared.from.ctx = ctx;
1927
- return shared.loop;
1928
- }
1929
- async function deliver(jobs, input) {
1930
- const wait = shouldWait(input.mode, input.wait);
1931
- if (wait) {
1932
- let streamed = "";
1933
- const { result: outcome, output } = await captureConsole(() => input.run((delta) => {
1934
- streamed += delta;
1935
- input.onUpdate?.({ content: [{ type: "text", text: streamed }], details: {} });
1936
- }));
1937
- const noise = describeCaptured(output);
1938
- return {
1939
- content: [{ type: "text", text: noise ? `${outcome.report}\n\n${noise}` : outcome.report }],
1940
- details: outcome.details ?? {},
1941
- };
1942
- }
1943
- // The job's name stays short for the panel; which model it runs on goes to the agent.
1944
- const summary = input.summary;
1945
- const onModel = input.model ? ` on ${input.model}` : "";
1946
- const job = jobs.start({
1947
- kind: input.kind,
1948
- summary,
1949
- diff: input.diff,
1950
- model: input.model,
1951
- lanes: input.lanes,
1952
- // Background work writes through the same terminal the TUI is drawing on, so its
1953
- // console output is collected rather than printed.
1954
- run: async (onDelta) => {
1955
- const { result, output } = await captureConsole(() => input.run(onDelta));
1956
- const noise = describeCaptured(output);
1957
- return noise ? { ...result, report: `${result.report}\n\n${noise}` } : result;
1958
- },
1959
- });
1960
- return {
1961
- content: [
1962
- {
1963
- type: "text",
1964
- text: (job.status === "queued"
1965
- ? `Queued ${input.kind} as pulse ${job.id}: ${summary}${onModel}. It writes the same ` +
1966
- `module as ${job.waitingOn.map((id) => `pulse ${id}`).join(" and ")}, so it starts when that ` +
1967
- "finishes. Nothing to wait for: if what you are doing has a next step, take it now, in this same turn, and tell " +
1968
- "the user it is queued and why alongside it, never as a reply that ends your turn - and that the two of you " +
1969
- "can go on with the ***plain, or anything else, meanwhile: they need not wait for it. "
1970
- : `Started ${input.kind} as pulse ${job.id}: ${summary}${onModel}.\n` +
1971
- "It is running now and will report back when it finishes - nothing to wait for: if what you are doing has a " +
1972
- "next step, take it now, in this same turn, and tell the user it has started alongside it, never as a reply " +
1973
- "that ends your turn - and that the two of you can go on with the ***plain, or anything else, meanwhile: they " +
1974
- "need not wait for it. ") +
1975
- `Use pulses with "${job.id}" if they ask how it is going.`,
1976
- },
1977
- ],
1978
- details: { jobId: job.id, status: job.status },
1979
- };
1980
- }
1981
- /** Looking in on work that is still running, and collecting what finished. */
1982
- /** By registry: what opens the side panel - for a skill's question that invites the person to peek. */
1983
- const panelOpeners = new WeakMap();
1984
- /** By registry: the last pulse that failed, stopped or did not pass, not yet looked at - ctrl+h opens on it. */
1985
- const needsLooking = new WeakMap();
1986
- /** What heads a pulse told from the ledger: it is not this session's, and the facts are all there is of it. */
1987
- const pastPulseNote = "A pulse of an earlier session, as the ledger recorded it - facts, not its transcript. Its whole log is the file it names, " +
1988
- "for the read tool.";
1989
- function registerJobTools(pi, jobs, cwd) {
1990
- pi.registerTool(doctorTool({ cwd }));
1991
- pi.registerTool({
1992
- name: "pulses",
1993
- label: "Pulses",
1994
- description: "Pulses in every tense - earlier sessions', this session's, running now and what runs next. With no parameter: every pulse of " +
1995
- "this session - finished, running, and planned, those of a look ahead marked as waiting for regenerate - the launches and what they started, " +
1996
- "and the last runs of earlier sessions, a line a pulse - how each ended, how long, what it cost. With job_id, one pulse: " +
1997
- "running, whether it still is and its latest output; finished, its report and what the ledger recorded of it - its rounds " +
1998
- "and test runs (how many failed the same way), the verdicts, the healers, the model provider's trouble, what turri refused, " +
1999
- "what it committed - and, one that did not land, why, from its whole transcript: its diagnosis, the stages that went wrong, " +
2000
- "the last failing test run with its output, the last review that sent the work back, the tool calls that failed, and where " +
2001
- "the whole log is; of an earlier session, told from the ledger; planned (planned-<module>-N), its cases and - the next pulse " +
2002
- "of its codebase - the whole prompt its coding agent will get, from the plan regenerate runs. With plain_file, a look " +
2003
- "ahead: that module's work planned as regenerate plans it, and kept - nothing started, its pulses waiting " +
2004
- "for regenerate, which then runs this plan unless the ***plain changed - and what is planned listed. " +
2005
- "What is left to regenerate, without a plan, is drift's. Every generation of a module's code and tests is a commit in its " +
2006
- "history, read with git: git --git-dir=plain_modules/<module>/.plaingit log, and show <commit>.",
2007
- promptSnippet: "pulses: every pulse or one - earlier, running or planned - why one did not land, and with plain_file what will run next and its prompt",
2008
- promptGuidelines: [
2009
- "When a pulse failed or did not land, call pulses with its id before you explain it or change the spec: go by what happened, not by the report alone.",
2010
- "Call pulses with plain_file when the user wants to see or check what will run before it does, then with a planned row's id for its prompt. To change the plan, change the ***plain, then look again.",
2011
- ],
2012
- parameters: Type.Object({
2013
- job_id: Type.Optional(Type.String({
2014
- description: "One pulse: the id returned when it started, an earlier session's, or a planned row's (planned-<module>-N). Omitted: every pulse",
2015
- })),
2016
- plain_file: Type.Optional(Type.String({ description: "A look ahead: the .plain file of the module to plan, starting nothing. Not with job_id. Omitted: no look ahead" })),
2017
- working_dir: WORKING_DIR_PARAM,
2018
- wait: Type.Optional(Type.Boolean({ description: "With a pulse started: block until it finishes instead of reporting its current state (default false)" })),
2019
- runs: Type.Optional(Type.Number({ description: `With no parameter: how many runs of earlier sessions to list (default ${EARLIER_RUNS})` })),
2020
- }),
2021
- async execute(_id, params, _signal, _onUpdate, ctx) {
2022
- if (params.plain_file !== undefined) {
2023
- if (params.job_id !== undefined)
2024
- return { content: [{ type: "text", text: "Pass job_id or plain_file, not both: plain_file looks ahead at a module, job_id tells one pulse." }], details: { status: "refused" } };
2025
- const given = fromWorkingDir(cwd, params);
2026
- const plainFile = resolve(given.base, given.plain_file);
2027
- refuseTestPlainFile(plainFile);
2028
- return whenBuildable(plainFile, async () => {
2029
- const loop = workLoopFor(jobs, cwd, ctx);
2030
- const statuses = await loop.lookAhead(plainFile);
2031
- return { content: [{ type: "text", text: describeLookAhead(loop, statuses) }], details: { status: "looked ahead" } };
2032
- });
2033
- }
2034
- if (params.job_id === undefined) {
2035
- const runs = params.runs !== undefined && Number.isFinite(params.runs) ? Math.max(1, Math.floor(params.runs)) : EARLIER_RUNS;
2036
- return { content: [{ type: "text", text: listJobs(jobs, cwd, runs) }], details: { status: "all" } };
2037
- }
2038
- const existing = jobs.get(params.job_id);
2039
- const planned = shownJobs(jobs).find((job) => job.id === params.job_id && jobs.get(job.id) === undefined);
2040
- if (planned !== undefined) {
2041
- const pulse = await workLoops.get(jobs)?.loop.plannedPulse(planned.id);
2042
- return { content: [{ type: "text", text: describePlannedRow(planned, pulse) }], details: { status: "planned" } };
2043
- }
2044
- if (existing === undefined) {
2045
- const past = describePastPulse(ledgerProjects(cwd), params.job_id);
2046
- if (past !== undefined)
2047
- return { content: [{ type: "text", text: `${pastPulseNote}\n\n${past}` }], details: { status: "earlier" } };
2048
- const known = shownJobs(jobs).map((job) => job.id);
2049
- return {
2050
- content: [
2051
- {
2052
- type: "text",
2053
- text: `No pulse ${params.job_id}. ${known.length > 0 ? `Known pulses: ${known.join(", ")}.` : "No pulses have been started."}`,
2054
- },
2055
- ],
2056
- details: { status: "unknown" },
2057
- };
2058
- }
2059
- const job = params.wait === true ? await jobs.wait(params.job_id) : existing;
2060
- if (job.status === "running" || job.status === "queued")
2061
- return { content: [{ type: "text", text: describeJob(job) }], details: { status: job.status } };
2062
- // Ended: how it went - why, for one that did not land - and what the ledger recorded of it besides: its rounds, test
2063
- // runs, verdicts, healers and commits, as facts. A pulse that landed after a struggle shows it there.
2064
- const told = didNotLand(job) ? whyFailed(job) : describeJob(job);
2065
- const facts = describePastPulse(ledgerProjects(cwd), job.id, { report: false });
2066
- const text = facts !== undefined ? `${told}\n\nWhat the ledger recorded of it:\n${facts}` : told;
2067
- return { content: [{ type: "text", text }], details: { status: job.status } };
2068
- },
2069
- });
2070
- // The panel is compact and ctrl+o only lasts as long as the work does. This is the whole
2071
- // list, finished jobs included, put in the transcript where it stays.
2072
- pi.registerCommand("halt", {
2073
- description: "Halt a queued or running pulse, a module's planned pulses, a launch, or what a launch started: /halt [pulse id | module | launched <name | module>]",
2074
- handler: async (args, ctx) => {
2075
- if (!ctx.hasUI)
2076
- return;
2077
- const live = jobs.list().filter((job) => job.status === "running" || job.status === "queued");
2078
- const servers = runningLaunched();
2079
- const track = sessionLaunches.get(jobs)?.track;
2080
- const underWay = (track?.list() ?? []).filter((launch) => launch.status === "running" || launch.status === "waiting");
2081
- const loop = workLoops.get(jobs)?.loop;
2082
- // A module's planned pulses, one line a module: halting one halts the module.
2083
- const plannedRows = loop?.planned() ?? [];
2084
- const planned = [...new Set(plannedRows.map((row) => row.module ?? ""))].filter((module) => module !== "");
2085
- let id = args.trim();
2086
- if (id === "") {
2087
- if (live.length === 0 && servers.length === 0 && underWay.length === 0 && planned.length === 0)
2088
- return ctx.ui.notify("Nothing is regenerating, queued, planned or launched.", "info");
2089
- const label = (job) => `${job.id} ${job.status.padEnd(8)} ${pulseName(job)}`;
2090
- const plannedLabel = (module) => {
2091
- const rows = plannedRows.filter((row) => row.module === module);
2092
- const waiting = rows.find((row) => row.id.endsWith("-waiting"));
2093
- return `${module} ${waiting !== undefined ? waiting.summary : `${rows.length} planned`} - halts the module`;
2094
- };
2095
- const labels = [
2096
- ...live.map(label),
2097
- ...planned.map(plannedLabel),
2098
- ...underWay.map(describeLaunchLine),
2099
- ...servers.map((item) => launchedLabel(item.name, item.url ?? item.command)),
2100
- ];
2101
- const picked = await ctx.ui.select("Halt which?", labels);
2102
- const job = live.find((candidate) => picked !== undefined && label(candidate) === picked);
2103
- const module = planned.find((name) => picked !== undefined && plannedLabel(name) === picked);
2104
- const launch = underWay.find((candidate) => picked !== undefined && describeLaunchLine(candidate) === picked);
2105
- const server = servers.find((item) => picked !== undefined && launchedLabel(item.name, item.url ?? item.command) === picked);
2106
- if (server !== undefined)
2107
- id = `launched ${server.name}`;
2108
- else if (launch !== undefined)
2109
- id = `launched ${launch.codebase}`;
2110
- else if (job !== undefined)
2111
- id = job.id;
2112
- else if (module !== undefined)
2113
- id = module;
2114
- else
2115
- return;
2116
- }
2117
- const name = /^launched\s+(.+)$/.exec(id)?.[1]?.trim();
2118
- if (name !== undefined)
2119
- return shownAfterCommand(pi, ctx, `/halt ${id}`, await haltLaunched(name, track), "info");
2120
- ctx.ui.notify(stopJob(jobs, id, undefined, loop), "info");
2121
- },
2122
- });
2123
- // Debug mode, for the render agents started from now on - see debug-log.ts.
2124
- // A module's history: every render, regeneration and conformance run, as git commits.
2125
- pi.registerCommand("lineage", {
2126
- description: "Show a module's lineage - every generation of its code and tests, and what each was regenerated from: /lineage [module]",
2127
- handler: async (args, ctx) => {
2128
- if (!ctx.hasUI)
2129
- return;
2130
- const modules = modulesWithHistory(cwd);
2131
- let name = args.trim();
2132
- if (name === "") {
2133
- if (modules.length === 0)
2134
- return ctx.ui.notify("No module has any history yet.", "info");
2135
- name = modules.length === 1 ? modules[0] : ((await ctx.ui.select("Lineage of which module?", modules)) ?? "");
2136
- if (name === "")
2137
- return;
2138
- }
2139
- pi.appendEntry(HISTORY_ENTRY, { module: name, text: historyLog(defaultBuildDir(name, cwd)) });
2140
- },
2141
- });
2142
- // The side panel: the regeneration - and the pulses behind p - over the whole screen, or beside the chat (s, from one to
2143
- // the other). Its key (PANEL_KEY) opens it; the key again closes it and goes back to the chat, as esc does over the
2144
- // screen - beside the chat, the key switches sides, giving the keys to the chat or the panel, as esc gives them to the
2145
- // chat, the panel staying; ctrl+c closes it.
2146
- // While the panel has the keys, every key is its own.
2147
- // The side panel is the session's, one for every chat: it stays on the screen - beside the chat or over it - as
2148
- // another chat is shown, and what it says to a chat it says to the one shown.
2149
- const sidePanel = sidePanelOf(jobs, cwd);
2150
- const openPanel = sidePanel.open;
2151
- pi.on("session_start", () => {
2152
- sidePanel.say = (text) => pi.sendUserMessage(text, { deliverAs: "followUp" });
2153
- });
2154
- // /pulses opens the side panel on every pulse, regenerating, planned and finished, and what each regenerates; regen -
2155
- // the spec, with how far the code has been regenerated into it - is PANEL_KEY's, no command of its own beside
2156
- // /regenerate. What the agents did is in each pulse's log.
2157
- pi.registerCommand("pulses", {
2158
- description: `The pulses, in the side panel: every pulse, regenerating, planned and finished, and what each regenerates. ${PANEL_KEY} opens the panel too.`,
2159
- handler: async (_args, ctx) => {
2160
- if (!ctx.hasUI)
2161
- return;
2162
- openPanel(ctx, "pulses");
2163
- },
2164
- });
2165
- panelOpeners.set(jobs, (ctx) => openPanel(ctx));
2166
- // A question open in the chat on the screen peeks at this chat's panel.
2167
- const peek = {
2168
- open: (ctx) => openPanel(ctx),
2169
- shown: () => sidePanel.shown(),
2170
- };
2171
- questionPeek = peek;
2172
- pi.on("session_start", () => {
2173
- questionPeek = peek;
2174
- });
2175
- pi.registerShortcut(PANEL_KEY, {
2176
- description: "Peek at regen and the pulses - a question waiting in the chat waits for you - or go back to it",
2177
- handler: async (ctx) => {
2178
- if (!ctx.hasUI)
2179
- return;
2180
- openPanel(ctx);
2181
- },
2182
- });
2183
- // /settings: every setting of config.turri.yaml from the chat, each taking effect as it says - what turri fixed at its
2184
- // start changed here, as it runs.
2185
- registerSettings(pi, {
2186
- cwd,
2187
- rules: ruleNames,
2188
- chatSpec: () => modelSpec(projectModels(readProjectConfig(cwd)).harness),
2189
- live: {
2190
- chatModel: async (spec, ctx) => {
2191
- if (spec === undefined)
2192
- return "The conversation keeps the model it runs on now; turri starts on pi's own choice next time.";
2193
- const { model, thinking } = splitModelSpec(spec);
2194
- if (model !== undefined) {
2195
- const resolved = resolveModel(model, ctx.modelRegistry);
2196
- if (!resolved.ok)
2197
- return `The conversation keeps its model: ${model} cannot be used here.\n${describeResolution(resolved)}`;
2198
- const slash = resolved.model.indexOf("/");
2199
- const found = ctx.modelRegistry.find(resolved.model.slice(0, slash), resolved.model.slice(slash + 1));
2200
- if (found === undefined || !(await pi.setModel(found)))
2201
- return `The conversation keeps its model: ${resolved.model} could not be switched to.`;
2202
- }
2203
- if (thinking !== undefined)
2204
- pi.setThinkingLevel(thinking);
2205
- return `The conversation runs on ${spec} now.`;
2206
- },
2207
- codingModel: () => {
2208
- const dropped = [];
2209
- // What the session chose wins over the file; changed in the file, the file's holds from now on.
2210
- if (process.env[CODING_MODEL_ENV] !== undefined) {
2211
- dropped.push(`--coding-model ${process.env[CODING_MODEL_ENV]}`);
2212
- delete process.env[CODING_MODEL_ENV];
2213
- }
2214
- return dropped.length === 0 ? undefined : `Chosen this session, and given way to the config: ${dropped.join("; ")}.`;
2215
- },
2216
- parallelJobs: (count) => {
2217
- const limit = count ?? parallelJobs(cwd);
2218
- jobs.setMaxRunning(limit);
2219
- return `Up to ${limit} pulse${limit === 1 ? "" : "s"} run at once now.`;
2220
- },
2221
- },
2222
- });
2223
- }
2224
- export { fromWorkingDir };
2225
- const WATCH_REDRAW_MS = 500;
2226
- /**
2227
- * What a chat's agent is told of a pulse it asked for that ended, with the sentinel off. One that landed under
2228
- * launch-after-pulse is being launched as it is told: it says so, and offers nothing else for it - it is told once the
2229
- * launch ends.
2230
- */
2231
- export function pulseEndNote(job, options = {}) {
2232
- const head = job.status === "succeeded"
2233
- ? `Pulse ${job.id} (${job.kind}) finished after ${formatDuration(job)}.\n\n${job.report ?? ""}`
2234
- : job.status === "stopped"
2235
- ? `Pulse ${job.id} (${job.kind}) was stopped after ${formatDuration(job)}. ${job.error ?? STOPPED_ON_REQUEST}${job.error === undefined || job.error === STOPPED_ON_REQUEST ? " The person stopped it; what it was building counts as not built." : ""}`
2236
- : `Pulse ${job.id} (${job.kind}) failed after ${formatDuration(job)}.\n\n${job.error ?? ""}`;
2237
- const landed = job.status === "succeeded" && job.details?.landed === true;
2238
- if (!landed || options.launching !== true)
2239
- return `${head}\n\n${JOB_FINISHED_REACTION}`;
2240
- return [
2241
- head,
2242
- "",
2243
- "It landed, and turri is launching the commit it landed now, in the background (launch-after-pulse): you are told once",
2244
- "that launch ends - where it runs, or why it did not come up. React to this now - the person has not asked, and need",
2245
- "not: say in a line or two what landed and that it is being launched. Offer nothing else for it - do not call launch,",
2246
- "open it, run it or test it, and never say nothing runs - and start no other work, unless guidance for this project",
2247
- "(its AGENTS.md, a skill, what the person said) says to do something besides launching it when a pulse finishes: do",
2248
- "that. When you are told it is launched, do what you were told to do once something is launched.",
2249
- ].join("\n");
2250
- }
2251
- /**
2252
- * What the agent is to do with a job that just ended, unasked: what the project's guidance says to do then, or else say
2253
- * in a line or two what ended - the person saw it end already, in the transcript.
2254
- */
2255
- export const JOB_FINISHED_REACTION = [
2256
- "React to this now - the person has not asked, and need not. If guidance for this project - its AGENTS.md, a skill,",
2257
- "what the person said earlier - says what to do when a pulse finishes (launch what was built, run something, tell",
2258
- "someone), do that, as it says. Otherwise say in a line or two what finished and what it means for the person - the",
2259
- "report is theirs to read in full; do not repeat it - and, when it failed, what they can do. Start no other work.",
2260
- "Under launch-after-pulse turri launches what a pulse lands itself, in the background: do not call launch for it - you",
2261
- "are told once it is launched, and do then what you were told to do once something is launched.",
2262
- "A pulse that stopped on its environment - \"stopped: turri's sandbox kept its agents from…\" or \"stopped: the",
2263
- "environment lacks…\" - stops the same way again until that is fixed: never regenerate it before. Heal it, then regenerate the",
2264
- "module to resume:",
2265
- "- turri's sandbox kept the agents from reading a folder on this machine: nothing is missing. Add the folder its report",
2266
- " names to `toolchains:` in config.turri.yaml - a list, keeping what is there - say so in a line, and resume.",
2267
- "- turri's sandbox kept the agents from writing a file - a lock a build tool takes, say: no setting lets them, and",
2268
- " `toolchains:` does not - never add it there, and never resume before the fix. Do what the report says if it is the",
2269
- " project's to change - a tool told to use `$HOME` in the build's own files - say so, and resume; otherwise tell the",
2270
- " person, in a line or two, what the report says and that \"resume\" picks it up once it is done.",
2271
- "- the machine lacks a toolchain or a tool - a JDK, Maven, Gradle, Go, uv, Node, a system library: you install nothing,",
2272
- " and change no setting of the machine's or the person's shell - never, even when asked: your shell refuses it. First",
2273
- " find out, in your shell, whether it is there after all: off the PATH (`command -v`, Homebrew's opt folders,",
2274
- " /Library/Java/JavaVirtualMachines, a version manager's folder - mise, asdf, sdkman, nvm), or under another name - python",
2275
- " where the testing script runs python3, of the version the ***plain names. When it is there, the testing script calling",
2276
- " it the way this machine has it is the fix: change the script, say so in a line, and resume. When it is not, tell the",
2277
- " person exactly what to run themselves - `brew install openjdk@21`, `mise use -g java@21` - and the line for their",
2278
- " shell profile when the PATH needs it, and that \"resume\" picks it up once it is in. A tool the person installs where the",
2279
- " PATH turri was started with does not reach needs turri restarted: say so.",
2280
- "- a credential `agent-env:` names that is not there: never make one up - tell the person where it is read from.",
2281
- ].join("\n");
2282
- const sidePanels = new WeakMap();
2283
- /** The side panel of the session these jobs are, made as a chat first asks for it. */
2284
- function sidePanelOf(jobs, cwd) {
2285
- const known = sidePanels.get(jobs);
2286
- if (known !== undefined)
2287
- return known;
2288
- const self = {
2289
- open: (ctx, view) => openPanel(ctx, view),
2290
- shown: () => panel !== undefined && panel.keys,
2291
- };
2292
- sidePanels.set(jobs, self);
2293
- let panel;
2294
- // Beside the chat or over it: as the person last left it, for the conversation.
2295
- let panelDocked = false;
2296
- // The terminal the panel is drawn on, for its width: set as it opens.
2297
- let panelTerminal;
2298
- /** The columns the panel takes beside the chat - 0 over the whole screen, or when the terminal is too narrow to share. */
2299
- const panelBeside = () => (panelDocked && panelTerminal !== undefined ? dockedWidth(paddedColumns(panelTerminal.columns)) : 0);
2300
- // What is open in the pulse list and the map, and where their cursors are: the conversation's, as left each time it opens.
2301
- const jobsTree = createJobsTreeState();
2302
- // Earlier sessions' pulses, from the ledger: read as the panel first shows them - they do not change while this one runs.
2303
- let earlier;
2304
- const earlierJobs = () => {
2305
- if (earlier !== undefined)
2306
- return earlier;
2307
- try {
2308
- const found = earlierPulses(ledgerProjects(cwd), new Set(jobs.list().map((job) => job.id)));
2309
- earlier = found.jobs;
2310
- jobsTree.earlierMore = found.more;
2311
- }
2312
- catch {
2313
- earlier = [];
2314
- }
2315
- return earlier;
2316
- };
2317
- const mapState = createSpecMapState();
2318
- // The map from the files - the .plain files asked for, else the project's - with the work loop's plan laid over them.
2319
- const specMap = createSpecMapSource({
2320
- files: () => {
2321
- const asked = workLoops.get(jobs)?.loop.mapPlan().files ?? [];
2322
- return asked.length > 0 ? asked : defaultMapFiles(cwd);
2323
- },
2324
- plan: () => workLoops.get(jobs)?.loop.mapPlan() ?? { files: [], codebases: [] },
2325
- });
2326
- /** Open the side panel - on the view named, or as it was left. */
2327
- const openPanel = (ctx, view) => {
2328
- // Found: ctrl+h under the job panel stops breathing.
2329
- keyPressed("peek");
2330
- if (view !== undefined)
2331
- mapState.view = view;
2332
- // A pulse that failed or stopped since the panel was last opened: opened as it is, it is on that pulse - what went
2333
- // wrong is what the person opens it to see.
2334
- else {
2335
- const id = needsLooking.get(jobs);
2336
- if (id !== undefined && selectJob(shownJobs(jobs), jobsTree, id))
2337
- mapState.view = "pulses";
2338
- }
2339
- needsLooking.delete(jobs);
2340
- if (panel !== undefined) {
2341
- panel.keepChatFocus();
2342
- panel.handle?.setHidden(false);
2343
- panel.keys = true;
2344
- panel.handle?.focus();
2345
- return;
2346
- }
2347
- // Not awaited: the panel lives on while the jobs it shows run.
2348
- void ctx.ui.custom((tui, theme, _keybindings, done) => {
2349
- // What the chat shows when the panel takes the keys - its editor, or a pi dialog - for when it gives them back.
2350
- const focusedNow = () => tui.getFocusedComponent?.() ?? null;
2351
- let chatFocus = focusedNow();
2352
- const keepChatFocus = () => {
2353
- const focused = focusedNow();
2354
- if (focused !== null && focused !== component && !(focused instanceof QuestionDialog))
2355
- chatFocus = focused;
2356
- };
2357
- // The keys back to the chat: to the question open there now, else to what it showed - never to a question answered
2358
- // while the panel was open.
2359
- const giveBack = () => entry.handle?.unfocus({ target: questionShown ?? chatFocus });
2360
- const close = () => {
2361
- giveBack();
2362
- done(undefined);
2363
- };
2364
- panelTerminal = tui.terminal;
2365
- let component;
2366
- // Beside the chat: the chat drawn narrower, on the left, and a click on either side giving it the keys - undone
2367
- // when the panel goes over the screen, or closes.
2368
- let undock;
2369
- const layOut = () => {
2370
- if (panelDocked && undock === undefined) {
2371
- const widen = narrowChat(tui, panelBeside);
2372
- const unwatch = clickToFocus(tui, () => tui.terminal.columns - SCREEN_PADDING.right - panelBeside(), (side) => {
2373
- if (panelBeside() === 0)
2374
- return;
2375
- if (side === "chat")
2376
- toChat();
2377
- else
2378
- toPanel();
2379
- });
2380
- // The side without the keys in the shade: the chat while the panel has them.
2381
- const unshade = shadeChat(tui, () => panelBeside() > 0 && entry.keys);
2382
- undock = () => {
2383
- unshade();
2384
- unwatch();
2385
- widen();
2386
- };
2387
- }
2388
- else if (!panelDocked && undock !== undefined) {
2389
- undock();
2390
- undock = undefined;
2391
- }
2392
- };
2393
- // Beside the chat, back to it: the chat has the keys, the panel stays.
2394
- const toChat = () => {
2395
- entry.keys = false;
2396
- giveBack();
2397
- tui.requestRender();
2398
- };
2399
- const toPanel = () => {
2400
- keepChatFocus();
2401
- entry.keys = true;
2402
- entry.handle?.focus();
2403
- tui.requestRender();
2404
- };
2405
- const back = () => (panelBeside() > 0 ? toChat() : close());
2406
- // Opened, it reads the files again at once: they may have changed while it was closed.
2407
- specMap.refresh();
2408
- const view = createSidePanel({
2409
- jobs: () => shownJobs(jobs),
2410
- earlier: earlierJobs,
2411
- tree: jobsTree,
2412
- map: () => specMap.read(),
2413
- mapState,
2414
- rows: () => paddedRows(tui.terminal.rows),
2415
- key: PANEL_KEY,
2416
- dock: {
2417
- docked: () => panelBeside() > 0,
2418
- toggle: () => {
2419
- panelDocked = panelBeside() === 0;
2420
- layOut();
2421
- tui.requestRender();
2422
- },
2423
- },
2424
- style: {
2425
- heading: (text) => theme.bold(theme.fg("accent", text)),
2426
- muted: (text) => theme.fg("muted", text),
2427
- accent: (text) => theme.fg("accent", text),
2428
- error: (text) => theme.fg("error", text),
2429
- success: (text) => theme.fg("success", text),
2430
- warning: (text) => theme.fg("warning", text),
2431
- added: (text) => theme.fg("toolDiffAdded", text),
2432
- removed: (text) => theme.fg("toolDiffRemoved", text),
2433
- // A spec diff's ***plain highlighted by turri's grammar, and its added and removed lines filled.
2434
- diff: plainPaint(theme),
2435
- // What conformance tests show does what its spec says: neon.
2436
- conforms: brandNeon(theme),
2437
- },
2438
- back,
2439
- close,
2440
- // A module that needs the person: the chat takes it up with them, in their words - what went wrong, and what now.
2441
- discuss: (page) => {
2442
- back();
2443
- const why = page.codebase?.stuck?.why;
2444
- self.say?.(`regen says ${page.module} needs me: ${page.status}. What went wrong, and what do we do about it?${why !== undefined ? `\n\n(turri's reason: ${why})` : ""}`);
2445
- },
2446
- // Something took the keys' focus while the panel showed - a question in the chat - and waits there.
2447
- waiting: () => {
2448
- if (!entry.keys)
2449
- return false;
2450
- const focused = tui.getFocusedComponent?.() ?? null;
2451
- return focused !== null && focused !== component;
2452
- },
2453
- });
2454
- const entry = { view, close, keepChatFocus, keys: true };
2455
- panel = entry;
2456
- layOut();
2457
- // Every key goes to the panel while it shows, whatever has the focus: a question the chat model asks in the
2458
- // background takes the focus, but no key reaches it - an enter never answers it unseen. It waits in the chat
2459
- // until the panel closes, and has the keys then. Mouse events are the screen's, before this sees them.
2460
- // Only while it is on the screen: up in the TUI's overlays and not hidden. An overlay taken off without the panel
2461
- // being disposed - another one closed over it - leaves no panel to take keys for: it lets them go, and goes.
2462
- const shown = () => {
2463
- const overlays = tui.overlayStack;
2464
- if (entry.handle === undefined || component === undefined)
2465
- return false;
2466
- if (overlays !== undefined && !overlays.some((overlay) => overlay.component === component))
2467
- return "gone";
2468
- return entry.handle.isHidden() !== true;
2469
- };
2470
- const unlisten = tui.addInputListener((data) => {
2471
- const state = shown();
2472
- if (state === "gone") {
2473
- component?.dispose?.();
2474
- return undefined;
2475
- }
2476
- if (!state)
2477
- return undefined;
2478
- // Beside the chat, with the chat's keys: they are the chat's - PANEL_KEY among them, for the shortcut that gives
2479
- // them to the panel. A click on the panel gives it the focus, and the keys with it.
2480
- if (!entry.keys && entry.handle?.isFocused() !== true)
2481
- return undefined;
2482
- entry.keys = true;
2483
- // A terminal on the Kitty keyboard protocol reports a key's release, and listeners are given it: the release of
2484
- // the ctrl+h that opened the panel would close it again at once, and every arrow would move twice. Only
2485
- // presses count - and ctrl+h held down, repeating, does not open and close it over and over.
2486
- if (isKeyRelease(data) || (isKeyRepeat(data) && matchesKey(data, PANEL_KEY)))
2487
- return { consume: true };
2488
- // PANEL_KEY goes back: beside the chat, to the chat, the panel staying - the switch between the sides, as it is
2489
- // from the chat to the panel - and over the screen, closing it. ctrl+c closes it either way: whatever else goes
2490
- // wrong, a key always leads back to the chat.
2491
- if (matchesKey(data, "ctrl+c"))
2492
- close();
2493
- else if (matchesKey(data, PANEL_KEY))
2494
- back();
2495
- else {
2496
- try {
2497
- view.handleInput(data);
2498
- }
2499
- catch {
2500
- /* a key the panel fails on is dropped, never the panel's hold on the keys */
2501
- }
2502
- }
2503
- tui.requestRender();
2504
- return { consume: true };
2505
- });
2506
- // Jobs keep writing; redraw so the panel follows them while it shows.
2507
- const timer = setInterval(() => {
2508
- if (entry.handle?.isHidden() !== true)
2509
- tui.requestRender();
2510
- }, WATCH_REDRAW_MS);
2511
- timer.unref?.();
2512
- component = {
2513
- // Beside the chat, a rule down its left edge between them - and the panel in the shade while the chat has the keys.
2514
- render: (width) => {
2515
- if (panelBeside() === 0)
2516
- return view.render(width);
2517
- const lines = view.render(width - 2).map((line) => `${theme.fg("borderMuted", "│")} ${line}`);
2518
- return entry.keys ? lines : lines.map(shade);
2519
- },
2520
- // Reached only if the listener above is gone: the same, so the panel never passes a key on.
2521
- handleInput: (data) => {
2522
- if (isKeyRepeat(data) && matchesKey(data, PANEL_KEY))
2523
- return;
2524
- if (matchesKey(data, "ctrl+c"))
2525
- close();
2526
- else if (matchesKey(data, PANEL_KEY))
2527
- back();
2528
- else
2529
- view.handleInput(data);
2530
- tui.requestRender();
2531
- },
2532
- handleMouse: (event) => view.handleMouse(event),
2533
- invalidate: () => view.invalidate(),
2534
- dispose: () => {
2535
- unlisten();
2536
- clearInterval(timer);
2537
- undock?.();
2538
- if (panel === entry)
2539
- panel = undefined;
2540
- },
2541
- };
2542
- return component;
2543
- }, {
2544
- overlay: true,
2545
- // The whole screen, or the columns on the right beside the chat - read at each frame, so it follows the terminal -
2546
- // inside the screen's padding.
2547
- overlayOptions: {
2548
- get width() {
2549
- return panelBeside() > 0 ? panelBeside() : "100%";
2550
- },
2551
- maxHeight: "100%",
2552
- anchor: "top-right",
2553
- margin: { ...SCREEN_PADDING },
2554
- },
2555
- onHandle: (handle) => {
2556
- if (panel !== undefined)
2557
- panel.handle = handle;
2558
- },
2559
- });
2560
- };
2561
- return self;
2562
- }
2563
- /** Opens the side panel, and goes back to it from the conversation. */
2564
- /** The modules in this project that have a history, by name. */
2565
- function modulesWithHistory(cwd) {
2566
- const root = join(cwd, "plain_modules");
2567
- try {
2568
- return readdirSync(root).filter((name) => existsSync(join(root, name, HISTORY_DIR)));
2569
- }
2570
- catch {
2571
- return [];
2572
- }
2573
- }
2574
- /** Stop a job by id or id prefix, and say what that means for the queue. */
2575
- /** Every job, in the order it was started, with what a queued one is waiting for. */
2576
- /** What a launch started, as /halt offers it. */
2577
- function launchedLabel(name, what) {
2578
- return `launched ${name} running ${what}`;
2579
- }
2580
- /** The jobs as the person is shown them: those started, and those the work loop has planned after them. */
2581
- function shownJobs(jobs) {
2582
- return [...(workLoops.get(jobs)?.loop.planned() ?? []), ...jobs.list()];
2583
- }
2584
- function listJobs(jobs, cwd, runs = EARLIER_RUNS) {
2585
- const all = [...shownJobs(jobs)].reverse().filter((job) => job.replacedBy === undefined);
2586
- const servers = runningLaunched().map((item) => `launched ${item.name} running ${item.moduleName}: ${item.url ?? item.command} (pid ${item.pid}, output in ${relative(process.cwd(), item.log) || item.log})`);
2587
- const launches = (sessionLaunches.get(jobs)?.track.list() ?? []).slice(-10).reverse().map(describeLaunchLine);
2588
- const listed = (launches.length > 0 ? `\n\nLaunches, newest first - /halt launched <module> halts one under way:\n${launches.join("\n")}` : "") +
2589
- (servers.length > 0 ? `\n\nWhat launches started - /halt launched <name> halts one:\n${servers.join("\n")}` : "");
2590
- const before = earlierRuns(jobs, cwd, runs);
2591
- if (all.length === 0)
2592
- return `No pulses have been started in this session.${listed}${before}`;
2593
- return `${jobLines(all)}${listed}${before}`;
2594
- }
2595
- /** How many runs of earlier sessions `pulses` lists when it is asked for none. */
2596
- const EARLIER_RUNS = 3;
2597
- /** Earlier sessions' last runs and their pulses, from the ledger - nothing when it has none. */
2598
- function earlierRuns(jobs, cwd, runs) {
2599
- try {
2600
- const found = earlierPulses(ledgerProjects(cwd), new Set(jobs.list().map((job) => job.id)), runs);
2601
- if (found.runs.length === 0)
2602
- return "";
2603
- const more = found.more > 0 ? `\n\n${found.more} earlier run${found.more === 1 ? "" : "s"} beyond these: ask with runs for more.` : "";
2604
- return `\n\nEarlier sessions, from the ledger - pulses with a pulse's id tells one:\n${describeRuns(found.runs)}${more}`;
2605
- }
2606
- catch {
2607
- return "";
2608
- }
2609
- }
2610
- /** A look ahead, for the chat: what is planned in each codebase, each row by its id, and what happens next. */
2611
- function describeLookAhead(loop, statuses) {
2612
- const modules = new Set(statuses.map((status) => status.module));
2613
- const rows = loop.planned().filter((row) => row.module !== undefined && modules.has(row.module));
2614
- const listed = rows.length > 0 ? `\n\nThe planned pulses - pulses with a row's id tells its cases and, for the next pulse of a codebase, the whole prompt its coding agent will get:\n${rows.map((row) => `${row.id} ${row.summary}`).join("\n")}` : "";
2615
- return (`${describeModules(statuses)}${listed}\n\n` +
2616
- "Nothing was started. What is planned here waits for regenerate, conform or /regenerate, which runs this plan as it is - unless " +
2617
- "the ***plain changes first, when it is planned again. To change the plan, change the ***plain, then " +
2618
- "look again. Tell the user what will run and in what order - the parts they are likely to care about.");
2619
- }
2620
- /** A planned row, for the chat: what it is, and its prompt when it is the next pulse of its codebase. */
2621
- function describePlannedRow(row, pulse) {
2622
- const head = `${row.id} · ${pulseName(row)}: ${row.note ?? "planned, not started"}${row.waitingOn.length > 0 ? ` It runs after ${row.waitingOn.join(", ")}.` : ""}`;
2623
- if (pulse?.task !== undefined) {
2624
- return (`${head}\n\nThe whole prompt its coding agent will get - built from the plan kept, the one regenerate runs:\n<prompt>\n${pulse.task}\n</prompt>\n\n` +
2625
- "Tell the user what the pulse is and what it will be told - the parts they are likely to care about, not the whole prompt unless they ask.");
2626
- }
2627
- return pulse?.why !== undefined ? `${head}\n\nNo prompt shown: ${pulse.why}` : head;
2628
- }
2629
- function jobLines(all) {
2630
- return all
2631
- .map((job) => {
2632
- // Planned by the work loop, not started: it has no job of the registry's yet.
2633
- const planned = job.id.startsWith("planned-");
2634
- const time = job.status === "queued" ? "waiting" : formatDuration(job);
2635
- const after = job.status === "queued" && job.waitingOn.length > 0 ? ` (after ${job.waitingOn.join(", ")})` : "";
2636
- const spent = describeUsage(job.usage);
2637
- const model = job.model ? ` · ${job.model}` : "";
2638
- const held = job.lookedAhead === true ? " · looked ahead: waits for regenerate" : "";
2639
- return `${job.id} ${(planned ? "planned" : job.status).padEnd(9)} ${time.padStart(7)} ${pulseName(job)}${model}${after}${held}${spent ? ` · ${spent}` : ""}`;
2640
- })
2641
- .join("\n");
2642
- }
2643
- /**
2644
- * The ***plain parsed - its syntax and structure - regenerating nothing.
2645
- *
2646
- * This is the check that used to mean a renderer dry-run. It runs this repo's own parser,
2647
- * so it needs no external tool, no API key and no credits - and it is the only honest way
2648
- * to answer "is this spec valid?" without generating anything.
2649
- */
2650
- function registerCheckPlain(pi, cwd, dialogs, afterAnswer) {
2651
- pi.registerTool(checkPlainTool(cwd));
2652
- pi.registerTool(chatAskUserTool(dialogs, afterAnswer));
2653
- // The web, for the conversation too - a library's documentation, an API, an error; curl is its
2654
- // bash. Run here, like the rendering agents' (see render/web.ts).
2655
- for (const tool of createWebTools())
2656
- pi.registerTool(tool);
2657
- }
2658
- const SIDE_ENTRY = "turri_btw";
2659
- /** A message the person sent while a skill ran in the chat, read by the skill's agent: drawn as the message it is. */
2660
- const SKILL_MESSAGE_ENTRY = "turri_skill_message";
2661
- /**
2662
- * /btw, a question on the side (btw.ts): answered at once, even while a skill runs - pi runs a command mid-turn - and
2663
- * shown in the transcript, never in a model's context.
2664
- */
2665
- function registerSideQuestions(pi, cwd, jobs) {
2666
- pi.registerCommand("btw", {
2667
- description: "Ask turri something on the side - answered now, even mid-skill, and left out of the conversation: /btw <question>",
2668
- handler: async (args, ctx) => {
2669
- const question = args.trim();
2670
- if (question === "")
2671
- return ctx.ui.notify(BTW_HOW, "info");
2672
- ctx.ui.notify(`Looking into it: ${question}`, "info");
2673
- // Not awaited: the editor is free while it is answered, for another /btw or the conversation.
2674
- void askOnTheSide(pi, ctx, cwd, jobs, question).catch((error) => ctx.ui.notify(`The side question could not be answered: ${error instanceof Error ? error.message : String(error)}`, "error"));
2675
- },
2676
- });
2677
- pi.registerEntryRenderer(COMMAND_OUTCOME, (entry, _options, theme) => {
2678
- const data = entry.data;
2679
- if (data === undefined)
2680
- return undefined;
2681
- const box = new Box(1, 0);
2682
- // The command as typed; what it said, under it - or, said without it above, with it.
2683
- const said = data.text !== undefined ? theme.fg(data.level === undefined || data.level === "info" ? "text" : data.level, data.text) : undefined;
2684
- const lines = data.text === undefined ? [theme.bold(theme.fg("accent", data.command))] : data.echoed === true ? [said] : [theme.fg("muted", data.command), said];
2685
- box.addChild(new Text(lines.join("\n"), 0, 0));
2686
- return box;
2687
- });
2688
- pi.registerEntryRenderer(SKILL_MESSAGE_ENTRY, (entry) => {
2689
- const data = entry.data;
2690
- if (data === undefined)
2691
- return undefined;
2692
- return new UserMessageComponent(data.text, getMarkdownTheme());
2693
- });
2694
- pi.registerEntryRenderer(SIDE_ENTRY, (entry, _options, theme) => {
2695
- const data = entry.data;
2696
- if (data === undefined)
2697
- return undefined;
2698
- const box = new Box(1, 0);
2699
- box.addChild(new Text([theme.fg("muted", `btw: ${data.question}`), theme.fg("text", data.answer)].join("\n"), 0, 0));
2700
- return box;
2701
- });
2702
- }
2703
- /** A side question answered - from the conversation, the skill running, the pulses - and kept in the transcript. */
2704
- async function askOnTheSide(pi, ctx, cwd, jobs, question) {
2705
- let entries = [];
2706
- try {
2707
- entries = ctx.sessionManager.getEntries();
2708
- }
2709
- catch {
2710
- // Without the conversation it is still answered, from the skill and the project.
2711
- }
2712
- const skill = runningSkill();
2713
- const answer = await answerSideQuestion({
2714
- question,
2715
- conversation: transcriptOf(entries, 24_000),
2716
- ...(skill !== undefined ? { skill: { name: skill.skill, dir: skill.dir, step: skill.step(), trace: skill.trace(), session: skillSessionText(skill.runDir) } } : {}),
2717
- pulses: jobs.list().map((job) => `${job.id} ${job.status}: ${pulseName(job)}`),
2718
- projectDir: cwd,
2719
- harnessDir: PACKAGE_ROOT,
2720
- ...(surfaceOf(jobs) !== undefined ? { surface: surfaceOf(jobs) } : {}),
2721
- }, chatModelOf(ctx));
2722
- try {
2723
- pi.appendEntry(SIDE_ENTRY, { question, answer });
2724
- }
2725
- catch {
2726
- // Shown where it was asked all the same.
2727
- }
2728
- return answer;
2729
- }
2730
- /** A launch ended, told to a chat's agent - to tell the person where it runs, or why it did not come up. */
2731
- function tellLaunch(pi, jobs, launch) {
2732
- const job = "pulse" in launch.cause ? jobs.get(launch.cause.pulse) : undefined;
2733
- void pi.sendMessage({ customType: "turri_launch", content: launchedNote(launch, job), display: false, details: { launch: launch.id, status: launch.status } }, { triggerTurn: true, deliverAs: "followUp" });
2734
- }
2735
- /** A newer launch took the place of one a chat asked for, told to its agent: it hears that one's end instead. */
2736
- function tellReplaced(pi, jobs, launch, next) {
2737
- const job = "pulse" in next.cause ? jobs.get(next.cause.pulse) : undefined;
2738
- void pi.sendMessage({ customType: "turri_launch", content: replacedNote(launch, next, job), display: false, details: { launch: launch.id, status: launch.status, replacedBy: next.id } }, { triggerTurn: true, deliverAs: "followUp" });
2739
- }
2740
- function registerLaunch(pi, cwd, jobs) {
2741
- const launches = sessionLaunches.get(jobs);
2742
- if (launches !== undefined) {
2743
- pi.registerTool(launchTool({
2744
- cwd,
2745
- track: launches.track,
2746
- defaultPlainFile: () => readProjectConfig(cwd).module,
2747
- chat: () => currentChat()?.id,
2748
- // Told in the chat that asked, as a launch after a pulse is with the sentinel off.
2749
- ended: (launch) => tellLaunch(pi, jobs, launch),
2750
- replaced: (launch, next) => tellReplaced(pi, jobs, launch, next),
2751
- wait: (ctx) => shouldWait(ctx.mode, undefined),
2752
- }));
2753
- }
2754
- pi.registerTool(haltTool({ jobs, workLoop: () => workLoops.get(jobs)?.loop, ...(launches !== undefined ? { launches: launches.track } : {}) }));
2755
- // What launches started runs until turri ends - not when a chat is opened, closed, forked or reloaded.
2756
- pi.on("session_shutdown", async (event) => {
2757
- if (event.reason !== "quit")
2758
- return;
2759
- await launches?.track.stop();
2760
- await stopLaunched();
2761
- });
2762
- }
2763
- const MILESTONE_ENTRY = "turri_milestone";
2764
- /** A newer turri out, found once turri had started (turri-versions.ts). */
2765
- const VERSION_ENTRY = "turri_version";
2766
- const JOB_ENTRY = "turri_job";
2767
- const JOBS_LIST_ENTRY = "turri_jobs";
2768
- const HISTORY_ENTRY = "turri_history";
2769
- function announceJob(pi, job) {
2770
- if (job.status !== "succeeded" && job.status !== "failed" && job.status !== "stopped")
2771
- return;
2772
- const announcement = {
2773
- id: job.id,
2774
- // Its module, kind and number - never what it regenerates, which is the agents' words and long.
2775
- summary: pulseName(job),
2776
- status: job.status,
2777
- incomplete: job.status === "succeeded" && job.details?.passed === false,
2778
- duration: formatDuration(job),
2779
- spent: describeUsage(job.usage) || undefined,
2780
- text: job.specConflict !== undefined
2781
- ? describeSpecConflict(job.specConflict)
2782
- : job.status === "succeeded"
2783
- ? (job.announce ?? job.report ?? "")
2784
- : job.status === "stopped"
2785
- ? (job.note ?? "Stopped on request. Whatever it changed before it stopped is still on disk; the functionality it was on counts as not built.")
2786
- : (job.error ?? "no error recorded"),
2787
- };
2788
- try {
2789
- pi.appendEntry(JOB_ENTRY, announcement);
2790
- }
2791
- catch {
2792
- // The agent still gets the report; losing the entry must not lose the result.
2793
- }
2794
- }
2795
- /**
2796
- * What the conversation's agent is asked to do about a spec that contradicts itself: confirm it
2797
- * with analyze-2-func-specs, work out the ways out with resolve-spec-conflict, and put the choice
2798
- * to the person - who decides. Nothing in the spec is changed before they have.
2799
- */
2800
- function specConflictTask(conflict) {
2801
- const [one, two] = conflict.specs;
2802
- return [
2803
- describeSpecConflict(conflict),
2804
- "",
2805
- `The render stopped on it: the conformance run's judge found them conflicting, ${conflict.reasons.length} times -`,
2806
- `functional spec ${one.module}:${one.funcId} (${one.plainFile}) and functional spec ${two.module}:${two.funcId} (${two.plainFile}). Now:`,
2807
- "1. Run the analyze-2-func-specs skill (cultivate) on these two functional specs, to confirm they conflict.",
2808
- "2. If they do, run the resolve-spec-conflict skill on the pair, to work out what could be changed - but change nothing yet.",
2809
- "3. Tell the user exactly what the conflict is - both specs as they read, and the behaviour that cannot satisfy both -",
2810
- " and put the decision to them with ask_user: the ways out resolve-spec-conflict found, and Something else. Suggest they",
2811
- " simply decide which is meant; it is their call, not yours.",
2812
- "4. Only once they have decided, make the change they chose to the .plain file it belongs in - either module's -",
2813
- " and regenerate it - its conformance tests follow it.",
2814
- "If analyze-2-func-specs finds the two compatible, tell the user so, and that the conformance tests of these two are what",
2815
- "kept failing - offer to conform them again.",
2816
- ].join("\n");
2817
- }
2818
- const INTERVIEW_ENTRY = "turri_exchange";
2819
- /**
2820
- * A skill's question as the transcript keeps it: who asked, what it said before asking - a brief to confirm, the choices
2821
- * it weighed, shown in the dialog that is gone once answered - the question, and the answer.
2822
- */
2823
- export function exchangeLines(data, fg) {
2824
- const said = data.said !== undefined ? data.said.split("\n").map((line) => fg("text", line)) : [];
2825
- const answer = data.answer.trim() === "" ? fg("dim", "> (no answer)") : fg("accent", `> ${data.answer}`);
2826
- return [fg("muted", `${data.skill} asked`), ...said, ...(said.length > 0 ? [""] : []), fg("text", data.question), answer];
2827
- }
2828
- /**
2829
- * Show each question and answer in the transcript, where the person can see it.
2830
- *
2831
- * A skill runs inside one tool call and asks through dialogs, so its interview leaves no
2832
- * trace in the conversation - the questions vanish once answered. These are custom
2833
- * *entries* rather than messages on purpose: they are durable and rendered, but they do
2834
- * not enter the model's context, so a long interview is readable without being paid for
2835
- * twice.
2836
- */
2837
- function registerInterviewLog(pi) {
2838
- pi.registerEntryRenderer(JOB_ENTRY, (entry, _options, theme) => {
2839
- const data = entry.data;
2840
- if (data === undefined)
2841
- return undefined;
2842
- // A job that ran to its end but whose build did not pass is not a success: it says so.
2843
- const header = data.status === "succeeded" && data.incomplete === true
2844
- ? `${theme.fg("error", "✗")} ${theme.fg("text", data.summary)} ${theme.fg("error", `did not pass - stopped after ${data.duration}`)}`
2845
- : data.status === "succeeded"
2846
- ? `${theme.fg("success", "✓")} ${theme.fg("text", data.summary)} ${theme.fg("muted", `finished after ${data.duration}`)}`
2847
- : data.status === "stopped"
2848
- ? `${theme.fg("warning", "■")} ${theme.fg("text", data.summary)} ${theme.fg("warning", `stopped after ${data.duration}`)}`
2849
- : `${theme.fg("error", "✗")} ${theme.fg("text", data.summary)} ${theme.fg("error", `failed after ${data.duration}`)}`;
2850
- const spent = data.spent ? ` ${theme.fg("muted", `· ${data.spent}`)}` : "";
2851
- // Its headline only: the chat has the whole report, and says what it means - or does what the project says to. One
2852
- // that went wrong says where to see why: the live panel, which said it, is gone with the last pulse.
2853
- const wrong = data.status !== "succeeded" || data.incomplete === true;
2854
- const box = new Box(1, 0);
2855
- box.addChild(new Text(header + spent + (wrong ? `\n${theme.fg("muted", ` ${PANEL_KEY} shows this pulse - its stages, what its agents did, its log`)}` : ""), 0, 0));
2856
- return box;
2857
- });
2858
- pi.registerEntryRenderer(HISTORY_ENTRY, (entry, _options, theme) => {
2859
- const data = entry.data;
2860
- if (data === undefined)
2861
- return undefined;
2862
- const box = new Box(1, 0);
2863
- box.addChild(new Text([theme.fg("muted", `history of ${data.module}`), theme.fg("text", data.text)].join("\n"), 0, 0));
2864
- return box;
2865
- });
2866
- pi.registerEntryRenderer(JOBS_LIST_ENTRY, (entry, _options, theme) => {
2867
- const data = entry.data;
2868
- if (data === undefined)
2869
- return undefined;
2870
- const box = new Box(1, 0);
2871
- box.addChild(new Text([theme.fg("muted", "pulses"), theme.fg("text", data.text)].join("\n"), 0, 0));
2872
- return box;
2873
- });
2874
- pi.registerEntryRenderer(MILESTONE_ENTRY, (entry, _options, theme) => {
2875
- const data = entry.data;
2876
- if (data === undefined)
2877
- return undefined;
2878
- const box = new Box(1, 0);
2879
- box.addChild(new Text(`${theme.fg("success", "●")} ${theme.fg("muted", data.module)} ${theme.fg("text", data.text)}`, 0, 0));
2880
- return box;
2881
- });
2882
- pi.registerEntryRenderer(INTERVIEW_ENTRY, (entry, _options, theme) => {
2883
- const data = entry.data;
2884
- if (data === undefined)
2885
- return undefined;
2886
- // Two details of the TUI components matter here. Box's third argument is a
2887
- // *background* function - passing a foreground colour into it tints every line, which
2888
- // is what made these unreadable. And Text pads by 1 on both axes unless told
2889
- // otherwise, so one Text per line puts a blank line between each. Hence a single Text
2890
- // with explicit zero padding, coloured per line.
2891
- const box = new Box(1, 0);
2892
- box.addChild(new Text(exchangeLines(data, (color, text) => theme.fg(color, text)).join("\n"), 0, 0));
2893
- return box;
2894
- });
2895
- }
2896
- function recordExchange(pi, exchange) {
2897
- try {
2898
- pi.appendEntry(INTERVIEW_ENTRY, exchange);
2899
- }
2900
- catch {
2901
- // The trace still carries it; a rendering failure must not lose the answer.
2902
- }
2903
- }
2904
- /**
2905
- * What the skill should be told about the conversation that started it.
2906
- *
2907
- * The agent's own summary comes first, because it knows which parts matter. The user's
2908
- * recent messages are appended verbatim underneath: a summary drops the particulars - a
2909
- * product name, a phrasing the user chose - and those are exactly what makes a skill's
2910
- * first question sound like it was listening.
2911
- */
2912
- function conversationContext(ctx, summary) {
2913
- const spoken = recentUserMessages(ctx, 12);
2914
- const parts = [];
2915
- if (summary !== undefined && summary.trim() !== "")
2916
- parts.push(summary.trim());
2917
- if (spoken.length > 0) {
2918
- parts.push(`In their own words:\n${spoken.map((line) => `- ${line}`).join("\n")}`);
2919
- }
2920
- return parts.length > 0 ? parts.join("\n\n") : undefined;
2921
- }
2922
- function recentUserMessages(ctx, limit) {
2923
- let entries;
2924
- try {
2925
- entries = ctx.sessionManager.getEntries();
2926
- }
2927
- catch {
2928
- return [];
2929
- }
2930
- const said = [];
2931
- for (const entry of entries) {
2932
- const message = entry.message;
2933
- if (entry.type !== "message" || message?.role !== "user")
2934
- continue;
2935
- const text = typeof message.content === "string"
2936
- ? message.content
2937
- : Array.isArray(message.content)
2938
- ? message.content
2939
- .filter((part) => part.type === "text")
2940
- .map((part) => part.text ?? "")
2941
- .join(" ")
2942
- : "";
2943
- const trimmed = text.trim().replace(/\s+/g, " ");
2944
- if (trimmed !== "")
2945
- said.push(trimmed.length > 400 ? `${trimmed.slice(0, 400)}…` : trimmed);
2946
- }
2947
- return said.slice(-limit);
2948
- }
2949
- const BANNER_ENTRY = "turri_banner";
2950
- /**
2951
- * The name on the door.
2952
- *
2953
- * Pi's own startup header is a built-in component an extension cannot replace, so this
2954
- * adds a wordmark of its own at the top of the session. `turri` starts pi without
2955
- * its header (see pi-launch.ts), leaving only this one.
2956
- */
2957
- /**
2958
- * The ***plain rules as the conversation has them in its system prompt, every turn - the standard library's
2959
- * inventory among them, in its rule, so the conversation knows what a spec can import from the start.
2960
- */
2961
- export function chatRulesBlock(rules = loadRules(join(PACKAGE_ROOT, "genome", "rules"))) {
2962
- return renderRulesBlock(rules);
2963
- }
2964
- function registerBranding(pi, skills) {
2965
- pi.registerCommand("stdlib", {
2966
- description: "List the ***plain standard library: the stacks a spec can import instead of writing its implementation reqs.",
2967
- handler: async (_args, ctx) => {
2968
- if (ctx.hasUI)
2969
- ctx.ui.notify(describeStdlib(), "info");
2970
- },
2971
- });
2972
- pi.registerEntryRenderer(BANNER_ENTRY, (entry, _options, theme) => {
2973
- const data = entry.data;
2974
- if (data === undefined)
2975
- return undefined;
2976
- const lines = [
2977
- `${brandPink(theme)("turri")} ${theme.fg("muted", `v${data.version}`)}` +
2978
- (data.commit !== undefined ? theme.fg("dim", ` from a clone, ${data.commit}${data.changed ? " with changes" : ""}`) : ""),
2979
- // A newer turri out, or one installed and hidden behind this one: said first, under the version it is about.
2980
- ...(data.versions ?? []).map((line) => theme.fg("warning", line)),
2981
- // A key renamed is information; the rest are the person's to take out.
2982
- ...(data.config ?? []).map((line) => theme.fg(line.kind === "renamed" ? "muted" : "warning", line.text)),
2983
- `${theme.fg("text", "the first coding agent with the power of ")}${brandPink(theme)("regenerative software")}`,
2984
- // Where the settings are changed, without leaving the chat.
2985
- theme.fg("muted", "configure with /settings"),
2986
- // Only what is wrong: skills that did not load, and agents' commands less fenced than they should be.
2987
- ...(data.pending > 0 ? [theme.fg("warning", `${data.pending} skill${data.pending === 1 ? "" : "s"} failed to load`)] : []),
2988
- ...(data.sandbox !== undefined && data.sandbox.level !== "ok" ? [theme.fg(data.sandbox.level === "limited" ? "warning" : "error", data.sandbox.text)] : []),
2989
- ];
2990
- // The jellyfish turri is named after, regenerating, in ink for the theme's background: a picture
2991
- // where the terminal shows images, drawn in text where it does not.
2992
- return new Banner(lines, (rule) => theme.fg("borderMuted", rule), jellyfishArt(theme.appearance, (theme.getColorMode?.() ?? "truecolor") === "truecolor"));
2993
- });
2994
- // A newer turri, found once turri had started: a line, as the banner would have said it.
2995
- pi.registerEntryRenderer(VERSION_ENTRY, (entry, _options, theme) => {
2996
- const data = entry.data;
2997
- if (data === undefined)
2998
- return undefined;
2999
- const box = new Box(1, 0);
3000
- box.addChild(new Text(theme.fg("warning", data.text), 0, 0));
3001
- return box;
3002
- });
3003
- let bannered = false;
3004
- pi.on("session_start", (_event, ctx) => {
3005
- if (ctx.hasUI) {
3006
- padTheScreen(ctx);
3007
- animateJellyfish(ctx);
3008
- }
3009
- // Once a chat: it starts again each time it is shown.
3010
- if (bannered)
3011
- return;
3012
- bannered = true;
3013
- try {
3014
- const identity = turriIdentity();
3015
- const versions = bannerWarnings();
3016
- // A newer turri npm says is out only now - the banner read what it said last time: said under the banner once it does.
3017
- void versions.later.then((line) => {
3018
- if (line === undefined)
3019
- return;
3020
- try {
3021
- pi.appendEntry(VERSION_ENTRY, { text: line });
3022
- }
3023
- catch {
3024
- /* the chat let go meanwhile: the next start's banner says it */
3025
- }
3026
- });
3027
- pi.appendEntry(BANNER_ENTRY, {
3028
- version: identity.version ?? "0.0.0",
3029
- commit: identity.git_commit?.slice(0, 7),
3030
- changed: identity.git_dirty === true,
3031
- pending: skills.pending.length,
3032
- sandbox: sandboxSummary(),
3033
- versions: versions.lines,
3034
- config: configLines(ctx.cwd),
3035
- });
3036
- }
3037
- catch {
3038
- // Branding is the least important thing here; never let it stop a session starting.
3039
- }
3040
- });
3041
- }
3042
- /**
3043
- * How many rows the banner's picture takes at most: its frame reaches down to the sea floor the polyp stands on, so it
3044
- * is given more than the jellyfish drawn in text, ten.
3045
- */
3046
- const JELLYFISH_ROWS = 14;
3047
- /** How far along its sequence the jellyfish every banner shows is, moved on by `animateJellyfish`. */
3048
- let jellyfishFrame = 0;
3049
- /** The frame the jellyfish is on: the one its sequence has at this point. */
3050
- export const shownFrame = () => JELLYFISH_SEQUENCE[jellyfishFrame % JELLYFISH_SEQUENCE.length];
3051
- let jellyfishTimer;
3052
- /**
3053
- * Moves the jellyfish on a frame every JELLYFISH_FRAME_MS while the banner is on the screen. An entry's
3054
- * renderer is given no TUI to redraw, so an empty widget below the editor - which pi gives no
3055
- * spacer - hands it over. Once the conversation is taller than the screen the banner has scrolled off,
3056
- * and a line changing up there would have pi-tui clear and redraw everything, frame after frame: the
3057
- * jellyfish stops for the rest of the session - swimming, whole, drawn once more if it was not, rather than on whatever
3058
- * frame it was at, a polyp half grown.
3059
- */
3060
- export function animateJellyfish(ctx) {
3061
- if (jellyfishTimer !== undefined)
3062
- clearInterval(jellyfishTimer);
3063
- jellyfishTimer = undefined;
3064
- ctx.ui.setWidget(JELLYFISH_CLOCK_KEY, (tui) => {
3065
- drawOverlaysBesidePicture(tui);
3066
- const timer = setInterval(() => {
3067
- if (tui.render(tui.terminal.columns).length > tui.terminal.rows) {
3068
- clearInterval(timer);
3069
- if (shownFrame() !== JELLYFISH_SEQUENCE[JELLYFISH_REST]) {
3070
- jellyfishFrame = JELLYFISH_REST;
3071
- tui.requestRender();
3072
- }
3073
- return;
3074
- }
3075
- jellyfishFrame++;
3076
- tui.requestRender();
3077
- }, JELLYFISH_FRAME_MS);
3078
- timer.unref?.();
3079
- jellyfishTimer = timer;
3080
- return {
3081
- render: () => [],
3082
- invalidate: () => { },
3083
- dispose: () => clearInterval(timer),
3084
- };
3085
- }, { placement: "belowEditor" });
3086
- }
3087
- const JELLYFISH_CLOCK_KEY = "turri-jellyfish";
3088
- /**
3089
- * The whole screen inside its padding (`screen-padding.ts`). An extension is given pi's screen only through what it
3090
- * draws, so an empty widget below the editor hands it over - at each frame, as pi starts a new screen when it changes
3091
- * how it draws.
3092
- */
3093
- function padTheScreen(ctx) {
3094
- ctx.ui.setWidget(SCREEN_PADDING_KEY, (tui) => {
3095
- padScreen(tui);
3096
- return {
3097
- render: () => {
3098
- padScreen(tui);
3099
- return [];
3100
- },
3101
- invalidate: () => { },
3102
- };
3103
- }, { placement: "belowEditor" });
3104
- }
3105
- const SCREEN_PADDING_KEY = "turri-padding";
3106
- /** The columns the banner's picture takes from the left edge, while it shows one; 0 when it does not. */
3107
- let pictureRight = 0;
3108
- /**
3109
- * pi-tui draws no overlay over a line holding an image: it leaves the line as it is, and the side panel
3110
- * would have a gap on the banner's row that carries the picture. So that row's text gets the overlay as
3111
- * any other does, and the picture goes back on after it - unless the overlay reaches over the picture,
3112
- * which is then left out of that row until it no longer does.
3113
- */
3114
- function drawOverlaysBesidePicture(tui) {
3115
- const target = tui;
3116
- if (target.turriPicture === true || typeof target.compositeLineAt !== "function")
3117
- return;
3118
- target.turriPicture = true;
3119
- const original = target.compositeLineAt.bind(tui);
3120
- target.compositeLineAt = (base, overlay, col, width, total) => overPictureRow(base, overlay, col, width, total, pictureRight) ?? original(base, overlay, col, width, total);
3121
- }
3122
- /** Columns between the jellyfish and the lines beside it. */
3123
- const JELLYFISH_GAP = 3;
3124
- /** The fewest columns the lines keep beside the jellyfish; a terminal narrower than that gets the lines alone. */
3125
- const BANNER_TEXT_MIN = 30;
3126
- /**
3127
- * The banner: the jellyfish on the left at the frame `animateJellyfish` has it on, its lines beside it in
3128
- * the middle of its height, and a rule the width of the terminal under them both.
3129
- *
3130
- * pi-tui writes a line holding an image as it is. So the picture goes on one of the rows after that
3131
- * row's text: back to the jellyfish's column (`CSI G`), then the image's escape sequence. Kitty places
3132
- * the image there without moving the cursor, from the first row; iTerm2 moves the cursor past what it
3133
- * draws, so it goes on the last row and climbs back up to start, as pi-tui's Image does.
3134
- */
3135
- class Banner {
3136
- lines;
3137
- rule;
3138
- art;
3139
- kittyImageId;
3140
- /** Without `art` the banner is its lines alone. */
3141
- constructor(lines, rule, art) {
3142
- this.lines = lines;
3143
- this.rule = rule;
3144
- this.art = art;
3145
- }
3146
- invalidate() { }
3147
- render(width) {
3148
- const inner = Math.max(1, width - 2);
3149
- const art = this.art;
3150
- const placed = art?.kind === "image" ? this.placeImage(art, Math.max(JELLYFISH_ROWS, this.lines.length), width - 2 - JELLYFISH_GAP - BANNER_TEXT_MIN) : art?.kind === "text" && art.columns <= width - 2 - JELLYFISH_GAP - BANNER_TEXT_MIN ? art : undefined;
3151
- const left = placed !== undefined ? 1 + placed.columns + JELLYFISH_GAP : 1;
3152
- // Wrapped in the columns beside the picture, never cut short - the chat beside the docked panel is narrow.
3153
- const text = this.lines.flatMap((line) => wrapTextWithAnsi(line, Math.max(1, width - 1 - left)));
3154
- const height = Math.max(text.length, placed?.rows ?? 0);
3155
- const above = Math.floor((height - text.length) / 2);
3156
- const drawn = placed?.kind === "text" ? placed.frames[shownFrame()] : undefined;
3157
- const rows = Array.from({ length: height }, (_, row) => {
3158
- const line = text[row - above];
3159
- const jellyfish = drawn !== undefined ? (drawn[row] ?? " ".repeat(placed.columns)) : " ".repeat(placed?.columns ?? 0);
3160
- const before = placed !== undefined ? ` ${jellyfish}${" ".repeat(JELLYFISH_GAP)}` : " ";
3161
- return line !== undefined ? `${before}${line}` : placed?.kind === "text" ? ` ${jellyfish}` : "";
3162
- });
3163
- // The side panel is drawn beside the picture (drawOverlaysBesidePicture), which goes on showing.
3164
- pictureRight = placed?.kind === "image" ? SCREEN_PADDING.left + 1 + placed.columns : 0;
3165
- if (placed?.kind === "image") {
3166
- const at = placed.onLastRow ? placed.rows - 1 : 0;
3167
- rows[at] = `${rows[at]}${PICTURE_AT}${placed.sequence}`;
3168
- }
3169
- return [...rows, ` ${this.rule("─".repeat(inner))}`];
3170
- }
3171
- placeImage(art, rows, room) {
3172
- if (room < 4)
3173
- return undefined;
3174
- const kitty = getCapabilities().images === "kitty";
3175
- if (kitty && this.kittyImageId === undefined)
3176
- this.kittyImageId = allocateImageId();
3177
- const result = renderImage(art.frames[shownFrame()], art.dimensions, {
3178
- maxWidthCells: room,
3179
- maxHeightCells: rows,
3180
- imageId: this.kittyImageId,
3181
- moveCursor: false,
3182
- });
3183
- if (result === null || result.columns > room)
3184
- return undefined;
3185
- const sequence = kitty ? result.sequence : `${result.rows > 1 ? `\x1b[${result.rows - 1}A` : ""}${result.sequence}`;
3186
- return { kind: "image", sequence, columns: result.columns, rows: result.rows, onLastRow: !kitty };
3187
- }
3188
- }
3189
- const jellyfishFrameCache = new Map();
3190
- /**
3191
- * The banner's jellyfish for this terminal: where it shows images, the picture's frames
3192
- * (scripts/jellyfish-frames.mjs writes them), in the colours for the theme's background; where it does not, the
3193
- * small one in half blocks. None when the pictures cannot be read.
3194
- */
3195
- function jellyfishArt(appearance, truecolor) {
3196
- const dir = join(PACKAGE_ROOT, "assets", "jellyfish");
3197
- try {
3198
- if (getCapabilities().images === null) {
3199
- const frames = JELLYFISH_TEXT_FRAMES.map((pixels) => halfBlocks(pixels, appearance, truecolor));
3200
- return { kind: "text", frames, columns: JELLYFISH_TEXT_FRAMES[0][0].length, rows: frames[0].length };
3201
- }
3202
- let frames = jellyfishFrameCache.get(appearance);
3203
- if (frames === undefined) {
3204
- frames = readdirSync(dir)
3205
- .filter((name) => name.startsWith(`${appearance}-`) && name.endsWith(".png"))
3206
- .sort()
3207
- .map((name) => readFileSync(join(dir, name)).toString("base64"));
3208
- jellyfishFrameCache.set(appearance, frames);
3209
- }
3210
- const dimensions = frames.length > 0 ? getPngDimensions(frames[0]) : null;
3211
- return dimensions !== null ? { kind: "image", frames, dimensions } : undefined;
3212
- }
3213
- catch {
3214
- return undefined;
3215
- }
3216
- }