@odysx/codemind 0.0.0-stage → 0.1.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 (331) hide show
  1. package/README.md +293 -2
  2. package/dist/commands/agents.d.ts +2 -0
  3. package/dist/commands/agents.d.ts.map +1 -0
  4. package/dist/commands/agents.js +91 -0
  5. package/dist/commands/agents.js.map +1 -0
  6. package/dist/commands/auth.d.ts +2 -0
  7. package/dist/commands/auth.d.ts.map +1 -0
  8. package/dist/commands/auth.js +35 -0
  9. package/dist/commands/auth.js.map +1 -0
  10. package/dist/commands/chat.d.ts +2 -0
  11. package/dist/commands/chat.d.ts.map +1 -0
  12. package/dist/commands/chat.js +180 -0
  13. package/dist/commands/chat.js.map +1 -0
  14. package/dist/commands/keys.d.ts +2 -0
  15. package/dist/commands/keys.d.ts.map +1 -0
  16. package/dist/commands/keys.js +81 -0
  17. package/dist/commands/keys.js.map +1 -0
  18. package/dist/commands/local.d.ts +2 -0
  19. package/dist/commands/local.d.ts.map +1 -0
  20. package/dist/commands/local.js +325 -0
  21. package/dist/commands/local.js.map +1 -0
  22. package/dist/commands/mcp.d.ts +2 -0
  23. package/dist/commands/mcp.d.ts.map +1 -0
  24. package/dist/commands/mcp.js +73 -0
  25. package/dist/commands/mcp.js.map +1 -0
  26. package/dist/commands/prompts.d.ts +2 -0
  27. package/dist/commands/prompts.d.ts.map +1 -0
  28. package/dist/commands/prompts.js +59 -0
  29. package/dist/commands/prompts.js.map +1 -0
  30. package/dist/commands/skills.d.ts +2 -0
  31. package/dist/commands/skills.d.ts.map +1 -0
  32. package/dist/commands/skills.js +41 -0
  33. package/dist/commands/skills.js.map +1 -0
  34. package/dist/core/auth/index.d.ts +10 -0
  35. package/dist/core/auth/index.d.ts.map +1 -0
  36. package/dist/core/auth/index.js +82 -0
  37. package/dist/core/auth/index.js.map +1 -0
  38. package/dist/core/config/index.d.ts +47 -0
  39. package/dist/core/config/index.d.ts.map +1 -0
  40. package/dist/core/config/index.js +118 -0
  41. package/dist/core/config/index.js.map +1 -0
  42. package/dist/core/history.d.ts +14 -0
  43. package/dist/core/history.d.ts.map +1 -0
  44. package/dist/core/history.js +80 -0
  45. package/dist/core/history.js.map +1 -0
  46. package/dist/core/markdown-renderer.d.ts +47 -0
  47. package/dist/core/markdown-renderer.d.ts.map +1 -0
  48. package/dist/core/markdown-renderer.js +385 -0
  49. package/dist/core/markdown-renderer.js.map +1 -0
  50. package/dist/core/permissions/index.d.ts +31 -0
  51. package/dist/core/permissions/index.d.ts.map +1 -0
  52. package/dist/core/permissions/index.js +64 -0
  53. package/dist/core/permissions/index.js.map +1 -0
  54. package/dist/core/provider/external.d.ts +28 -0
  55. package/dist/core/provider/external.d.ts.map +1 -0
  56. package/dist/core/provider/external.js +248 -0
  57. package/dist/core/provider/external.js.map +1 -0
  58. package/dist/core/provider/index.d.ts +96 -0
  59. package/dist/core/provider/index.d.ts.map +1 -0
  60. package/dist/core/provider/index.js +423 -0
  61. package/dist/core/provider/index.js.map +1 -0
  62. package/dist/core/registry/index.d.ts +25 -0
  63. package/dist/core/registry/index.d.ts.map +1 -0
  64. package/dist/core/registry/index.js +216 -0
  65. package/dist/core/registry/index.js.map +1 -0
  66. package/dist/core/schema/types.d.ts +93 -0
  67. package/dist/core/schema/types.d.ts.map +1 -0
  68. package/dist/core/schema/types.js +12 -0
  69. package/dist/core/schema/types.js.map +1 -0
  70. package/dist/core/terminal.d.ts +40 -0
  71. package/dist/core/terminal.d.ts.map +1 -0
  72. package/dist/core/terminal.js +134 -0
  73. package/dist/core/terminal.js.map +1 -0
  74. package/dist/core/workspace/index.d.ts +35 -0
  75. package/dist/core/workspace/index.d.ts.map +1 -0
  76. package/dist/core/workspace/index.js +194 -0
  77. package/dist/core/workspace/index.js.map +1 -0
  78. package/dist/index.d.ts +10 -0
  79. package/dist/index.d.ts.map +1 -0
  80. package/dist/index.js +393 -0
  81. package/dist/index.js.map +1 -0
  82. package/dist/ui/app.d.ts +3 -0
  83. package/dist/ui/app.d.ts.map +1 -0
  84. package/dist/ui/app.js +554 -0
  85. package/dist/ui/app.js.map +1 -0
  86. package/dist/ui/commands/cases/catalog.d.ts +11 -0
  87. package/dist/ui/commands/cases/catalog.d.ts.map +1 -0
  88. package/dist/ui/commands/cases/catalog.js +62 -0
  89. package/dist/ui/commands/cases/catalog.js.map +1 -0
  90. package/dist/ui/commands/cases/misc.d.ts +35 -0
  91. package/dist/ui/commands/cases/misc.d.ts.map +1 -0
  92. package/dist/ui/commands/cases/misc.js +245 -0
  93. package/dist/ui/commands/cases/misc.js.map +1 -0
  94. package/dist/ui/commands/cases/tasks.d.ts +13 -0
  95. package/dist/ui/commands/cases/tasks.d.ts.map +1 -0
  96. package/dist/ui/commands/cases/tasks.js +91 -0
  97. package/dist/ui/commands/cases/tasks.js.map +1 -0
  98. package/dist/ui/commands/runCommand.d.ts +22 -0
  99. package/dist/ui/commands/runCommand.d.ts.map +1 -0
  100. package/dist/ui/commands/runCommand.js +136 -0
  101. package/dist/ui/commands/runCommand.js.map +1 -0
  102. package/dist/ui/components/AgentPicker.d.ts +11 -0
  103. package/dist/ui/components/AgentPicker.d.ts.map +1 -0
  104. package/dist/ui/components/AgentPicker.js +7 -0
  105. package/dist/ui/components/AgentPicker.js.map +1 -0
  106. package/dist/ui/components/AuthPicker.d.ts +14 -0
  107. package/dist/ui/components/AuthPicker.d.ts.map +1 -0
  108. package/dist/ui/components/AuthPicker.js +7 -0
  109. package/dist/ui/components/AuthPicker.js.map +1 -0
  110. package/dist/ui/components/Banner.d.ts +8 -0
  111. package/dist/ui/components/Banner.d.ts.map +1 -0
  112. package/dist/ui/components/Banner.js +24 -0
  113. package/dist/ui/components/Banner.js.map +1 -0
  114. package/dist/ui/components/CommandMenu.d.ts +17 -0
  115. package/dist/ui/components/CommandMenu.d.ts.map +1 -0
  116. package/dist/ui/components/CommandMenu.js +21 -0
  117. package/dist/ui/components/CommandMenu.js.map +1 -0
  118. package/dist/ui/components/ErrorBoundary.d.ts +24 -0
  119. package/dist/ui/components/ErrorBoundary.d.ts.map +1 -0
  120. package/dist/ui/components/ErrorBoundary.js +51 -0
  121. package/dist/ui/components/ErrorBoundary.js.map +1 -0
  122. package/dist/ui/components/InputBar.d.ts +28 -0
  123. package/dist/ui/components/InputBar.d.ts.map +1 -0
  124. package/dist/ui/components/InputBar.js +108 -0
  125. package/dist/ui/components/InputBar.js.map +1 -0
  126. package/dist/ui/components/KeysPanel.d.ts +12 -0
  127. package/dist/ui/components/KeysPanel.d.ts.map +1 -0
  128. package/dist/ui/components/KeysPanel.js +25 -0
  129. package/dist/ui/components/KeysPanel.js.map +1 -0
  130. package/dist/ui/components/MessageView.d.ts +29 -0
  131. package/dist/ui/components/MessageView.d.ts.map +1 -0
  132. package/dist/ui/components/MessageView.js +107 -0
  133. package/dist/ui/components/MessageView.js.map +1 -0
  134. package/dist/ui/components/PermissionPrompt.d.ts +10 -0
  135. package/dist/ui/components/PermissionPrompt.d.ts.map +1 -0
  136. package/dist/ui/components/PermissionPrompt.js +4 -0
  137. package/dist/ui/components/PermissionPrompt.js.map +1 -0
  138. package/dist/ui/components/Pickers.d.ts +43 -0
  139. package/dist/ui/components/Pickers.d.ts.map +1 -0
  140. package/dist/ui/components/Pickers.js +33 -0
  141. package/dist/ui/components/Pickers.js.map +1 -0
  142. package/dist/ui/components/SearchOverlay.d.ts +21 -0
  143. package/dist/ui/components/SearchOverlay.d.ts.map +1 -0
  144. package/dist/ui/components/SearchOverlay.js +14 -0
  145. package/dist/ui/components/SearchOverlay.js.map +1 -0
  146. package/dist/ui/components/SessionPicker.d.ts +12 -0
  147. package/dist/ui/components/SessionPicker.d.ts.map +1 -0
  148. package/dist/ui/components/SessionPicker.js +8 -0
  149. package/dist/ui/components/SessionPicker.js.map +1 -0
  150. package/dist/ui/components/WorkingIndicator.d.ts +10 -0
  151. package/dist/ui/components/WorkingIndicator.d.ts.map +1 -0
  152. package/dist/ui/components/WorkingIndicator.js +23 -0
  153. package/dist/ui/components/WorkingIndicator.js.map +1 -0
  154. package/dist/ui/controls/ApiKeyEntry.d.ts +8 -0
  155. package/dist/ui/controls/ApiKeyEntry.d.ts.map +1 -0
  156. package/dist/ui/controls/ApiKeyEntry.js +5 -0
  157. package/dist/ui/controls/ApiKeyEntry.js.map +1 -0
  158. package/dist/ui/controls/MultiSelect.d.ts +18 -0
  159. package/dist/ui/controls/MultiSelect.d.ts.map +1 -0
  160. package/dist/ui/controls/MultiSelect.js +9 -0
  161. package/dist/ui/controls/MultiSelect.js.map +1 -0
  162. package/dist/ui/hooks/useAgentPicker.d.ts +14 -0
  163. package/dist/ui/hooks/useAgentPicker.d.ts.map +1 -0
  164. package/dist/ui/hooks/useAgentPicker.js +53 -0
  165. package/dist/ui/hooks/useAgentPicker.js.map +1 -0
  166. package/dist/ui/hooks/useAuthFlow.d.ts +14 -0
  167. package/dist/ui/hooks/useAuthFlow.d.ts.map +1 -0
  168. package/dist/ui/hooks/useAuthFlow.js +31 -0
  169. package/dist/ui/hooks/useAuthFlow.js.map +1 -0
  170. package/dist/ui/hooks/useKeysFlow.d.ts +17 -0
  171. package/dist/ui/hooks/useKeysFlow.d.ts.map +1 -0
  172. package/dist/ui/hooks/useKeysFlow.js +130 -0
  173. package/dist/ui/hooks/useKeysFlow.js.map +1 -0
  174. package/dist/ui/hooks/useSessionPicker.d.ts +29 -0
  175. package/dist/ui/hooks/useSessionPicker.d.ts.map +1 -0
  176. package/dist/ui/hooks/useSessionPicker.js +58 -0
  177. package/dist/ui/hooks/useSessionPicker.js.map +1 -0
  178. package/dist/ui/hooks/useTerminalSize.d.ts +6 -0
  179. package/dist/ui/hooks/useTerminalSize.d.ts.map +1 -0
  180. package/dist/ui/hooks/useTerminalSize.js +29 -0
  181. package/dist/ui/hooks/useTerminalSize.js.map +1 -0
  182. package/dist/ui/input/keyRouter.d.ts +125 -0
  183. package/dist/ui/input/keyRouter.d.ts.map +1 -0
  184. package/dist/ui/input/keyRouter.js +574 -0
  185. package/dist/ui/input/keyRouter.js.map +1 -0
  186. package/dist/ui/layouts/ScreenLayout.d.ts +98 -0
  187. package/dist/ui/layouts/ScreenLayout.d.ts.map +1 -0
  188. package/dist/ui/layouts/ScreenLayout.js +56 -0
  189. package/dist/ui/layouts/ScreenLayout.js.map +1 -0
  190. package/dist/ui/shared/types.d.ts +143 -0
  191. package/dist/ui/shared/types.d.ts.map +1 -0
  192. package/dist/ui/shared/types.js +38 -0
  193. package/dist/ui/shared/types.js.map +1 -0
  194. package/dist/ui/theme.d.ts +29 -0
  195. package/dist/ui/theme.d.ts.map +1 -0
  196. package/dist/ui/theme.js +54 -0
  197. package/dist/ui/theme.js.map +1 -0
  198. package/dist/ui/utils/markdown.d.ts +74 -0
  199. package/dist/ui/utils/markdown.d.ts.map +1 -0
  200. package/dist/ui/utils/markdown.js +187 -0
  201. package/dist/ui/utils/markdown.js.map +1 -0
  202. package/dist/ui/utils/mentions.d.ts +12 -0
  203. package/dist/ui/utils/mentions.d.ts.map +1 -0
  204. package/dist/ui/utils/mentions.js +28 -0
  205. package/dist/ui/utils/mentions.js.map +1 -0
  206. package/dist/ui/utils/terminal-text.d.ts +33 -0
  207. package/dist/ui/utils/terminal-text.d.ts.map +1 -0
  208. package/dist/ui/utils/terminal-text.js +123 -0
  209. package/dist/ui/utils/terminal-text.js.map +1 -0
  210. package/dist/ui/utils/text.d.ts +72 -0
  211. package/dist/ui/utils/text.d.ts.map +1 -0
  212. package/dist/ui/utils/text.js +171 -0
  213. package/dist/ui/utils/text.js.map +1 -0
  214. package/eslint.config.js +40 -0
  215. package/graphify-out/GRAPH_REPORT.md +140 -0
  216. package/graphify-out/cache/1236b1806943f8eb5c64fece9fb448149370f4a1b52b32f0977ad528d7911291.json +1 -0
  217. package/graphify-out/cache/15cbf641dcc0fd641c18da872214918203a1f64baa7ac8430e4702ef32d18b02.json +1 -0
  218. package/graphify-out/cache/1abc52745bb46f6cc5a528530e2bc1f368c26e348dff85cdde5cad6f275d7177.json +1 -0
  219. package/graphify-out/cache/1c7815c37c13177e98895e272285f6151a8d0807478fc843ec452634b3e9912d.json +1 -0
  220. package/graphify-out/cache/1ec38c39f044f329c78642b61d6394fb8e15d0014335f32947d1f5c7b88c02bc.json +1 -0
  221. package/graphify-out/cache/20c9b57ff76dbb9d57cbd00659b0a42d2b28dd2abacf1ef4143cc67a5b6fe7f4.json +1 -0
  222. package/graphify-out/cache/285e11876884eb619e779d540cd957b33e70f14c67ecc26c9b9755aa9cedd717.json +1 -0
  223. package/graphify-out/cache/2c0a9c49ab51f4e0f07543b4e941bf802b7db31fa607c4cee8e595575be68fe7.json +1 -0
  224. package/graphify-out/cache/3025e6c2756c79ccaadd51d611f25a8b6630a6a11ce1b4e6e261b3e033dc194f.json +1 -0
  225. package/graphify-out/cache/4801a686ddfa0a52824a4fc3d65443cbb0ab9f0b030af67d02fccb520c584a08.json +1 -0
  226. package/graphify-out/cache/4f8fd96f38aa7d0293b4fab60c4581c4f3e68f4533c664c9cd78d1c53bea1cba.json +1 -0
  227. package/graphify-out/cache/5928e562b0f5700184b810e2403f4aa685e2b93c3c584c10460562b514c40fdd.json +1 -0
  228. package/graphify-out/cache/66132486efb0a4cfaeea766448f1f15bb33635808714052e7e24e5b00fbc984f.json +1 -0
  229. package/graphify-out/cache/66ab27669e7ec685130063662af9f30018c267f7639b4af4b0504a98282c383a.json +1 -0
  230. package/graphify-out/cache/6ff6b3dd433b5ffe96e166263a203dd622397e419dc00bb676824988b7defeab.json +1 -0
  231. package/graphify-out/cache/7a00a49932177a6215e2590b1ddfd6f1d8494792f693068e9d427d16b165d370.json +1 -0
  232. package/graphify-out/cache/7b681bc5182f40f707f1c0b16b78af38efffa62a1df315d10878f4de888408ef.json +1 -0
  233. package/graphify-out/cache/81196d44e50ac0b276d826a531ed10c425a528b298e3fe18e8d5a3eec996e9d5.json +1 -0
  234. package/graphify-out/cache/8934e9b32dea6e66fdc34fa1681b287ff1335c389917e0fc6ee2fc573e23e87b.json +1 -0
  235. package/graphify-out/cache/975f6c99807f86b79c80ca40c783618e2080a927eaebe6ea3db37b869f048851.json +1 -0
  236. package/graphify-out/cache/9ab98f08626fd8190462595e38de828293ad184db8df5e1177b05a8fe290faa1.json +1 -0
  237. package/graphify-out/cache/9c434a6796d7932b6e87a908c155c09cb2b8d097fc55f141f0302b6600f94749.json +1 -0
  238. package/graphify-out/cache/ac5cf4c489dc417c1f6ea728d0b6ba12ac7087bc6c2e736697ff3024b4d4e534.json +1 -0
  239. package/graphify-out/cache/ae5083b5c1dca3e5c6af485e7f6eb8a08ff8b382cdecf92ab5e0902053442afe.json +1 -0
  240. package/graphify-out/cache/b274057fc2e0118cf2746d1d8060841122bb2a2b0305566fc3f32d3a51e08bcc.json +1 -0
  241. package/graphify-out/cache/b39beef31da682387f030c0d149f6cd5b3e66effbf936cc8430db15360759dda.json +1 -0
  242. package/graphify-out/cache/bf3c6a36bb72820bc11cbf4a5c49067d1f62013d4686c019a4dbd9951b1e980e.json +1 -0
  243. package/graphify-out/cache/c034e156028d1a58b89bce659726e9a4065ddc4d2b560d6bce7a206fdff8dad3.json +1 -0
  244. package/graphify-out/cache/c619b5bbe8d1f427fbd7816d1e9fcfaf90d7201b020ae6b578166aeb9cb20683.json +1 -0
  245. package/graphify-out/cache/c8db77a9da0b0f601acfa50a620f31155cdda0d0cc0f2285adcea19e77194ee6.json +1 -0
  246. package/graphify-out/cache/ca664791ec7741a2077d9e7c10384142d30e7a3b77b388df719c315da608d57d.json +1 -0
  247. package/graphify-out/cache/cba43a116186bd55c8a63368dea4eee4a8123b2bec0a42df6efb3254f89f9a7a.json +1 -0
  248. package/graphify-out/cache/cd51cbb3dad1cf34417b9761fe2eb184a9f57d23dc86e45630e63bfa2ecafddc.json +1 -0
  249. package/graphify-out/cache/d06738cde193b34a136b94104220c17e0212b814b3e4d7ff399105635cae1a03.json +1 -0
  250. package/graphify-out/cache/d093c19f0169c0398eeb1360895b1c16ecc50abc59f4be8eec3f6fd27c89a6e5.json +1 -0
  251. package/graphify-out/cache/da8f75c438531d232fe114d5cbf2374576ce842a5fb87c7e5a88b78fdb334e5e.json +1 -0
  252. package/graphify-out/cache/e35798fa04ddede548a6953bdea506bd7d0788dfed4e8a8ea6ae77b1b60ef5e0.json +1 -0
  253. package/graphify-out/cache/e5a38c254719000487098782125e15e2e982c07d66b99d359ed1781f30f9fc8c.json +1 -0
  254. package/graphify-out/cache/e6e4c4a5a7200ee0154585b5d6538f699b0a746dbded3164f8391f06ce7cb212.json +1 -0
  255. package/graphify-out/cache/ea8d0838df6309b673b031f616b253af957898ee7289d25a541fa6183b732e4e.json +1 -0
  256. package/graphify-out/cache/ebaee92b0e881efd7a08f3143e2c1803310396b4651d4f77532003c699cc6836.json +1 -0
  257. package/graphify-out/cache/edf8543318a9e60d56d04704078da6c37202ddd6fdfc83144fe2b94fe19b80ef.json +1 -0
  258. package/graphify-out/cache/efca19d3668035f11126fc9eccbeab290abfa94babf3f9a8706de81d17aba263.json +1 -0
  259. package/graphify-out/cache/f1480bb642025ebd6d99986cdd8a7d5726897ec038300e4b095c9c938435dfad.json +1 -0
  260. package/graphify-out/cache/f459f21277f03865f732affb175b1b092954dae5967f27b3cd1864466e3e24f4.json +1 -0
  261. package/graphify-out/cache/f899e37e864010b30f4c196e86082d7bd022a0df032005e0407883ebcec36514.json +1 -0
  262. package/graphify-out/cache/fb3cbe07fbcd97c536cff9c6bc343c35f22d49613f05c53ad30ef67a75c5d93e.json +1 -0
  263. package/graphify-out/cache/fd3dc682b1ca2f5ae03b50d6b0e045ae50f5701c0a21c5a388d77ef482939d3a.json +1 -0
  264. package/graphify-out/graph.html +257 -0
  265. package/graphify-out/graph.json +4396 -0
  266. package/package.json +45 -6
  267. package/scripts/e2e-external.mjs +65 -0
  268. package/scripts/live-agents.mjs +6 -0
  269. package/scripts/live-stream.mjs +51 -0
  270. package/src/commands/agents.ts +91 -0
  271. package/src/commands/auth.ts +39 -0
  272. package/src/commands/chat.ts +198 -0
  273. package/src/commands/keys.ts +83 -0
  274. package/src/commands/local.ts +302 -0
  275. package/src/commands/mcp.ts +74 -0
  276. package/src/commands/prompts.ts +58 -0
  277. package/src/commands/skills.ts +43 -0
  278. package/src/core/auth/index.ts +101 -0
  279. package/src/core/config/index.ts +152 -0
  280. package/src/core/history.ts +79 -0
  281. package/src/core/markdown-renderer.ts +420 -0
  282. package/src/core/permissions/index.ts +99 -0
  283. package/src/core/provider/external.ts +312 -0
  284. package/src/core/provider/index.ts +517 -0
  285. package/src/core/registry/index.ts +250 -0
  286. package/src/core/schema/types.ts +106 -0
  287. package/src/core/terminal.ts +124 -0
  288. package/src/core/workspace/index.ts +216 -0
  289. package/src/index.ts +401 -0
  290. package/src/ui/app.tsx +644 -0
  291. package/src/ui/commands/cases/catalog.ts +76 -0
  292. package/src/ui/commands/cases/misc.ts +293 -0
  293. package/src/ui/commands/cases/tasks.ts +115 -0
  294. package/src/ui/commands/runCommand.ts +178 -0
  295. package/src/ui/components/Banner.tsx +63 -0
  296. package/src/ui/components/CommandMenu.tsx +63 -0
  297. package/src/ui/components/ErrorBoundary.tsx +75 -0
  298. package/src/ui/components/InputBar.tsx +227 -0
  299. package/src/ui/components/KeysPanel.tsx +115 -0
  300. package/src/ui/components/MessageView.tsx +226 -0
  301. package/src/ui/components/Pickers.tsx +234 -0
  302. package/src/ui/components/SearchOverlay.tsx +65 -0
  303. package/src/ui/components/WorkingIndicator.tsx +35 -0
  304. package/src/ui/controls/ApiKeyEntry.tsx +29 -0
  305. package/src/ui/controls/MultiSelect.tsx +55 -0
  306. package/src/ui/hooks/useAgentPicker.ts +64 -0
  307. package/src/ui/hooks/useAuthFlow.ts +47 -0
  308. package/src/ui/hooks/useKeysFlow.ts +157 -0
  309. package/src/ui/hooks/useSessionPicker.ts +84 -0
  310. package/src/ui/hooks/useTerminalSize.ts +36 -0
  311. package/src/ui/input/keyRouter.ts +627 -0
  312. package/src/ui/layouts/ScreenLayout.tsx +202 -0
  313. package/src/ui/shared/types.ts +160 -0
  314. package/src/ui/theme.ts +53 -0
  315. package/src/ui/utils/markdown.ts +255 -0
  316. package/src/ui/utils/mentions.ts +40 -0
  317. package/src/ui/utils/terminal-text.ts +130 -0
  318. package/src/ui/utils/text.ts +174 -0
  319. package/test/commands.test.mjs +127 -0
  320. package/test/config.test.mjs +123 -0
  321. package/test/history.test.mjs +42 -0
  322. package/test/keyrouter.test.mjs +324 -0
  323. package/test/layout.test.mjs +271 -0
  324. package/test/markdown.test.mjs +92 -0
  325. package/test/mentions.test.mjs +51 -0
  326. package/test/permissions.test.mjs +130 -0
  327. package/test/provider.test.mjs +287 -0
  328. package/test/terminal-text.test.mjs +116 -0
  329. package/test/text.test.mjs +134 -0
  330. package/test/workspace.test.mjs +101 -0
  331. package/tsconfig.json +32 -0
@@ -0,0 +1,202 @@
1
+ /**
2
+ * ScreenLayout — the REPL's vertical composition, top → bottom:
3
+ * static transcript · live reply · spinner · overlays · command menu · input.
4
+ *
5
+ * The transcript is split in two:
6
+ * - everything except the last assistant message renders inside Ink's
7
+ * <Static>, which is written once and never re-drawn. This is what makes
8
+ * long sessions cheap: a streaming token only re-renders the live reply,
9
+ * the spinner, and the input — not 200 messages.
10
+ * - the last assistant message is live (it is usually the one streaming) and
11
+ * is rendered normally underneath.
12
+ * Pure layout: everything arrives as props, zero logic.
13
+ */
14
+ import React from "react";
15
+ import { Box, Static } from "ink";
16
+ import type { ChatMessage } from "../shared/types.js";
17
+ import { Banner } from "../components/Banner.js";
18
+ import { MessageView, StreamingMessage } from "../components/MessageView.js";
19
+ import { WorkingIndicator } from "../components/WorkingIndicator.js";
20
+ import { CommandMenu } from "../components/CommandMenu.js";
21
+ import { InputBar } from "../components/InputBar.js";
22
+ import { SearchOverlay } from "../components/SearchOverlay.js";
23
+ import { AgentPicker, AuthPicker, SessionPicker, PermissionPrompt, TrustPrompt } from "../components/Pickers.js";
24
+ import { KeysPanel } from "../components/KeysPanel.js";
25
+ import { MultiSelect } from "../controls/MultiSelect.js";
26
+ import { ApiKeyEntry } from "../controls/ApiKeyEntry.js";
27
+ import { AUTH_OPTIONS, KEY_SCOPES } from "../shared/types.js";
28
+ import type { AgentOption, SessionRow, KeysState, PendingOp } from "../shared/types.js";
29
+ import type { AuthMode } from "../hooks/useAuthFlow.js";
30
+
31
+ export interface ScreenLayoutProps {
32
+ messages: ChatMessage[];
33
+ streaming: boolean;
34
+ elapsed: number;
35
+
36
+ /** Folder trust gate — replaces the whole REPL until answered. */
37
+ trust: { pending: boolean; index: number; folder: string; mode: string };
38
+ /** Ctrl+/ and Ctrl+R search overlays. */
39
+ search: { mode: "commands" | "history" | null; query: string; index: number };
40
+ commandRows: Array<{ key: string; label: string; detail?: string }>;
41
+ historyRows: Array<{ key: string; label: string }>;
42
+ permissionMode: string;
43
+ agentPick: { open: boolean; busy: boolean; options: AgentOption[]; index: number };
44
+ authMode: AuthMode;
45
+ authIndex: number;
46
+ authBusy: boolean;
47
+ apiKeyDraft: string;
48
+ sessionPick: { open: boolean; busy: boolean; rows: SessionRow[]; index: number };
49
+ pendingOp: PendingOp | null;
50
+ keys: KeysState;
51
+
52
+ menuOpen: boolean;
53
+ filteredCommands: Array<{ name: string; args?: string; description: string }>;
54
+ clampedMenuIndex: number;
55
+
56
+ input: string;
57
+ /** Caret position within `input`. */
58
+ cursor: number;
59
+ agentName: string;
60
+ model: string;
61
+ authed: boolean;
62
+ provider?: string;
63
+ /** Launch folder, home-relative (~/…). */
64
+ cwd: string;
65
+ /** Terminal row count, used to bound the command menu. */
66
+ rows?: number;
67
+ }
68
+
69
+ /**
70
+ * The last message is live only while it is an assistant reply at the tail.
71
+ *
72
+ * <Static> writes each item once and tracks a high-water-mark index
73
+ * (`items.slice(index)`), so `settled` MUST be a growing prefix. Pulling an
74
+ * assistant message out of the middle — the old behavior — re-indexed the
75
+ * array when the next user prompt arrived: the completed reply was either
76
+ * emitted below the newer prompt or skipped past the cursor and vanished.
77
+ * Keeping the live item strictly at the tail makes every append a prefix
78
+ * extension, so a reply is committed exactly when the next message lands.
79
+ */
80
+ export const splitTranscript = (
81
+ messages: ChatMessage[],
82
+ ): { settled: ChatMessage[]; live: ChatMessage | null } => {
83
+ const last = messages[messages.length - 1];
84
+ if (last && last.role === "assistant") {
85
+ return { settled: messages.slice(0, -1), live: last };
86
+ }
87
+ // System notices (errors, interrupts, approvals) settle immediately, and
88
+ // they also settle the reply they follow.
89
+ return { settled: messages, live: null };
90
+ };
91
+
92
+ export const ScreenLayout = (p: ScreenLayoutProps) => {
93
+ const { settled, live } = splitTranscript(p.messages);
94
+ // Keep the last `limit` settled messages visible; <Static> still receives
95
+ // every item exactly once, so nothing is lost from scrollback.
96
+ const menuLimit = Math.max(4, Math.min(10, (p.rows ?? 24) - 8));
97
+ // The window scrolls with the selection. Clamping the *index* instead (the
98
+ // old behavior) parked the pointer on the last visible row while Enter ran
99
+ // a different command from the full list.
100
+ const menuStart = Math.max(0, Math.min(
101
+ p.clampedMenuIndex - Math.floor(menuLimit / 2),
102
+ Math.max(0, p.filteredCommands.length - menuLimit),
103
+ ));
104
+ const visibleCommands = p.filteredCommands.slice(menuStart, menuStart + menuLimit);
105
+
106
+ const overlayOpen =
107
+ p.trust.pending ||
108
+ Boolean(p.search.mode) ||
109
+ p.authMode !== "closed" ||
110
+ p.keys.mode !== "closed" ||
111
+ p.agentPick.open ||
112
+ p.sessionPick.open ||
113
+ Boolean(p.pendingOp);
114
+
115
+ if (p.trust.pending) {
116
+ return (
117
+ <Box flexDirection="column">
118
+ <Banner />
119
+ <TrustPrompt folder={p.trust.folder} selected={p.trust.index} mode={p.permissionMode} />
120
+ </Box>
121
+ );
122
+ }
123
+
124
+ return (
125
+ <Box flexDirection="column">
126
+ <Static items={settled}>
127
+ {(msg, i) => <MessageView key={i} msg={msg} />}
128
+ </Static>
129
+
130
+ {settled.length === 0 && <Banner />}
131
+
132
+ {/* While tokens are arriving only the tail is drawn (bounds Ink's
133
+ per-frame layout cost); once the turn finishes the full reply is
134
+ rendered, because the alternate screen has no scrollback to recover
135
+ the part that was hidden. */}
136
+ {live && (p.streaming ? <StreamingMessage msg={live} /> : <MessageView msg={live} />)}
137
+
138
+ {p.streaming && <WorkingIndicator elapsed={p.elapsed} agent={p.agentName} />}
139
+
140
+ {p.search.mode && (
141
+ <SearchOverlay
142
+ title={p.search.mode === "commands" ? "Commands" : "Prompt history"}
143
+ query={p.search.query}
144
+ rows={p.search.mode === "commands" ? p.commandRows : p.historyRows}
145
+ selected={p.search.index}
146
+ hint="↑/↓ move · Enter use · esc close"
147
+ />
148
+ )}
149
+
150
+ {p.agentPick.open && (
151
+ <AgentPicker options={p.agentPick.options} selected={p.agentPick.index} busy={p.agentPick.busy} />
152
+ )}
153
+
154
+ {p.authMode === "picker" && (
155
+ <AuthPicker options={AUTH_OPTIONS} selected={p.authIndex} busy={p.authBusy} />
156
+ )}
157
+
158
+ {p.sessionPick.open && (
159
+ <SessionPicker rows={p.sessionPick.rows} selected={p.sessionPick.index} busy={p.sessionPick.busy} />
160
+ )}
161
+
162
+ {p.pendingOp && <PermissionPrompt op={p.pendingOp} />}
163
+
164
+ {p.authMode === "api-key" && <ApiKeyEntry draft={p.apiKeyDraft} />}
165
+
166
+ {p.keys.mode === "create-scopes" ? (
167
+ <MultiSelect
168
+ title="Create API key — scopes"
169
+ options={[...KEY_SCOPES]}
170
+ selectedIds={p.keys.scopeSelection}
171
+ cursorIndex={p.keys.scopeCursor}
172
+ busy={p.keys.busy}
173
+ />
174
+ ) : (
175
+ p.keys.mode !== "closed" && <KeysPanel state={p.keys} />
176
+ )}
177
+
178
+ {p.menuOpen && visibleCommands.length > 0 && (
179
+ <CommandMenu
180
+ commands={visibleCommands}
181
+ selected={p.clampedMenuIndex - menuStart}
182
+ total={p.filteredCommands.length}
183
+ above={menuStart}
184
+ />
185
+ )}
186
+
187
+ {!overlayOpen && (
188
+ <InputBar
189
+ value={p.input}
190
+ cursor={p.cursor}
191
+ agent={p.agentName}
192
+ model={p.model}
193
+ authed={p.authed}
194
+ provider={p.provider}
195
+ turns={p.messages.length}
196
+ cwd={p.cwd}
197
+ mode={p.permissionMode}
198
+ />
199
+ )}
200
+ </Box>
201
+ );
202
+ };
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Shared types for the REPL UI components.
3
+ */
4
+ import type { Dispatch, MutableRefObject, SetStateAction } from "react";
5
+
6
+ export interface SlashCommand {
7
+ name: string;
8
+ args?: string;
9
+ description: string;
10
+ }
11
+
12
+ /** A selectable row in the /agent switcher. */
13
+ export interface AgentOption {
14
+ id: string;
15
+ label: string;
16
+ description: string;
17
+ }
18
+
19
+ /** A selectable row in the /sessions switcher. */
20
+ export interface SessionRow {
21
+ session_id: string;
22
+ title?: string;
23
+ agent_name?: string;
24
+ agent_id?: string;
25
+ model?: string;
26
+ updated_at?: string;
27
+ }
28
+
29
+ /** Risky local op awaiting y/N approval in the permission prompt. */
30
+ export interface PendingOp {
31
+ /** Must stay in sync with `GATED` in commands/local.ts. */
32
+ kind: "write" | "exec" | "delete" | "move";
33
+ summary: string; // human-readable one-liner of what will run
34
+ cliArgs: string[]; // full `odysx local ...` args to dispatch on approval
35
+ /** For writes: unified-ish before/after snippet shown in the prompt. */
36
+ diff?: { file: string; before: string; after: string };
37
+ /** Callback-based approval for operations that cannot be re-dispatched as a
38
+ * `local --yes` command (e.g. /export). One of these resolves the caller's
39
+ * promise; omit both for the normal CLI-command approval path. */
40
+ onApproved?: () => void;
41
+ onDenied?: () => void;
42
+ }
43
+
44
+ /* ── /keys flow ── */
45
+ export type KeysMode =
46
+ | "closed"
47
+ | "menu"
48
+ | "create-name"
49
+ | "create-scopes"
50
+ | "confirm-revoke"
51
+ | "created";
52
+
53
+ /** Scopes a user API key can carry (must match backend ApiKeyGate). */
54
+ export const KEY_SCOPES = [
55
+ { id: "chat", label: "chat", description: "Send chat messages (/llm/chat)" },
56
+ { id: "agents:read", label: "agents:read", description: "List agents, skills, prompt templates" },
57
+ { id: "keys", label: "keys", description: "Manage API keys" },
58
+ ] as const;
59
+
60
+ export interface ApiKeyRow {
61
+ id: string;
62
+ name: string;
63
+ key_prefix: string;
64
+ is_active: boolean;
65
+ scopes?: string[];
66
+ rate_limit_rpm?: number;
67
+ daily_token_limit?: number;
68
+ last_used_at?: string | null;
69
+ created_at?: string;
70
+ }
71
+
72
+ export interface KeysState {
73
+ mode: KeysMode;
74
+ busy: boolean;
75
+ rows: ApiKeyRow[];
76
+ selectedIndex: number;
77
+ draftName: string;
78
+ /** Scopes multi-select state (create-scopes mode). */
79
+ scopeCursor: number;
80
+ scopeSelection: Set<string>;
81
+ createdKey: { key: string; name: string } | null;
82
+ /** Persisted local label (key prefix) of the selected active key. */
83
+ activeKeyLabel: string | null;
84
+ }
85
+
86
+ /* ── Transcript ── */
87
+ export type Role = "user" | "assistant" | "system";
88
+
89
+ export interface ChatMessage {
90
+ role: Role;
91
+ text: string;
92
+ agentName?: string; // display name of the agent that produced an assistant reply
93
+ }
94
+
95
+ /** Per-session token accounting, filled from stream/chat responses. */
96
+ export interface UsageAccumulator {
97
+ requests: number;
98
+ promptTokens: number;
99
+ completionTokens: number;
100
+ }
101
+
102
+ /** Everything a slash-command handler may touch from the REPL shell. */
103
+ export interface CommandCtx {
104
+ addMessage: (text: string) => void;
105
+ setMessages: Dispatch<SetStateAction<ChatMessage[]>>;
106
+ /** Session id getter (lives in a ref in app.tsx, not a module mutable). */
107
+ sessionId: () => string;
108
+ agentId: string;
109
+ config: { apiKey?: string; token?: string; apiUrl: string };
110
+ openAgentPicker: () => void;
111
+ setAgentId: (id: string) => void;
112
+ resumeSession: (sid: string) => void;
113
+ openSessionPicker: () => void;
114
+ openKeysPanel: () => Promise<void>;
115
+ setPendingOp: (op: PendingOp | null) => void;
116
+ /** Wipe the transcript and remount the static region (/clear, /compact). */
117
+ resetTranscript: () => void;
118
+ /** Start a fresh server-side session (/new); clears the local transcript too. */
119
+ newSession: () => void;
120
+ usageRef: MutableRefObject<UsageAccumulator>;
121
+ /** Aborts an in-flight stream (used by /clear so tokens stop appending). */
122
+ abortStream: () => void;
123
+ requestExit: () => void;
124
+ /** Auth picker setters, so /signin can open the sign-in menu from runCommand. */
125
+ setAuthMode: (mode: "closed" | "picker" | "api-key") => void;
126
+ setAuthIndex: (index: number) => void;
127
+ }
128
+
129
+ /** Slash-command list shown in /help and the suggestion menu. */
130
+ export const SLASH_COMMANDS: SlashCommand[] = [
131
+ { name: "help", description: "Show help" },
132
+ { name: "clear", description: "Clear screen (server conversation is kept)" },
133
+ { name: "new", description: "Start a fresh session (new server conversation)" },
134
+ { name: "status", description: "Session info (auth, agent, model)" },
135
+ { name: "signin", description: "Authenticate — API key or account sign-in" },
136
+ { name: "keys", description: "Manage API keys (list / new / revoke / usage)" },
137
+ { name: "agent", args: "<id>", description: "Switch agent" },
138
+ { name: "model", args: "<id>", description: "Switch model" },
139
+ { name: "provider", args: "[name]", description: "List external providers / switch (odysx = platform)" },
140
+ { name: "sessions", args: "[id]", description: "List and resume past sessions" },
141
+ { name: "tasks", args: "[id|retry <id>|cancel <id>|follow <id>]", description: "Background agent tasks — list, inspect, retry, cancel" },
142
+ { name: "ralph", args: "<objective>", description: "Autonomous improve-until-done run (opt-in)" },
143
+ { name: "mcp", description: "List registered MCP servers" },
144
+ { name: "prompts", description: "List prompt templates (/prompts <slug> to view)" },
145
+ { name: "skills", description: "List installed skills" },
146
+ { name: "usage", description: "Token usage summary this session" },
147
+ { name: "local", args: "<read|write|exec|ls|pwd|delete>", description: "Workspace file/shell ops (gated)" },
148
+ { name: "mode", args: "[auto|plan|manual|guide]", description: "Permission mode — read-only, guide, ask, or auto" },
149
+ { name: "trust", args: "[forget <path>]", description: "Trusted folders — list them, or forget one" },
150
+ { name: "compact", description: "Clear conversation context" },
151
+ { name: "export", description: "Export session transcript to JSON" },
152
+ { name: "quit", description: "Exit OdysX" },
153
+ ];
154
+
155
+ /** Sign-in menu choices. */
156
+ export const AUTH_OPTIONS = [
157
+ { id: "api-key", label: "Use an API key", description: "Paste an existing OdysX API key" },
158
+ { id: "keys", label: "Manage API keys", description: "Create, list, or revoke keys" },
159
+ { id: "account", label: "Sign in with account", description: "Username & password (coming soon)" },
160
+ ] as const;
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Theme — the single source of color and glyph choices for the Ink UI.
3
+ *
4
+ * Components must not hardcode ANSI names or box-drawing characters: keeping
5
+ * them here means a palette change is one edit, and the transcript, overlays,
6
+ * and footer stay visually coherent.
7
+ *
8
+ * When colour is off (`--no-color`, NO_COLOR, piped stdout, TERM=dumb) every
9
+ * entry becomes `undefined`. Ink treats a missing colour as "no escape", so
10
+ * the UI goes monochrome *without* losing bold/dim/inverse. That matters:
11
+ * Ink routes those attributes through the same chalk instance, so turning
12
+ * chalk off wholesale would also erase the input caret (`inverse`) and every
13
+ * selection marker. Colour and text attributes are separate decisions.
14
+ */
15
+ import { colorEnabled } from "../core/terminal.js";
16
+
17
+ /** A named colour, or undefined when colour is disabled. */
18
+ const c = (name: string): string | undefined => (colorEnabled() ? name : undefined);
19
+
20
+ export const theme = {
21
+ color: {
22
+ brand: c("cyan"),
23
+ accent: c("magenta"),
24
+ user: c("blue"),
25
+ success: c("green"),
26
+ warning: c("yellow"),
27
+ error: c("red"),
28
+ muted: c("gray"),
29
+ info: c("cyan"),
30
+ code: c("yellow"),
31
+ link: c("blue"),
32
+ },
33
+ glyph: {
34
+ pointer: "❯",
35
+ bullet: "•",
36
+ check: "✓",
37
+ cross: "✗",
38
+ warn: "⚠",
39
+ info: "·",
40
+ bar: "│",
41
+ rule: "─",
42
+ arrowUp: "↑",
43
+ arrowDown: "↓",
44
+ },
45
+ } as const;
46
+
47
+ /** Severity → color, used by system lines so errors look like errors. */
48
+ export const systemColor = (text: string): string | undefined => {
49
+ if (text.startsWith("✗") || /^Error\b/i.test(text)) return theme.color.error;
50
+ if (text.startsWith("⚠")) return theme.color.warning;
51
+ if (text.startsWith("✓")) return theme.color.success;
52
+ return theme.color.muted;
53
+ };
@@ -0,0 +1,255 @@
1
+ import { sanitize } from "./terminal-text.js";
2
+
3
+ /**
4
+ * Line-oriented markdown → style model for the Ink transcript.
5
+ *
6
+ * Ink renders React nodes, not ANSI strings, so the previous approach (parse
7
+ * markdown to HTML, then regex the HTML back to text) threw away every style.
8
+ * This parser walks the raw markdown once and returns typed lines that
9
+ * MessageView maps to <Text> props. It is deliberately line-based: streaming
10
+ * replies arrive as an ever-growing string and we re-render on every token, so
11
+ * parsing must be cheap and allocation-light.
12
+ *
13
+ * Supported: ATX headings, fenced code (with a language label), ordered and
14
+ * unordered lists (nested by indent), blockquotes, rules, tables, and inline
15
+ * **bold**, *italic*, `code`, ~~strike~~, [links](url).
16
+ */
17
+
18
+ /** An inline run: text plus the styles that apply to it. */
19
+ export interface InlineRun {
20
+ text: string;
21
+ bold?: boolean;
22
+ italic?: boolean;
23
+ code?: boolean;
24
+ strike?: boolean;
25
+ underline?: boolean;
26
+ link?: string;
27
+ }
28
+
29
+ export type MdLine =
30
+ | { kind: "blank" }
31
+ | { kind: "heading"; level: number; runs: InlineRun[] }
32
+ | { kind: "text"; runs: InlineRun[] }
33
+ | { kind: "bullet"; depth: number; marker: string; runs: InlineRun[] }
34
+ | { kind: "quote"; runs: InlineRun[] }
35
+ | { kind: "rule" }
36
+ | { kind: "code"; lang: string; lines: string[]; open: boolean }
37
+ | { kind: "table"; header: string[]; rows: string[][]; align: Array<"left" | "center" | "right"> };
38
+
39
+ const FENCE = /^\s*(```|~~~)\s*([\w+-]*)\s*$/;
40
+ const HEADING = /^\s{0,3}(#{1,6})\s+(.*)$/;
41
+ const BULLET = /^(\s*)([-*+]|\d{1,3}[.)])\s+(.*)$/;
42
+ const QUOTE = /^\s{0,3}>\s?(.*)$/;
43
+ const RULE = /^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/;
44
+ // GFM allows a single dash per column (`|:-:|` is a centered column), so the
45
+ // minimum is one, not two.
46
+ const TABLE_DIVIDER = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;
47
+
48
+ /**
49
+ * Split inline markdown into styled runs. Unmatched delimiters stay literal,
50
+ * so a half-streamed `**bold` simply renders as text until it completes.
51
+ */
52
+ export function parseInline(text: string): InlineRun[] {
53
+ const runs: InlineRun[] = [];
54
+ let buffer = "";
55
+ const flush = (): void => {
56
+ if (buffer) {
57
+ runs.push({ text: buffer });
58
+ buffer = "";
59
+ }
60
+ };
61
+
62
+ for (let i = 0; i < text.length; i++) {
63
+ const ch = text[i];
64
+
65
+ // `code` — highest precedence, no nested formatting inside.
66
+ if (ch === "`") {
67
+ const end = text.indexOf("`", i + 1);
68
+ if (end !== -1) {
69
+ flush();
70
+ runs.push({ text: text.slice(i + 1, end), code: true });
71
+ i = end;
72
+ continue;
73
+ }
74
+ }
75
+
76
+ // **bold** / __bold__
77
+ if ((ch === "*" || ch === "_") && text[i + 1] === ch) {
78
+ const marker = ch + ch;
79
+ const end = text.indexOf(marker, i + 2);
80
+ if (end !== -1 && end > i + 2) {
81
+ flush();
82
+ for (const inner of parseInline(text.slice(i + 2, end))) {
83
+ runs.push({ ...inner, bold: true });
84
+ }
85
+ i = end + 1;
86
+ continue;
87
+ }
88
+ }
89
+
90
+ // *italic* / _italic_ — a single marker, not part of a word for `_`.
91
+ if (ch === "*" || ch === "_") {
92
+ const prev = text[i - 1] ?? " ";
93
+ const next = text[i + 1] ?? " ";
94
+ const wordBoundary = ch === "*" || (!/\w/.test(prev) && !/\w/.test(next));
95
+ if (wordBoundary && next !== " ") {
96
+ const end = text.indexOf(ch, i + 1);
97
+ if (end !== -1 && end > i + 1) {
98
+ flush();
99
+ for (const inner of parseInline(text.slice(i + 1, end))) {
100
+ runs.push({ ...inner, italic: true });
101
+ }
102
+ i = end;
103
+ continue;
104
+ }
105
+ }
106
+ }
107
+
108
+ // ~~strike~~
109
+ if (ch === "~" && text[i + 1] === "~") {
110
+ const end = text.indexOf("~~", i + 2);
111
+ if (end !== -1 && end > i + 2) {
112
+ flush();
113
+ for (const inner of parseInline(text.slice(i + 2, end))) {
114
+ runs.push({ ...inner, strike: true });
115
+ }
116
+ i = end + 1;
117
+ continue;
118
+ }
119
+ }
120
+
121
+ // [label](url)
122
+ if (ch === "[") {
123
+ const close = text.indexOf("](", i + 1);
124
+ if (close !== -1) {
125
+ const urlEnd = text.indexOf(")", close + 2);
126
+ if (urlEnd !== -1) {
127
+ flush();
128
+ const label = text.slice(i + 1, close);
129
+ const url = text.slice(close + 2, urlEnd);
130
+ runs.push({ text: label || url, link: url, underline: true });
131
+ i = urlEnd;
132
+ continue;
133
+ }
134
+ }
135
+ }
136
+
137
+ buffer += ch;
138
+ }
139
+ flush();
140
+ return runs;
141
+ }
142
+
143
+ /** Fence state carried across lines when streaming a partially received reply. */
144
+ interface ParseState {
145
+ inCode: boolean;
146
+ lang: string;
147
+ codeLines: string[];
148
+ }
149
+
150
+ /** Parse a full markdown string during streaming (an unclosed fence stays open). */
151
+ export function parseMarkdown(markdown: string): MdLine[] {
152
+ // Strip control sequences before parsing: model output is untrusted, and a
153
+ // raw `\x1b[2J` reaching Ink's output would clear or corrupt the screen.
154
+ return parseWithState(sanitize(markdown), { inCode: false, lang: "", codeLines: [] }).lines;
155
+ }
156
+
157
+ /** Internal: parse and expose residual fence state for incremental callers. */
158
+ export function parseWithState(
159
+ markdown: string,
160
+ initial: ParseState,
161
+ ): { lines: MdLine[]; state: ParseState } {
162
+ const out: MdLine[] = [];
163
+ const state: ParseState = { ...initial, codeLines: [...initial.codeLines] };
164
+ const lines = markdown.split("\n");
165
+
166
+ for (let i = 0; i < lines.length; i++) {
167
+ const line = lines[i];
168
+
169
+ const fence = line.match(FENCE);
170
+ if (state.inCode) {
171
+ if (fence) {
172
+ out.push({ kind: "code", lang: state.lang, lines: state.codeLines, open: false });
173
+ state.inCode = false;
174
+ state.lang = "";
175
+ state.codeLines = [];
176
+ } else {
177
+ state.codeLines.push(line);
178
+ }
179
+ continue;
180
+ }
181
+ if (fence) {
182
+ state.inCode = true;
183
+ state.lang = fence[2] ?? "";
184
+ state.codeLines = [];
185
+ continue;
186
+ }
187
+
188
+ // Table: a header row followed by a divider row.
189
+ if (line.includes("|") && i + 1 < lines.length && TABLE_DIVIDER.test(lines[i + 1])) {
190
+ const splitRow = (row: string): string[] =>
191
+ row.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((c) => c.trim());
192
+ const header = splitRow(line);
193
+ const divider = splitRow(lines[i + 1]);
194
+ const align = divider.map((cell) =>
195
+ cell.startsWith(":") && cell.endsWith(":") ? "center" : cell.endsWith(":") ? "right" : "left",
196
+ ) as Array<"left" | "center" | "right">;
197
+ const rows: string[][] = [];
198
+ i += 2;
199
+ while (i < lines.length && lines[i].includes("|") && lines[i].trim() !== "") {
200
+ rows.push(splitRow(lines[i]));
201
+ i++;
202
+ }
203
+ i--;
204
+ out.push({ kind: "table", header, rows, align });
205
+ continue;
206
+ }
207
+
208
+ if (!line.trim()) {
209
+ out.push({ kind: "blank" });
210
+ continue;
211
+ }
212
+
213
+ const heading = line.match(HEADING);
214
+ if (heading) {
215
+ out.push({ kind: "heading", level: heading[1].length, runs: parseInline(heading[2]) });
216
+ continue;
217
+ }
218
+
219
+ if (RULE.test(line)) {
220
+ out.push({ kind: "rule" });
221
+ continue;
222
+ }
223
+
224
+ const quote = line.match(QUOTE);
225
+ if (quote) {
226
+ out.push({ kind: "quote", runs: parseInline(quote[1]) });
227
+ continue;
228
+ }
229
+
230
+ const bullet = line.match(BULLET);
231
+ if (bullet) {
232
+ const indent = bullet[1].replace(/\t/g, " ").length;
233
+ out.push({
234
+ kind: "bullet",
235
+ depth: Math.min(3, Math.floor(indent / 2)),
236
+ marker: /^\d/.test(bullet[2]) ? bullet[2] : "•",
237
+ runs: parseInline(bullet[3]),
238
+ });
239
+ continue;
240
+ }
241
+
242
+ out.push({ kind: "text", runs: parseInline(line) });
243
+ }
244
+
245
+ // A fence that hasn't closed yet is still rendered live while streaming.
246
+ // The final newline produces one empty trailing line — it is the line break
247
+ // after the last code row, not a blank row, so drop it.
248
+ if (state.inCode) {
249
+ const codeLines = state.codeLines;
250
+ if (codeLines.length > 0 && codeLines[codeLines.length - 1] === "") codeLines.pop();
251
+ out.push({ kind: "code", lang: state.lang, lines: codeLines, open: true });
252
+ }
253
+
254
+ return { lines: out, state };
255
+ }