ceulen 0.5.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (367) hide show
  1. package/CHANGELOG.md +365 -12
  2. package/README.md +87 -91
  3. package/extensions/lib/advisor-marker.ts +33 -0
  4. package/extensions/lib/panel.ts +25 -2
  5. package/extensions/lib/rate.ts +24 -0
  6. package/extensions/lib/registry.test.ts +67 -0
  7. package/extensions/lib/registry.ts +104 -8
  8. package/extensions/lib/tools.ts +47 -0
  9. package/extensions/lib/usage-store.ts +33 -0
  10. package/extensions/modules/advisor/commands/advisor.ts +244 -0
  11. package/extensions/modules/advisor/configPanel.ts +194 -0
  12. package/extensions/modules/advisor/index.ts +235 -0
  13. package/extensions/modules/advisor/lib/config.ts +248 -0
  14. package/extensions/modules/advisor/lib/emission-guard.ts +153 -0
  15. package/extensions/modules/advisor/lib/isolated-model.ts +160 -0
  16. package/extensions/modules/advisor/lib/model-picker.ts +47 -0
  17. package/extensions/modules/advisor/lib/watcher.ts +288 -0
  18. package/extensions/modules/advisor/test/compliance.test.ts +125 -0
  19. package/extensions/modules/advisor/test/config.test.ts +202 -0
  20. package/extensions/modules/advisor/test/configPanel.test.ts +223 -0
  21. package/extensions/modules/advisor/test/emission-guard.test.ts +201 -0
  22. package/extensions/modules/advisor/test/isolated-model.test.ts +311 -0
  23. package/extensions/modules/advisor/test/model-picker.test.ts +32 -0
  24. package/extensions/modules/advisor/test/module.test.ts +649 -0
  25. package/extensions/modules/advisor/test/watcher.test.ts +478 -0
  26. package/extensions/modules/classifier/configPanel.ts +104 -0
  27. package/extensions/modules/classifier/index.ts +297 -0
  28. package/extensions/modules/classifier/lib/settings.ts +95 -0
  29. package/extensions/modules/classifier/test/classifier.test.ts +475 -0
  30. package/extensions/modules/composer/index.ts +152 -3
  31. package/extensions/modules/composer/lib/footer.ts +119 -0
  32. package/extensions/modules/composer/lib/shapes.ts +265 -26
  33. package/extensions/modules/composer/test/editor.test.ts +1 -1
  34. package/extensions/modules/composer/test/footer.test.ts +96 -0
  35. package/extensions/modules/composer/test/module.test.ts +113 -11
  36. package/extensions/modules/composer/test/screen.test.ts +29 -1
  37. package/extensions/modules/composer/test/shapes.test.ts +224 -8
  38. package/extensions/modules/config/defaultTools.ts +96 -0
  39. package/extensions/modules/config/index.ts +147 -7
  40. package/extensions/modules/config/piSettings.ts +254 -69
  41. package/extensions/modules/config/test/defaultTools.test.ts +122 -0
  42. package/extensions/modules/config/test/menu.test.ts +64 -0
  43. package/extensions/modules/config/test/panel.test.ts +38 -23
  44. package/extensions/modules/config/test/piSettings.test.ts +130 -3
  45. package/extensions/modules/config/test/renderTools.test.ts +71 -0
  46. package/extensions/modules/config/test/tools.test.ts +146 -0
  47. package/extensions/modules/fff/index.ts +2094 -0
  48. package/extensions/modules/fff/lib/query.ts +129 -0
  49. package/extensions/modules/fff/test/index.test.ts +607 -0
  50. package/extensions/modules/fff/test/query.test.ts +71 -0
  51. package/extensions/modules/munin/configPanel.ts +108 -0
  52. package/extensions/modules/munin/index.ts +641 -0
  53. package/extensions/modules/munin/lib/helpers.ts +471 -0
  54. package/extensions/modules/munin/lib/retry.ts +20 -0
  55. package/extensions/modules/munin/lib/sdk.ts +218 -0
  56. package/extensions/modules/munin/test/config.test.ts +168 -0
  57. package/extensions/modules/munin/test/configPanel.test.ts +186 -0
  58. package/extensions/modules/munin/test/extension.test.ts +224 -0
  59. package/extensions/modules/munin/test/helpers.test.ts +523 -0
  60. package/extensions/modules/munin/test/retry.test.ts +145 -0
  61. package/extensions/modules/munin/test/stale-protocol.test.ts +554 -0
  62. package/extensions/modules/plan/configPanel.ts +152 -0
  63. package/extensions/modules/plan/index.ts +917 -0
  64. package/extensions/modules/plan/lib/plan-tools.ts +72 -0
  65. package/extensions/modules/plan/lib/prompt.ts +65 -0
  66. package/extensions/modules/plan/lib/settings.ts +166 -0
  67. package/extensions/modules/plan/lib/shell-gate.ts +200 -0
  68. package/extensions/modules/plan/test/configPanel.test.ts +96 -0
  69. package/extensions/modules/plan/test/harness.ts +133 -0
  70. package/extensions/modules/plan/test/module.test.ts +305 -0
  71. package/extensions/modules/plan/test/settings.test.ts +114 -0
  72. package/extensions/modules/plan/test/shell-gate.test.ts +103 -0
  73. package/extensions/modules/ponytail/index.ts +23 -73
  74. package/extensions/modules/ponytail/lib/config.ts +1 -6
  75. package/extensions/modules/ponytail/test/extension.test.ts +1 -85
  76. package/extensions/modules/repair/configPanel.ts +96 -0
  77. package/extensions/modules/repair/index.ts +414 -0
  78. package/extensions/modules/repair/lib/auto-bg.ts +333 -0
  79. package/extensions/modules/repair/lib/edit-repair.ts +155 -0
  80. package/extensions/modules/repair/lib/editor.ts +251 -0
  81. package/extensions/modules/repair/lib/guards.ts +34 -0
  82. package/extensions/modules/repair/lib/input-repair.ts +324 -0
  83. package/extensions/modules/repair/lib/patch.ts +481 -0
  84. package/extensions/modules/repair/lib/settings.ts +114 -0
  85. package/extensions/modules/repair/test/auto-bg.test.ts +405 -0
  86. package/extensions/modules/repair/test/edit-repair.test.ts +224 -0
  87. package/extensions/modules/repair/test/editor.test.ts +141 -0
  88. package/extensions/modules/repair/test/guards.test.ts +64 -0
  89. package/extensions/modules/repair/test/input-repair.test.ts +231 -0
  90. package/extensions/modules/repair/test/patch.test.ts +563 -0
  91. package/extensions/modules/repair/test/settings.test.ts +167 -0
  92. package/extensions/modules/repair/test/wrapper.test.ts +210 -0
  93. package/extensions/modules/router/commands/commands.ts +4 -0
  94. package/extensions/modules/router/configPanel.ts +24 -10
  95. package/extensions/modules/router/lib/client.ts +63 -0
  96. package/extensions/modules/router/lib/provider.ts +34 -13
  97. package/extensions/modules/router/lib/systemone.ts +152 -0
  98. package/extensions/modules/router/test/unit.test.ts +260 -0
  99. package/extensions/modules/rtk/findFallback.js +68 -0
  100. package/extensions/modules/rtk/index.ts +248 -0
  101. package/extensions/modules/rtk/safe-rewrite.js +74 -0
  102. package/extensions/modules/rtk/test/findFallback.test.js +66 -0
  103. package/extensions/modules/rtk/test/index.test.js +131 -0
  104. package/extensions/modules/rtk/test/safe-rewrite.test.js +96 -0
  105. package/extensions/modules/rtk/version-gate.js +34 -0
  106. package/extensions/modules/rules/index.ts +120 -0
  107. package/extensions/modules/rules/lib/rules.ts +348 -0
  108. package/extensions/modules/rules/test/lib.test.ts +263 -0
  109. package/extensions/modules/rules/test/module.test.ts +222 -0
  110. package/extensions/modules/serena/index.ts +629 -0
  111. package/extensions/modules/serena/lib/detect.ts +73 -0
  112. package/extensions/modules/serena/lib/env.ts +76 -0
  113. package/extensions/modules/serena/lib/guidance.ts +26 -0
  114. package/extensions/modules/serena/lib/normalize.ts +27 -0
  115. package/extensions/modules/serena/lib/symbol-key.ts +20 -0
  116. package/extensions/modules/serena/lib/truncate.ts +20 -0
  117. package/extensions/modules/serena/test/env.test.ts +122 -0
  118. package/extensions/modules/serena/test/index.test.ts +347 -0
  119. package/extensions/modules/serena/test/worker.test.ts +562 -0
  120. package/extensions/modules/serena/worker.ts +858 -0
  121. package/extensions/modules/steering/configPanel.ts +122 -0
  122. package/extensions/modules/steering/index.ts +616 -0
  123. package/extensions/modules/steering/lib/anchor.ts +175 -0
  124. package/extensions/modules/steering/lib/errors.ts +253 -0
  125. package/extensions/modules/steering/lib/family.ts +33 -0
  126. package/extensions/modules/steering/lib/guidance.ts +172 -0
  127. package/extensions/modules/steering/lib/history.ts +170 -0
  128. package/extensions/modules/steering/lib/settings.ts +127 -0
  129. package/extensions/modules/steering/test/anchor-regressions.test.ts +93 -0
  130. package/extensions/modules/steering/test/anchor-wiring.test.ts +99 -0
  131. package/extensions/modules/steering/test/anchor.test.ts +160 -0
  132. package/extensions/modules/steering/test/cache-stats.test.ts +43 -0
  133. package/extensions/modules/steering/test/errors.test.ts +309 -0
  134. package/extensions/modules/steering/test/family.test.ts +43 -0
  135. package/extensions/modules/steering/test/guidance.test.ts +357 -0
  136. package/extensions/modules/steering/test/harness.ts +93 -0
  137. package/extensions/modules/steering/test/history.test.ts +118 -0
  138. package/extensions/modules/steering/test/settings.test.ts +182 -0
  139. package/extensions/modules/steering/test/status.test.ts +71 -0
  140. package/extensions/modules/steering/test/toolCall.test.ts +99 -0
  141. package/extensions/modules/subagent/agents/planner.md +14 -0
  142. package/extensions/modules/subagent/agents/reviewer.md +42 -0
  143. package/extensions/modules/subagent/agents/scout.md +47 -0
  144. package/extensions/modules/subagent/agents/tester.md +12 -0
  145. package/extensions/modules/subagent/agents/worker.md +18 -0
  146. package/extensions/modules/subagent/configPanel.ts +219 -0
  147. package/extensions/modules/subagent/index.ts +2464 -0
  148. package/extensions/modules/subagent/lib/agents.ts +408 -0
  149. package/extensions/modules/subagent/lib/background.ts +383 -0
  150. package/extensions/modules/subagent/lib/herdr.ts +1019 -0
  151. package/extensions/modules/subagent/lib/history.ts +126 -0
  152. package/extensions/modules/subagent/lib/model.ts +156 -0
  153. package/extensions/modules/subagent/lib/render.ts +335 -0
  154. package/extensions/modules/subagent/lib/result.ts +110 -0
  155. package/extensions/modules/subagent/lib/roles.ts +296 -0
  156. package/extensions/modules/subagent/lib/routing.ts +228 -0
  157. package/extensions/modules/subagent/lib/runner.ts +559 -0
  158. package/extensions/modules/subagent/lib/schema.ts +21 -0
  159. package/extensions/modules/subagent/lib/security.ts +763 -0
  160. package/extensions/modules/subagent/lib/settings.ts +159 -0
  161. package/extensions/modules/subagent/lib/thread-viewer.ts +319 -0
  162. package/extensions/modules/subagent/lib/threads.ts +135 -0
  163. package/extensions/modules/subagent/lib/types.ts +18 -0
  164. package/extensions/modules/subagent/lib/widget.ts +475 -0
  165. package/extensions/modules/subagent/test/configPanel.test.ts +132 -0
  166. package/extensions/modules/subagent/test/herdr-advisor.test.ts +40 -0
  167. package/extensions/modules/subagent/test/routing.test.ts +524 -0
  168. package/extensions/modules/subagent/test/widget.test.ts +208 -0
  169. package/extensions/modules/todo/index.ts +478 -0
  170. package/extensions/modules/todo/test/todo.test.ts +252 -0
  171. package/extensions/modules/usage/index.ts +70 -16
  172. package/extensions/modules/usage/test/genrate.test.ts +70 -0
  173. package/extensions/modules/usage/test/parsers.test.ts +13 -0
  174. package/extensions/modules/usage/test/session-accumulators.test.ts +85 -0
  175. package/extensions/modules/ux/UPSTREAM +24 -0
  176. package/extensions/modules/ux/index.ts +393 -0
  177. package/extensions/modules/ux/lib/audit.ts +562 -0
  178. package/extensions/modules/ux/lib/config.ts +136 -0
  179. package/extensions/modules/ux/lib/instructions.ts +77 -0
  180. package/extensions/modules/ux/test/audit.test.ts +756 -0
  181. package/extensions/modules/ux/test/extension.test.ts +394 -0
  182. package/extensions/modules/ux/test/instructions.test.ts +19 -0
  183. package/extensions/modules/web/configPanel.ts +218 -0
  184. package/extensions/modules/web/index.ts +978 -0
  185. package/extensions/modules/web/lib/agy.ts +209 -0
  186. package/extensions/modules/web/lib/brave.ts +42 -0
  187. package/extensions/modules/web/lib/cdp.ts +686 -0
  188. package/extensions/modules/web/lib/chatapi.ts +101 -0
  189. package/extensions/modules/web/lib/chatgpt.ts +796 -0
  190. package/extensions/modules/web/lib/chrome.ts +328 -0
  191. package/extensions/modules/web/lib/config.ts +136 -0
  192. package/extensions/modules/web/lib/content.ts +99 -0
  193. package/extensions/modules/web/lib/crawl4ai.ts +172 -0
  194. package/extensions/modules/web/lib/extract.ts +235 -0
  195. package/extensions/modules/web/lib/firecrawl.ts +56 -0
  196. package/extensions/modules/web/lib/format.ts +197 -0
  197. package/extensions/modules/web/lib/gemini-auth.ts +286 -0
  198. package/extensions/modules/web/lib/gemini-dr.ts +338 -0
  199. package/extensions/modules/web/lib/gemini.ts +551 -0
  200. package/extensions/modules/web/lib/imageapi.ts +559 -0
  201. package/extensions/modules/web/lib/retry.ts +71 -0
  202. package/extensions/modules/web/lib/search.ts +237 -0
  203. package/extensions/modules/web/lib/searxng.ts +69 -0
  204. package/extensions/modules/web/lib/settings.ts +157 -0
  205. package/extensions/modules/web/scripts/cdp-smoke.ts +77 -0
  206. package/extensions/modules/web/scripts/gemini-smoke.ts +107 -0
  207. package/extensions/modules/web/test/agy.test.ts +383 -0
  208. package/extensions/modules/web/test/cdp.test.ts +717 -0
  209. package/extensions/modules/web/test/chat.test.ts +171 -0
  210. package/extensions/modules/web/test/chatgpt.test.ts +633 -0
  211. package/extensions/modules/web/test/chrome.test.ts +282 -0
  212. package/extensions/modules/web/test/config.test.ts +218 -0
  213. package/extensions/modules/web/test/configPanel.test.ts +198 -0
  214. package/extensions/modules/web/test/crawl.test.ts +134 -0
  215. package/extensions/modules/web/test/crawl4ai.test.ts +105 -0
  216. package/extensions/modules/web/test/extension.test.ts +118 -0
  217. package/extensions/modules/web/test/extract.test.ts +436 -0
  218. package/extensions/modules/web/test/fixtures/dr-confirm.bin +12 -0
  219. package/extensions/modules/web/test/fixtures/dr-plan.bin +20 -0
  220. package/extensions/modules/web/test/fixtures/interaction.html +31 -0
  221. package/extensions/modules/web/test/format.test.ts +230 -0
  222. package/extensions/modules/web/test/gemini-auth.test.ts +465 -0
  223. package/extensions/modules/web/test/gemini-dr.test.ts +249 -0
  224. package/extensions/modules/web/test/gemini.test.ts +472 -0
  225. package/extensions/modules/web/test/hook.test.ts +101 -0
  226. package/extensions/modules/web/test/image.test.ts +1089 -0
  227. package/extensions/modules/web/test/retry.test.ts +119 -0
  228. package/extensions/modules/web/test/screenshot.test.ts +109 -0
  229. package/extensions/modules/web/test/search.test.ts +210 -0
  230. package/extensions/modules/web/test/settings.test.ts +165 -0
  231. package/extensions/modules/web/test/skill.test.ts +72 -0
  232. package/extensions/modules/web/types.d.ts +3 -0
  233. package/extensions/modules/web/vendor/package.json +1 -0
  234. package/extensions/modules/web/vendor/readability/LICENSE.md +13 -0
  235. package/extensions/modules/web/vendor/readability/Readability-readerable.js +123 -0
  236. package/extensions/modules/web/vendor/readability/Readability.js +2787 -0
  237. package/extensions/modules/web/vendor/readability/index.d.ts +64 -0
  238. package/extensions/modules/web/vendor/readability/index.js +9 -0
  239. package/extensions/modules/web/vendor/turndown/LICENSE +21 -0
  240. package/extensions/modules/web/vendor/turndown/turndown.cjs.js +784 -0
  241. package/extensions/modules/web/vendor/turndown-plugin-gfm/LICENSE +21 -0
  242. package/extensions/modules/web/vendor/turndown-plugin-gfm/turndown-plugin-gfm.cjs.js +163 -0
  243. package/extensions/modules/zai/configPanel.ts +154 -0
  244. package/extensions/modules/zai/index.ts +186 -0
  245. package/extensions/modules/zai/lib/anthropic.ts +159 -0
  246. package/extensions/modules/zai/lib/settings.ts +198 -0
  247. package/extensions/modules/zai/lib/signing.ts +721 -0
  248. package/extensions/modules/zai/lib/throttle.ts +198 -0
  249. package/extensions/modules/zai/test/anthropic.test.ts +132 -0
  250. package/extensions/modules/zai/test/configPanel.test.ts +230 -0
  251. package/extensions/modules/zai/test/extension.test.ts +249 -0
  252. package/extensions/modules/zai/test/settings.test.ts +183 -0
  253. package/extensions/modules/zai/test/signing-wiring.test.ts +108 -0
  254. package/extensions/modules/zai/test/signing.test.ts +364 -0
  255. package/extensions/modules/zai/test/throttle.test.ts +329 -0
  256. package/package.json +19 -4
  257. package/scripts/validate-themes.mjs +75 -0
  258. package/skills/munin/SKILL.md +117 -0
  259. package/skills/ux-capture/SKILL.md +202 -0
  260. package/skills/ux-design/SKILL.md +279 -0
  261. package/skills/ux-presets/SKILL.md +484 -0
  262. package/skills/ux-routing/SKILL.md +46 -0
  263. package/skills/web/SKILL.md +153 -0
  264. package/themes/alabaster.json +93 -0
  265. package/themes/amethyst.json +96 -0
  266. package/themes/anthracite.json +93 -0
  267. package/themes/basalt.json +91 -0
  268. package/themes/birch.json +95 -0
  269. package/themes/catppuccin-mocha.json +91 -0
  270. package/themes/dark-abyss.json +91 -0
  271. package/themes/dark-arctic.json +104 -0
  272. package/themes/dark-aurora.json +95 -0
  273. package/themes/dark-catppuccin.json +107 -0
  274. package/themes/dark-cavern.json +91 -0
  275. package/themes/dark-celestial.json +106 -0
  276. package/themes/dark-copper.json +95 -0
  277. package/themes/dark-cosmos.json +90 -0
  278. package/themes/dark-cyberpunk.json +102 -0
  279. package/themes/dark-dracula.json +98 -0
  280. package/themes/dark-eclipse.json +91 -0
  281. package/themes/dark-ember.json +95 -0
  282. package/themes/dark-equinox.json +90 -0
  283. package/themes/dark-forest.json +96 -0
  284. package/themes/dark-github.json +105 -0
  285. package/themes/dark-gruvbox.json +112 -0
  286. package/themes/dark-lavender.json +95 -0
  287. package/themes/dark-lunar.json +89 -0
  288. package/themes/dark-midnight.json +95 -0
  289. package/themes/dark-monochrome.json +94 -0
  290. package/themes/dark-monokai.json +98 -0
  291. package/themes/dark-nebula.json +90 -0
  292. package/themes/dark-neon-noir.json +100 -0
  293. package/themes/dark-nord.json +98 -0
  294. package/themes/dark-ocean.json +101 -0
  295. package/themes/dark-one.json +100 -0
  296. package/themes/dark-poimandres.json +115 -0
  297. package/themes/dark-rainforest.json +91 -0
  298. package/themes/dark-reef.json +91 -0
  299. package/themes/dark-retro.json +92 -0
  300. package/themes/dark-rose-pine.json +96 -0
  301. package/themes/dark-sakura.json +95 -0
  302. package/themes/dark-slate.json +95 -0
  303. package/themes/dark-solarized.json +97 -0
  304. package/themes/dark-solstice.json +90 -0
  305. package/themes/dark-starfall.json +91 -0
  306. package/themes/dark-sunset.json +99 -0
  307. package/themes/dark-swamp.json +90 -0
  308. package/themes/dark-synthwave.json +103 -0
  309. package/themes/dark-taiga.json +91 -0
  310. package/themes/dark-terminal.json +95 -0
  311. package/themes/dark-tokyo-night.json +101 -0
  312. package/themes/dark-tundra.json +91 -0
  313. package/themes/dark-twilight.json +91 -0
  314. package/themes/dark-volcanic.json +91 -0
  315. package/themes/dark.json +80 -0
  316. package/themes/graphite.json +92 -0
  317. package/themes/light-arctic.json +107 -0
  318. package/themes/light-aurora-day.json +91 -0
  319. package/themes/light-canyon.json +91 -0
  320. package/themes/light-catppuccin.json +106 -0
  321. package/themes/light-cirrus.json +90 -0
  322. package/themes/light-coral.json +95 -0
  323. package/themes/light-cyberpunk.json +96 -0
  324. package/themes/light-dawn.json +90 -0
  325. package/themes/light-dunes.json +91 -0
  326. package/themes/light-eucalyptus.json +95 -0
  327. package/themes/light-forest.json +100 -0
  328. package/themes/light-frost.json +95 -0
  329. package/themes/light-github.json +115 -0
  330. package/themes/light-glacier.json +91 -0
  331. package/themes/light-gruvbox.json +108 -0
  332. package/themes/light-haze.json +90 -0
  333. package/themes/light-honeycomb.json +95 -0
  334. package/themes/light-lagoon.json +91 -0
  335. package/themes/light-lavender.json +95 -0
  336. package/themes/light-meadow.json +91 -0
  337. package/themes/light-mint.json +95 -0
  338. package/themes/light-monochrome.json +101 -0
  339. package/themes/light-ocean.json +99 -0
  340. package/themes/light-one.json +99 -0
  341. package/themes/light-opal.json +91 -0
  342. package/themes/light-orchard.json +91 -0
  343. package/themes/light-paper.json +95 -0
  344. package/themes/light-poimandres.json +115 -0
  345. package/themes/light-prism.json +90 -0
  346. package/themes/light-retro.json +98 -0
  347. package/themes/light-sand.json +95 -0
  348. package/themes/light-savanna.json +91 -0
  349. package/themes/light-solarized.json +102 -0
  350. package/themes/light-soleil.json +90 -0
  351. package/themes/light-sunset.json +99 -0
  352. package/themes/light-synthwave.json +98 -0
  353. package/themes/light-tokyo-night.json +111 -0
  354. package/themes/light-wetland.json +91 -0
  355. package/themes/light-zenith.json +89 -0
  356. package/themes/light.json +80 -0
  357. package/themes/limestone.json +94 -0
  358. package/themes/mahogany.json +97 -0
  359. package/themes/marble.json +93 -0
  360. package/themes/mirage.json +79 -0
  361. package/themes/obsidian.json +91 -0
  362. package/themes/onyx.json +91 -0
  363. package/themes/pearl.json +93 -0
  364. package/themes/porcelain.json +91 -0
  365. package/themes/quartz.json +96 -0
  366. package/themes/sandstone.json +95 -0
  367. package/themes/titanium.json +90 -0
@@ -0,0 +1,252 @@
1
+ /**
2
+ * todo module tests — the state machine, persistence rehydrate, and the
3
+ * footer indicator. Untyped harness stub: only the pi surface the module
4
+ * touches (usage/ponytail test tradition).
5
+ */
6
+
7
+ import assert from "node:assert/strict";
8
+ import { describe, it } from "node:test";
9
+
10
+ import todoModule, {
11
+ TODO_ENTRY_TYPE,
12
+ TODO_STATUS_KEY,
13
+ applyTodo,
14
+ resolveTodoPhases,
15
+ statusLine,
16
+ type TodoPhase,
17
+ } from "../index.ts";
18
+
19
+ type Params = Parameters<typeof applyTodo>[1];
20
+ const op = (o: Record<string, unknown>) => o as unknown as Params;
21
+
22
+ /** Apply an action to a list and return the resulting phases (throws on error). */
23
+ function run(current: TodoPhase[], params: Record<string, unknown>): TodoPhase[] {
24
+ const r = applyTodo(current, op(params));
25
+ assert.deepEqual(r.errors, [], `unexpected errors: ${r.errors}`);
26
+ return r.phases;
27
+ }
28
+ function fail(current: TodoPhase[], params: Record<string, unknown>): string[] {
29
+ const r = applyTodo(current, op(params));
30
+ assert.ok(r.errors.length > 0, "expected an error");
31
+ assert.equal(r.changed, false);
32
+ return r.errors;
33
+ }
34
+
35
+ const seeded = () =>
36
+ run([], {
37
+ action: "init",
38
+ phases: [{ title: "Read the repo" }, { title: "Port the tool" }, { title: "Verify" }],
39
+ });
40
+
41
+ function createPiHarness() {
42
+ const events = new Map<string, (event: unknown, ctx: unknown) => unknown>();
43
+ const commands = new Map<string, unknown>();
44
+ const tools = new Map<string, any>();
45
+ const entries: Array<{ customType: string; data: unknown }> = [];
46
+ let branchEntries: unknown[] = [];
47
+ const statusCalls: Array<[string, string | undefined]> = [];
48
+ const notifications: string[] = [];
49
+
50
+ const ui = {
51
+ notify: (m: string) => { notifications.push(m); },
52
+ setStatus: (k: string, t: string | undefined) => { statusCalls.push([k, t]); },
53
+ };
54
+ const ctx = { ui, sessionManager: { getBranch: () => branchEntries } };
55
+
56
+ const pi = {
57
+ on: (n: string, h: any) => { events.set(n, h); },
58
+ registerTool: (t: any) => { tools.set(t.name, t); },
59
+ registerCommand: (n: string, o: any) => { commands.set(n, o); },
60
+ appendEntry: (customType: string, data: unknown) => { entries.push({ customType, data }); },
61
+ };
62
+ todoModule(pi as never);
63
+
64
+ return {
65
+ events, commands, tools, entries, statusCalls, notifications, ui, ctx,
66
+ setBranch: (e: unknown[]) => { branchEntries = e; },
67
+ /** Fire the tool with params through the real execute() path. */
68
+ call: (params: Record<string, unknown>) => tools.get("todo").execute("call-1", op(params), undefined, undefined, ctx),
69
+ };
70
+ }
71
+
72
+ describe("todo state machine", () => {
73
+ it("init assigns stable ids, replaces the whole list, and auto-starts the first phase", () => {
74
+ const phases = seeded();
75
+ assert.deepEqual(phases.map((p) => [p.id, p.status]), [["p1", "in_progress"], ["p2", "pending"], ["p3", "pending"]]);
76
+ const replaced = run(phases, { action: "init", phases: [{ id: "a", title: "Only" }] });
77
+ assert.deepEqual(replaced.map((p) => p.id), ["a"]);
78
+ });
79
+
80
+ it("start marks in_progress; a second start ERRORS while one is running", () => {
81
+ // seeded() already auto-started p1 — p2 must be forced.
82
+ assert.match(fail(seeded(), { action: "start", id: "p2" })[0], /already in_progress/);
83
+ const forced = run(seeded(), { action: "start", id: "p2", force: true });
84
+ assert.deepEqual(forced.map((p) => p.status), ["pending", "in_progress", "pending"]);
85
+ // An explicit start that finishes the running phase advances the pointer by itself.
86
+ assert.equal(run(seeded(), { action: "done", id: "p1" })[1].status, "in_progress");
87
+ });
88
+
89
+ it("done marks done (idempotent) and never reopens a finished phase", () => {
90
+ const done = run(run(seeded(), { action: "done", id: "p1" }), { action: "done", id: "p3" });
91
+ // p2 auto-started when p1 completed; the out-of-order done of p3 leaves it running.
92
+ assert.deepEqual(done.map((p) => p.status), ["done", "in_progress", "done"]);
93
+ assert.equal(run(done, { action: "done", id: "p3" })[2].status, "done", "done of already-done stays done");
94
+ });
95
+
96
+ it("block/unblock set blockedBy; a blocked phase is skipped by the pointer", () => {
97
+ // p2 waits on p3 — a blocker that stays UNMET after p1 completes.
98
+ const blocked = run(seeded(), { action: "block", id: "p2", blockedBy: ["p3"] });
99
+ assert.deepEqual(blocked[1].blockedBy, ["p3"]);
100
+
101
+ // p1 completes → the pointer must SKIP blocked p2 and land on p3.
102
+ const advanced = run(blocked, { action: "done", id: "p1" });
103
+ assert.deepEqual(advanced.map((p) => p.status), ["done", "pending", "in_progress"]);
104
+ assert.equal(statusLine(advanced), "▸ 1/3 done · in_progress: Verify · 1 blocked");
105
+
106
+ // A met blocker unblocks the phase — but never steals a running pointer.
107
+ const unblocked = run(blocked, { action: "unblock", id: "p2" });
108
+ assert.deepEqual(unblocked[1].blockedBy, []);
109
+ const partial = run(run(blocked, { action: "block", id: "p2", blockedBy: ["p1"] }), { action: "unblock", id: "p2", blockedBy: ["p3"] });
110
+ assert.deepEqual(partial[1].blockedBy, ["p1"], "unblock drops only the named edge");
111
+ });
112
+
113
+ it("append adds one phase with a fresh id and rejects duplicates", () => {
114
+ const appended = run(seeded(), { action: "append", phases: [{ title: "Ship it" }] });
115
+ assert.deepEqual(appended.map((p) => p.id), ["p1", "p2", "p3", "p4"]);
116
+ assert.match(fail(appended, { action: "append", phases: [{ title: "Ship it" }] })[0], /already exists/);
117
+ });
118
+
119
+ it("rm removes a phase (and its dangling blocker edges), or clears the list", () => {
120
+ const blocked = run(seeded(), { action: "block", id: "p3", blockedBy: ["p2"] });
121
+ const removed = run(blocked, { action: "rm", id: "p2" });
122
+ assert.deepEqual(removed.map((p) => p.id), ["p1", "p3"]);
123
+ assert.deepEqual(removed[1].blockedBy, [], "the removed phase is no longer a blocker");
124
+ assert.deepEqual(run(seeded(), { action: "rm" }), [], "rm without an id clears");
125
+ });
126
+
127
+ it("errors: unknown phase, block with no blocker, unknown blocker, self-block, duplicate ids", () => {
128
+ const phases = seeded();
129
+ assert.match(fail(phases, { action: "start", id: "nope" })[0], /not found/);
130
+ assert.match(fail(phases, { action: "start" })[0], /Missing phase id/);
131
+ assert.match(fail(phases, { action: "block", id: "p1" })[0], /needs blockedBy/);
132
+ assert.match(fail(phases, { action: "block", id: "p1", blockedBy: ["ghost"] })[0], /not a phase in this list/);
133
+ assert.match(fail(phases, { action: "block", id: "p1", blockedBy: ["p1"] })[0], /cannot block itself/);
134
+ assert.match(fail(phases, { action: "init", phases: [{ id: "x", title: "A" }, { id: "x", title: "B" }] })[0], /Duplicate phase id/);
135
+ assert.match(fail(phases, { action: "init", phases: [{ title: "A", blockedBy: ["zz"] }] })[0], /unknown phase "zz"/);
136
+ });
137
+
138
+ it("view never changes the list", () => {
139
+ const phases = seeded();
140
+ const r = applyTodo(phases, op({ action: "view" }));
141
+ assert.deepEqual(r.errors, []);
142
+ assert.equal(r.changed, false);
143
+ assert.deepEqual(r.phases, phases);
144
+ });
145
+ });
146
+
147
+ describe("status indicator text", () => {
148
+ it("counts done/total, names the running phase, and clears when done", () => {
149
+ assert.equal(statusLine([]), undefined, "empty list → cleared");
150
+ assert.equal(statusLine(seeded()), "▸ 0/3 done · in_progress: Read the repo");
151
+ const allDone = run(run(run(seeded(), { action: "done", id: "p1" }), { action: "done", id: "p2" }), { action: "done", id: "p3" });
152
+ assert.equal(statusLine(allDone), undefined, "all done → cleared");
153
+ // A list whose remaining phases are all blocked names no pointer.
154
+ const blocked = run(run(seeded(), { action: "block", id: "p1", blockedBy: ["p2"] }), { action: "block", id: "p2", blockedBy: ["p3"] });
155
+ assert.equal(statusLine(blocked), "▸ 0/3 done · next: Verify · 2 blocked");
156
+ });
157
+ });
158
+
159
+ describe("module wiring", () => {
160
+ it("registers one tool and one command", () => {
161
+ const h = createPiHarness();
162
+ assert.deepEqual([...h.tools.keys()], ["todo"]);
163
+ assert.deepEqual([...h.commands.keys()], ["todo"]);
164
+ });
165
+
166
+ it("persists to ceulen-todo on every mutation, never on view", async () => {
167
+ const h = createPiHarness();
168
+ await h.call({ action: "init", phases: [{ title: "One" }, { title: "Two" }] });
169
+ await h.call({ action: "view" });
170
+ await h.call({ action: "done", id: "p1" });
171
+ assert.deepEqual(h.entries.map((e) => e.customType), [TODO_ENTRY_TYPE, TODO_ENTRY_TYPE]);
172
+ assert.deepEqual((h.entries[1].data as any).phases.map((p: TodoPhase) => p.status), ["done", "in_progress"]);
173
+ });
174
+
175
+ it("a failed op keeps the previous state and reports it as an error", async () => {
176
+ const h = createPiHarness();
177
+ await h.call({ action: "init", phases: [{ title: "One" }] });
178
+ const before = h.entries.length;
179
+ const r = await h.call({ action: "start", id: "ghost" });
180
+ assert.equal(r.isError, true);
181
+ assert.match(r.content[0].text, /not found/);
182
+ assert.match(r.content[0].text, /\[p1\] One/, "the board stays at the previous state");
183
+ assert.equal(h.entries.length, before, "no persistence on error");
184
+ });
185
+
186
+ it("mutating results restate the batch contract; a view does not", async () => {
187
+ const h = createPiHarness();
188
+ const init = await h.call({ action: "init", phases: [{ title: "One" }] });
189
+ assert.match(init.content[0].text, /never call todo alone/);
190
+ assert.match(init.content[0].text, /1\. ▸ \[p1\] One/, "the board renders glyph + id + title");
191
+ const view = await h.call({ action: "view" });
192
+ assert.doesNotMatch(view.content[0].text, /never call todo alone/);
193
+ });
194
+
195
+ it("the tool carries the batch contract as guidelines", () => {
196
+ const h = createPiHarness();
197
+ const guidelines: string[] = h.tools.get("todo").promptGuidelines;
198
+ assert.ok(guidelines.some((g) => /NEVER call todo alone/.test(g)));
199
+ assert.ok(guidelines.some((g) => /init alongside the FIRST work call/.test(g)));
200
+ assert.ok(guidelines.some((g) => /SAME call that starts the next action/.test(g)));
201
+ });
202
+
203
+ it("sets the footer indicator on mutation and clears it on shutdown", async () => {
204
+ const h = createPiHarness();
205
+ await h.call({ action: "init", phases: [{ title: "One" }] });
206
+ assert.deepEqual(h.statusCalls.at(-1), [TODO_STATUS_KEY, "▸ 0/1 done · in_progress: One"]);
207
+ await h.call({ action: "done", id: "p1" });
208
+ assert.deepEqual(h.statusCalls.at(-1), [TODO_STATUS_KEY, undefined], "all done → cleared");
209
+ await h.events.get("session_shutdown")!({}, h.ctx);
210
+ assert.deepEqual(h.statusCalls.at(-1), [TODO_STATUS_KEY, undefined]);
211
+ });
212
+
213
+ it("rehydrates the LAST ceulen-todo entry on session_start", async () => {
214
+ const h = createPiHarness();
215
+ h.setBranch([
216
+ { type: "message" },
217
+ { type: "custom", customType: TODO_ENTRY_TYPE, data: { phases: [{ id: "old", title: "Stale", status: "pending", blockedBy: [] }] } },
218
+ { type: "custom", customType: "other-entry", data: {} },
219
+ { type: "custom", customType: TODO_ENTRY_TYPE, data: { phases: [{ id: "a", title: "Resumed", status: "in_progress", blockedBy: [] }] } },
220
+ ]);
221
+ await h.events.get("session_start")!({}, h.ctx);
222
+ assert.deepEqual(h.statusCalls.at(-1), [TODO_STATUS_KEY, "▸ 0/1 done · in_progress: Resumed"]);
223
+ await h.call({ action: "done", id: "a" });
224
+ assert.deepEqual((h.entries.at(-1)!.data as any).phases[0].title, "Resumed");
225
+ });
226
+
227
+ it("resolveTodoPhases ignores malformed entries and unknown customTypes", () => {
228
+ assert.deepEqual(resolveTodoPhases(undefined), []);
229
+ assert.deepEqual(resolveTodoPhases([{ type: "custom", customType: "other", data: { phases: [{ id: "x", title: "y", status: "pending", blockedBy: [] }] } }]), []);
230
+ // Junk entries without a phases array are skipped, not fatal.
231
+ assert.deepEqual(
232
+ resolveTodoPhases([{ type: "custom", customType: TODO_ENTRY_TYPE, data: {} }, { type: "custom", customType: TODO_ENTRY_TYPE, data: { phases: [{ id: "a", title: "Good", status: "pending", blockedBy: [], junk: 1 }] } }]).map((p) => p.id),
233
+ ["a"],
234
+ );
235
+ });
236
+ });
237
+
238
+ describe("/todo command", () => {
239
+ it("bare prints the board, unknown warns, clear resets", async () => {
240
+ const h = createPiHarness();
241
+ await h.call({ action: "init", phases: [{ title: "One" }] });
242
+ const cmd = h.commands.get("todo") as any;
243
+ await cmd.handler("", h.ctx);
244
+ assert.match(h.notifications.at(-1)!, /\[p1\] One/);
245
+ await cmd.handler("bogus", h.ctx);
246
+ assert.match(h.notifications.at(-1)!, /Unknown subcommand/);
247
+ await cmd.handler("clear", h.ctx);
248
+ assert.equal(h.notifications.at(-1), "Todo list cleared.");
249
+ await cmd.handler("", h.ctx);
250
+ assert.equal(h.notifications.at(-1), "Todo list is empty.");
251
+ });
252
+ });
@@ -4,7 +4,8 @@ import fs from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { loadCwdEnvFilesIfTrusted, parseEnvText } from "../../lib/env.js";
7
-
7
+ import { resetGenRate, setGenRate } from "../../lib/rate.js";
8
+ import { resetUsageItem, setUsageItem } from "../../lib/usage-store.js";
8
9
  /** Single source of truth for User-Agent strings — matches package.json version. */
9
10
  const CEULEN_VERSION: string = (() => {
10
11
  try {
@@ -40,7 +41,10 @@ const ROUTER_PROVIDER = "router";
40
41
  const LEGACY_9ROUTER_PROVIDER = "9router";
41
42
  // pi-router (formerly pi-9router): URL lives in settings.json `router.baseUrl`
42
43
  // (env override ROUTER_BASE_URL), key in auth.json `router` credential.
43
- const ROUTER_SETTINGS_PATH = path.join(os.homedir(), ".pi", "agent", "settings.json");
44
+ // Resolves through PI_CODING_AGENT_DIR like piAuthPath() — a hardcoded
45
+ // ~/.pi/agent would fetch the WRONG endpoint in an alternate agent dir.
46
+ const routerSettingsPath = () =>
47
+ path.join(process.env.PI_CODING_AGENT_DIR?.trim() || path.join(os.homedir(), ".pi", "agent"), "settings.json");
44
48
  const COMMAND_CODE_PROVIDER = "commandcode";
45
49
  const COMMAND_CODE_USAGE_URL = "https://api.commandcode.ai/alpha/billing/credits";
46
50
 
@@ -134,7 +138,8 @@ export interface State {
134
138
  inFlight?: Promise<SubscriptionUsageSnapshot>;
135
139
  refreshTimer?: NodeJS.Timeout;
136
140
  debounceTimer?: NodeJS.Timeout;
137
- responseStartTime?: number;
141
+ /** performance.now() at before_provider_request — monotonic (Date.now() can step with NTP). */
142
+ responseStartPerf?: number;
138
143
  lastTokPerSec?: number;
139
144
  lastTokPerSecLabel?: string;
140
145
  cumulativeOutput: number;
@@ -276,15 +281,19 @@ function planLabel(plan: string | undefined): string | undefined {
276
281
  return labels[normalized] ?? plan;
277
282
  }
278
283
 
284
+ /** Remaining time until reset: hours keep minute precision (`2H3M`, OMP's
285
+ * formatUsageReset style), days stay coarse (`2D`), sub-minute rounds up. */
279
286
  function formatRemainingTime(resetAtSec: number | undefined): string | undefined {
280
287
  if (!resetAtSec) return undefined;
281
- const nowSec = Date.now() / 1000;
282
- const remainingSec = resetAtSec - nowSec;
288
+ const remainingSec = resetAtSec - Date.now() / 1000;
283
289
  if (remainingSec <= 0) return "0M";
284
290
  const remainingMin = Math.ceil(remainingSec / 60);
285
291
  if (remainingMin < 60) return `${remainingMin}M`;
286
- const remainingH = Math.ceil(remainingSec / 3600);
287
- if (remainingH < 24) return `${remainingH}H`;
292
+ if (remainingMin < 24 * 60) {
293
+ const h = Math.floor(remainingMin / 60);
294
+ const m = remainingMin % 60;
295
+ return m > 0 ? `${h}H${m}M` : `${h}H`;
296
+ }
288
297
  const remainingD = Math.ceil(remainingSec / 86400);
289
298
  return `${remainingD}D`;
290
299
  }
@@ -381,8 +390,8 @@ async function readZaiAuth(providerId: string, label: string): Promise<{ key: st
381
390
  function readRouterConfig(): { baseUrl: string } | null {
382
391
  try {
383
392
  let baseUrl = process.env.ROUTER_BASE_URL || process.env.NINE_ROUTER_BASE_URL;
384
- if (!baseUrl && fs.statSync(ROUTER_SETTINGS_PATH).isFile()) {
385
- const settings = JSON.parse(fs.readFileSync(ROUTER_SETTINGS_PATH, "utf8")) as Record<string, unknown>;
393
+ if (!baseUrl && fs.statSync(routerSettingsPath()).isFile()) {
394
+ const settings = JSON.parse(fs.readFileSync(routerSettingsPath(), "utf8")) as Record<string, unknown>;
386
395
  const router = settings.router as { baseUrl?: unknown } | undefined;
387
396
  if (typeof router?.baseUrl === "string" && router.baseUrl) baseUrl = router.baseUrl;
388
397
  }
@@ -1232,6 +1241,17 @@ function windowSegments(account: SubscriptionAccountSnapshot | undefined): strin
1232
1241
  return segments;
1233
1242
  }
1234
1243
 
1244
+ /** Compact status item for the composer band: provider label + quota windows
1245
+ * (e.g. `(router) R:59%/2H3M`). Cost/credits/tok/s stay out — those live in
1246
+ * /usage and the footer totals. */
1247
+ export function usageBandItem(account: SubscriptionAccountSnapshot | undefined, providerDisplayName: string | undefined): string | undefined {
1248
+ if (!account) return undefined;
1249
+ const label = providerDisplayName?.toLowerCase() === ROUTER_PROVIDER ? `(${ROUTER_PROVIDER})` : providerDisplayName?.toLowerCase();
1250
+ const windows = windowSegments(account).join(" ");
1251
+ if (!windows) return undefined;
1252
+ return label ? `${label} ${windows}` : windows;
1253
+ }
1254
+
1235
1255
  export function renderSubscriptionLine(state: State): void {
1236
1256
  // ponytail: resolve ctx at render time — any captured ctx goes stale on
1237
1257
  // session replacement (new/fork/switch/reload) and ctx.ui then throws.
@@ -1259,13 +1279,13 @@ export function renderSubscriptionLine(state: State): void {
1259
1279
  const windowParts = windowSegments(account);
1260
1280
  const accountPart = formatFooterAccount(account);
1261
1281
  const segments = accountPart ? [accountPart, ...windowParts] : [...windowParts];
1262
- const cost = state.cumulativeCost;
1263
1282
  const hasWindows = windowParts.length > 0;
1264
1283
  // Monthly balance (Command Code credits, router-reported balances):
1265
1284
  // currency-aware compact figure — e.g. M:$69.99 / M:¥88.00 CNY.
1266
1285
  if (typeof account?.monthlyCredits === "number") {
1267
1286
  segments.push(`M:${formatMonthlyCredits(account.monthlyCredits, account.creditsCurrency)}`);
1268
1287
  }
1288
+ const cost = state.cumulativeCost;
1269
1289
  if (cost > 0) segments.push(`$${cost.toFixed(2)}`);
1270
1290
  if (state.lastTokPerSec !== undefined) segments.push(`${state.lastTokPerSec} tok/s`);
1271
1291
  if (segments.length === 0) {
@@ -1278,6 +1298,21 @@ export function renderSubscriptionLine(state: State): void {
1278
1298
  const remaining = minRemaining(account);
1279
1299
  color = remaining <= 10 ? "error" : remaining <= 20 ? "warning" : "dim";
1280
1300
  }
1301
+ // Publish the compact band item (provider label + windows only) — the
1302
+ // composer renders it next to git; cost/credits/tok/s stay out (they live
1303
+ // in /usage and the footer totals). Errors/empty windows publish nothing so
1304
+ // the band drops the segment instead of showing a stale one. Tone mirrors
1305
+ // the setStatus color steps over the tightest window.
1306
+ if (!snapshot || snapshot.error) {
1307
+ setUsageItem({});
1308
+ } else {
1309
+ const remaining = minRemaining(snapshot.activeAccount);
1310
+ setUsageItem({
1311
+ provider: snapshot.providerDisplayName,
1312
+ windows: usageBandItem(snapshot.activeAccount, snapshot.providerDisplayName),
1313
+ tone: remaining <= 10 ? "error" : remaining <= 20 ? "warning" : "dim",
1314
+ });
1315
+ }
1281
1316
  ctx.ui.setStatus(STATUS_KEY, theme.fg(color, line));
1282
1317
  }
1283
1318
 
@@ -1833,6 +1868,19 @@ export default function (pi: ExtensionAPI) {
1833
1868
  // reload) before the session's other events, so mid-session handlers never
1834
1869
  // need to — and a late old-session event must not reinstall a stale ctx.
1835
1870
  state.ctx = ctx;
1871
+ resetGenRate(); // fresh session, fresh Generation Rate item
1872
+ resetUsageItem(); // ...and fresh usage windows
1873
+ // The cumulative figures are labelled "Session cost"/"Session avg" in
1874
+ // /usage, so they must not survive into the next session (/new, reload,
1875
+ // switch, fork). session_start fires before the new session's first
1876
+ // message_end, so an in-flight review of the old session cannot re-add
1877
+ // into these (its message_end precedes this handler).
1878
+ state.cumulativeCost = 0;
1879
+ state.cumulativeOutput = 0;
1880
+ state.cumulativeDurationMs = 0;
1881
+ state.responseStartPerf = undefined; // a request spanning the switch has no valid elapsed
1882
+ state.lastTokPerSec = undefined;
1883
+ state.lastTokPerSecLabel = undefined;
1836
1884
  updateActiveAdapter(state, ctx.model);
1837
1885
  if (state.adapter) deferRefresh(state, true);
1838
1886
  });
@@ -1843,7 +1891,7 @@ export default function (pi: ExtensionAPI) {
1843
1891
  });
1844
1892
 
1845
1893
  pi.on("before_provider_request", async (_event, _ctx) => {
1846
- state.responseStartTime = Date.now();
1894
+ state.responseStartPerf = performance.now();
1847
1895
  });
1848
1896
 
1849
1897
  pi.on("message_end", async (event, _ctx) => {
@@ -1853,16 +1901,21 @@ export default function (pi: ExtensionAPI) {
1853
1901
  // footer).
1854
1902
  const cost = Number((event.message.usage as any)?.cost?.total);
1855
1903
  if (Number.isFinite(cost) && cost > 0) state.cumulativeCost += cost;
1856
- if (state.responseStartTime) {
1904
+ if (state.responseStartPerf !== undefined) {
1857
1905
  // usage.output already includes reasoning tokens (Pi SDK contract) —
1858
1906
  // this is total tok/s in both thinking and normal mode.
1859
1907
  const output = (event.message.usage as any)?.output ?? 0;
1860
1908
  const reasoning = (event.message.usage as any)?.reasoning ?? 0;
1861
- const elapsed = Date.now() - state.responseStartTime;
1862
- state.responseStartTime = undefined;
1863
- if (elapsed > 0 && output > 0) {
1909
+ const elapsed = performance.now() - state.responseStartPerf;
1910
+ state.responseStartPerf = undefined;
1911
+ // 100ms floor (omp parity): a sub-floor reading is noise, e.g. a
1912
+ // 50-token continuation landing in 80ms would flash "625 tok/s".
1913
+ // Aborted/errored streams publish nothing — partial usage is not a rate.
1914
+ const stop = (event.message as { stopReason?: string }).stopReason;
1915
+ if (elapsed >= 100 && output > 0 && stop !== "aborted" && stop !== "error") {
1864
1916
  state.lastTokPerSec = Math.round(output / (elapsed / 1000));
1865
1917
  state.lastTokPerSecLabel = tokPerSecLabel(output, reasoning, elapsed);
1918
+ setGenRate({ tps: state.lastTokPerSec });
1866
1919
  state.cumulativeOutput += output;
1867
1920
  state.cumulativeDurationMs += elapsed;
1868
1921
  }
@@ -1873,7 +1926,7 @@ export default function (pi: ExtensionAPI) {
1873
1926
 
1874
1927
  pi.on("after_provider_response", async (event, _ctx) => {
1875
1928
  if (event.status >= 400) {
1876
- state.responseStartTime = undefined;
1929
+ state.responseStartPerf = undefined;
1877
1930
  }
1878
1931
  if (state.adapter) scheduleRefresh(state);
1879
1932
  });
@@ -1892,6 +1945,7 @@ export default function (pi: ExtensionAPI) {
1892
1945
  state.inFlight = undefined;
1893
1946
  state.refreshGeneration++;
1894
1947
  ctx.ui.setStatus(STATUS_KEY, undefined);
1948
+ resetUsageItem();
1895
1949
  state.ctx = undefined;
1896
1950
  });
1897
1951
 
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Generation Rate handoff: usage computes tok/s on message_end and publishes
3
+ * it to the shared store the composer renders. Reset per session.
4
+ */
5
+
6
+ import assert from "node:assert/strict";
7
+ import { test } from "node:test";
8
+ import extension from "../index.ts";
9
+ import { getGenRate } from "../../../lib/rate.js";
10
+
11
+ function makePi() {
12
+ const handlers: Record<string, (event: unknown, ctx: unknown) => Promise<void> | void> = {};
13
+ return {
14
+ handlers,
15
+ on(type: string, fn: (event: unknown, ctx: unknown) => Promise<void> | void) {
16
+ handlers[type] = fn;
17
+ },
18
+ registerCommand() {},
19
+ } as never;
20
+ }
21
+
22
+ const stubCtx = {
23
+ signal: undefined,
24
+ model: { provider: "ollama", id: "llama" }, // unsupported → no fetch/timer
25
+ ui: { theme: { fg: (_c: string, s: string) => s }, setStatus() {}, notify() {} },
26
+ getContextUsage: () => undefined,
27
+ } as never;
28
+
29
+ test("message_end publishes tok/s to the shared rate store; session_start resets it", async () => {
30
+ const pi = makePi() as { handlers: Record<string, (e: unknown, c: never) => Promise<void> | void> };
31
+ extension(pi);
32
+
33
+ await pi.handlers.session_start!({ reason: "new" }, stubCtx);
34
+ assert.equal(getGenRate().tps, undefined, "fresh session starts with no rate");
35
+
36
+ await pi.handlers.before_provider_request!({}, stubCtx);
37
+ await new Promise((r) => setTimeout(r, 110)); // clear the 100ms noise floor
38
+ const usage = { output: 1000, reasoning: 400, cost: { total: 0 } };
39
+ await pi.handlers.message_end!({ message: { role: "assistant", usage } }, stubCtx);
40
+ const tps = getGenRate().tps;
41
+ assert.ok(typeof tps === "number" && tps > 0, `rate published (${tps})`);
42
+
43
+ await pi.handlers.session_start!({ reason: "new" }, stubCtx);
44
+ assert.equal(getGenRate().tps, undefined, "new session clears the previous rate");
45
+ });
46
+
47
+ test("tok/s guards: sub-floor duration and aborted/errored streams publish nothing", async () => {
48
+ const pi = makePi() as { handlers: Record<string, (e: unknown, c: never) => Promise<void> | void> };
49
+ extension(pi);
50
+
51
+ await pi.handlers.session_start!({ reason: "new" }, stubCtx);
52
+ const usage = { output: 1000, reasoning: 0, cost: { total: 0 } };
53
+
54
+ // Sub-floor: fast continuation would otherwise flash a huge rate.
55
+ await pi.handlers.before_provider_request!({}, stubCtx);
56
+ await pi.handlers.message_end!({ message: { role: "assistant", usage } }, stubCtx);
57
+ assert.equal(getGenRate().tps, undefined, "<100ms elapsed is noise, not a rate");
58
+
59
+ // Aborted partial: accumulated output is not a rate either.
60
+ await pi.handlers.before_provider_request!({}, stubCtx);
61
+ await new Promise((r) => setTimeout(r, 110));
62
+ await pi.handlers.message_end!({ message: { role: "assistant", stopReason: "aborted", usage } }, stubCtx);
63
+ assert.equal(getGenRate().tps, undefined, "aborted stream publishes nothing");
64
+
65
+ // Errored stream.
66
+ await pi.handlers.before_provider_request!({}, stubCtx);
67
+ await new Promise((r) => setTimeout(r, 110));
68
+ await pi.handlers.message_end!({ message: { role: "assistant", stopReason: "error", usage } }, stubCtx);
69
+ assert.equal(getGenRate().tps, undefined, "errored stream publishes nothing");
70
+ });
@@ -8,11 +8,24 @@ import {
8
8
  tokPerSecLabel,
9
9
  formatMonthlyCredits,
10
10
  jwtExpired,
11
+ usageBandItem,
11
12
  } from "../index.ts";
12
13
  import { parseEnvText } from "../../../lib/env.ts";
13
14
 
14
15
  // ── parseOmniUsageText — OmniRoute /api/usage/om-usage free-text report ──────
15
16
 
17
+ test("usageBandItem: router renders the short (router) label + windows", () => {
18
+ const item = usageBandItem(
19
+ { fiveHour: { remaining: 59, remainingLabel: "2H3M" }, weekly: { remaining: 99, remainingLabel: "2D" } },
20
+ "Router",
21
+ );
22
+ assert.equal(item, "(router) R:59%/2H3M W:99%/2D");
23
+ // Non-router providers keep their display name, lowercased.
24
+ assert.equal(usageBandItem({ fiveHour: { remaining: 80, remainingLabel: "3H" } }, "Z.ai"), "z.ai R:80%/3H");
25
+ // No windows → no item (the band drops the segment entirely).
26
+ assert.equal(usageBandItem({}, "Router"), undefined);
27
+ assert.equal(usageBandItem(undefined, "Router"), undefined);
28
+ });
16
29
  test("om-usage: full report parses all four windows", () => {
17
30
  const p = parseOmniUsageText(
18
31
  [
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Session-scoped accumulators: /usage labels these figures "Session cost" and
3
+ * "Session avg", so they must not survive session_start (/new, reload, switch,
4
+ * fork) — before the fix they were created once at module load and kept
5
+ * accumulating, so the second session reported the first session's cost.
6
+ *
7
+ * Unsupported provider ("ollama") on purpose: no adapter, so no refresh timer
8
+ * is armed (no open handles) and renderSubscriptionLine takes the tok/s branch.
9
+ */
10
+
11
+ import assert from "node:assert/strict";
12
+ import { test } from "node:test";
13
+ import extension, { renderSubscriptionLine, type State } from "../index.ts";
14
+
15
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
16
+
17
+ function harness() {
18
+ const handlers: Record<string, (event: any, ctx: any) => any> = {};
19
+ const statuses: (string | undefined)[] = [];
20
+ const pi = {
21
+ on(type: string, fn: any) {
22
+ handlers[type] = fn;
23
+ },
24
+ registerCommand() {},
25
+ registerMessageRenderer() {},
26
+ };
27
+ const ctx = {
28
+ model: { provider: "ollama", id: "llama" }, // unsupported → no adapter, no timer
29
+ isProjectTrusted: () => false,
30
+ ui: {
31
+ theme: { fg: (_c: string, s: string) => s },
32
+ setStatus(_key: string, value?: string) {
33
+ statuses.push(value);
34
+ },
35
+ notify() {},
36
+ },
37
+ getContextUsage: () => undefined,
38
+ };
39
+ const state = extension(pi as never) as State;
40
+ /** One assistant response: publishes tok/s and accumulates the session figures. */
41
+ const respond = async (cost: number) => {
42
+ await handlers.before_provider_request!({}, ctx);
43
+ await sleep(110); // clear the 100ms noise floor
44
+ await handlers.message_end!({ message: { role: "assistant", usage: { output: 1000, reasoning: 400, cost: { total: cost } } } }, ctx);
45
+ };
46
+ return { handlers, ctx, state, statuses, respond };
47
+ }
48
+
49
+ test("session_start resets the session cost/avg accumulators (a second session never inherits the first)", async () => {
50
+ const h = harness();
51
+ await h.handlers.session_start!({ reason: "startup" }, h.ctx);
52
+ assert.equal(h.state.cumulativeCost, 0, "fresh session starts at zero cost");
53
+
54
+ await h.respond(0.05);
55
+ assert.ok(h.state.cumulativeCost > 0, "cost accumulates within the session");
56
+ assert.ok(h.state.cumulativeOutput > 0 && h.state.cumulativeDurationMs > 0, "tok/s samples accumulate the session average");
57
+ assert.ok(h.state.lastTokPerSec !== undefined, "last response rate published");
58
+
59
+ // The /usage footer/session-avg surface reads these fields directly.
60
+ renderSubscriptionLine(h.state);
61
+ assert.match(String(h.statuses.at(-1)), /tok\/s/, "last response rate rendered before the switch");
62
+
63
+ // /new (or reload/switch/fork): the accumulators must reset with the session.
64
+ await h.handlers.session_start!({ reason: "new" }, h.ctx);
65
+ assert.equal(h.state.cumulativeCost, 0, "session cost reset — not the previous session's total");
66
+ assert.equal(h.state.cumulativeOutput, 0, "session output reset");
67
+ assert.equal(h.state.cumulativeDurationMs, 0, "session duration reset");
68
+ assert.equal(h.state.lastTokPerSec, undefined, "last-response rate cleared with the session");
69
+ assert.equal(h.state.lastTokPerSecLabel, undefined, "last-response label cleared too (it belongs to the old session)");
70
+ assert.equal(h.state.responseStartPerf, undefined, "no half-measured request carried across the switch");
71
+
72
+ renderSubscriptionLine(h.state);
73
+ assert.equal(h.state.cumulativeCost, 0);
74
+ const last = String(h.statuses.at(-1));
75
+ assert.ok(!/Session avg|tok\/s/.test(last), `session-scoped tok/s surfaces gone after the switch (got ${JSON.stringify(last)})`);
76
+
77
+ // Positive control: the reset is per SESSION, not per message — the new
78
+ // session accumulates its own figures normally. (No separate lifetime/aggregate
79
+ // counter exists in State, so the reset has nothing else to clobber: cost,
80
+ // output, duration and the last-response rate are all session-scoped.)
81
+ await h.respond(0.01);
82
+ assert.ok(h.state.cumulativeCost > 0 && h.state.cumulativeCost < 0.02, "the new session counts only its own cost");
83
+ await h.respond(0.01);
84
+ assert.ok(h.state.cumulativeCost > 0.015, "messages within one session still accumulate");
85
+ });
@@ -0,0 +1,24 @@
1
+ upstream-url: https://github.com/bacnh85/pi-extensions (pi-ux package)
2
+ upstream-version: 0.6.6
3
+ fork-date: 2026-10-01
4
+ fork-source: /Volumes/Dev/agents/pi-extensions/pi-ux @ 0.6.6
5
+
6
+ # Port of pi-ux 0.6.6 into the ceulen ux module:
7
+ # - hooks/ux-audit.js → lib/audit.ts (CJS → ESM TS, logic verbatim)
8
+ # - hooks/ux-config.js → lib/config.ts (getHideStatus dropped — no status bar)
9
+ # - hooks/ux-instructions.js → lib/instructions.ts (SKILL.md path → package skills/)
10
+ # - extensions/index.js → index.ts
11
+ # - skills/ux-{design,capture,presets,routing} → package skills/ (upstream content)
12
+ #
13
+ # Deliberate divergences from upstream:
14
+ # - NO status bar: no setStatus, no agent_start/agent_end sync, no hideStatus
15
+ # setting/env (PI_UX_HIDE_STATUS is ignored).
16
+ # - Bare /ux reports status instead of resetting to the default (ponytail #99
17
+ # precedent, same as ceulen's ponytail module).
18
+ # - /ux default <mode> subcommand dropped — the default mode is owned by the
19
+ # central /config panel (ux.defaultMode row) writing via writeDefaultMode.
20
+ # - parseUxCommand/parse API mirrors ceulen's ponytail (status/set-mode/invalid).
21
+ #
22
+ # Config contract preserved from upstream: ~/.config/pi-ux/config.json
23
+ # (defaultMode, quietStartup) + PI_UX_DEFAULT_MODE / PI_UX_QUIET_STARTUP env
24
+ # overrides — existing pi-ux users keep their settings across the port.