ronin-skillforce 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 (429) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/LICENSE +21 -0
  3. package/README.md +225 -2
  4. package/bin/cli.js +811 -0
  5. package/bin/commands/check.js +298 -0
  6. package/bin/commands/create.js +169 -0
  7. package/bin/commands/doctor.js +392 -0
  8. package/bin/commands/import.js +557 -0
  9. package/bin/commands/next.js +125 -0
  10. package/bin/commands/review.js +207 -0
  11. package/bin/commands/status.js +114 -0
  12. package/bin/commands/studio.js +497 -0
  13. package/bin/commands/trail.js +211 -0
  14. package/bin/commands/web.js +350 -0
  15. package/bin/course-reader.js +611 -0
  16. package/bin/node-version.js +60 -0
  17. package/bin/platforms/_shared.js +211 -0
  18. package/bin/platforms/claude.js +104 -0
  19. package/bin/platforms/cursor.js +49 -0
  20. package/bin/platforms/gemini.js +65 -0
  21. package/bin/platforms/opencode.js +95 -0
  22. package/bin/registry-helpers.js +504 -0
  23. package/bin/static-server.js +153 -0
  24. package/bin/studio-store.js +94 -0
  25. package/bin/sync-shared.sh +5 -0
  26. package/package.json +91 -4
  27. package/plugin.json +139 -0
  28. package/shared/SKILL.md +568 -0
  29. package/shared/agents/coach.md +225 -0
  30. package/shared/agents/navigator.md +215 -0
  31. package/shared/agents/professor.md +372 -0
  32. package/shared/agents/researcher.md +181 -0
  33. package/shared/agents/spotter.md +129 -0
  34. package/shared/commands/professor/archive.md +103 -0
  35. package/shared/commands/professor/capstone-review.md +79 -0
  36. package/shared/commands/professor/capstone.md +34 -0
  37. package/shared/commands/professor/discuss.md +18 -0
  38. package/shared/commands/professor/done.md +44 -0
  39. package/shared/commands/professor/export.md +69 -0
  40. package/shared/commands/professor/hint.md +108 -0
  41. package/shared/commands/professor/navigator.md +67 -0
  42. package/shared/commands/professor/new-topic.md +73 -0
  43. package/shared/commands/professor/next.md +174 -0
  44. package/shared/commands/professor/note.md +63 -0
  45. package/shared/commands/professor/onboard.md +95 -0
  46. package/shared/commands/professor/progress.md +46 -0
  47. package/shared/commands/professor/publish.md +93 -0
  48. package/shared/commands/professor/quiz.md +27 -0
  49. package/shared/commands/professor/recall.md +74 -0
  50. package/shared/commands/professor/review.md +43 -0
  51. package/shared/commands/professor/schedule.md +75 -0
  52. package/shared/commands/professor/skill-export.md +87 -0
  53. package/shared/commands/professor/spotter.md +76 -0
  54. package/shared/commands/professor/stuck.md +27 -0
  55. package/shared/commands/professor/switch.md +50 -0
  56. package/shared/commands/professor/syllabus.md +9 -0
  57. package/shared/commands/professor/template-export.md +91 -0
  58. package/shared/commands/professor/template-import.md +111 -0
  59. package/shared/commands/professor/worktrees.md +58 -0
  60. package/shared/hooks/pre-compact.js +232 -0
  61. package/studio/README.md +313 -0
  62. package/studio/dist/assets/BetaReportPanel-8NrDLiPm.js +1 -0
  63. package/studio/dist/assets/Capstone-Cv9kH6LY.js +6 -0
  64. package/studio/dist/assets/CodeWorkspace-BwCEINWo.js +2 -0
  65. package/studio/dist/assets/Course-BJ_hafUP.js +1 -0
  66. package/studio/dist/assets/Editor-CV0mNhlz.js +53 -0
  67. package/studio/dist/assets/Home-C1ry89ak.js +1 -0
  68. package/studio/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  69. package/studio/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  70. package/studio/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  71. package/studio/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  72. package/studio/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  73. package/studio/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  74. package/studio/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  75. package/studio/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  76. package/studio/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  77. package/studio/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  78. package/studio/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  79. package/studio/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  80. package/studio/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  81. package/studio/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  82. package/studio/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  83. package/studio/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  84. package/studio/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  85. package/studio/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  86. package/studio/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  87. package/studio/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  88. package/studio/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  89. package/studio/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  90. package/studio/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  91. package/studio/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  92. package/studio/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  93. package/studio/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  94. package/studio/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  95. package/studio/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  96. package/studio/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  97. package/studio/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  98. package/studio/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  99. package/studio/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  100. package/studio/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  101. package/studio/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  102. package/studio/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  103. package/studio/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  104. package/studio/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  105. package/studio/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  106. package/studio/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  107. package/studio/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  108. package/studio/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  109. package/studio/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  110. package/studio/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  111. package/studio/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  112. package/studio/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  113. package/studio/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  114. package/studio/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  115. package/studio/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  116. package/studio/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  117. package/studio/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  118. package/studio/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  119. package/studio/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  120. package/studio/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  121. package/studio/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  122. package/studio/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  123. package/studio/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  124. package/studio/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  125. package/studio/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  126. package/studio/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  127. package/studio/dist/assets/Lesson-2e9TD9yL.js +2 -0
  128. package/studio/dist/assets/NewCourse-BZeOg2xn.js +952 -0
  129. package/studio/dist/assets/Progress-CRc_xEWC.js +1 -0
  130. package/studio/dist/assets/Review-6QEbHEfk.js +1 -0
  131. package/studio/dist/assets/Settings-NFnqVQui.js +1 -0
  132. package/studio/dist/assets/TutorPanel-DXQ6Z3BY.js +123 -0
  133. package/studio/dist/assets/abnfDiagram-WEYOIA3C-qeSjKlGM.js +1 -0
  134. package/studio/dist/assets/anthropic-D7NiQCUH.js +15 -0
  135. package/studio/dist/assets/arc-Y1ARJVZ4.js +1 -0
  136. package/studio/dist/assets/architecture-WOLXFQ4H-COG-m35l.js +1 -0
  137. package/studio/dist/assets/architectureDiagram-ZHVYKT53-VO7uKoeD.js +36 -0
  138. package/studio/dist/assets/array-BifhSqXX.js +1 -0
  139. package/studio/dist/assets/blockDiagram-RJAE7QA3-BGJF_qiL.js +140 -0
  140. package/studio/dist/assets/bridge-BTh0AeNX.js +1 -0
  141. package/studio/dist/assets/c4Diagram-XDPPPE54-C-S10RgU.js +38 -0
  142. package/studio/dist/assets/capstone-Amn6Hztq.js +135 -0
  143. package/studio/dist/assets/card-store-BrbrtX9w.js +1 -0
  144. package/studio/dist/assets/channel-SJiUQu_N.js +1 -0
  145. package/studio/dist/assets/chunk-2E7WHVMD-fv-iqTyC.js +88 -0
  146. package/studio/dist/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  147. package/studio/dist/assets/chunk-4EMNKR2T-CY9IZrgv.js +1 -0
  148. package/studio/dist/assets/chunk-55XCU76K-DyTZz7v_.js +1 -0
  149. package/studio/dist/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
  150. package/studio/dist/assets/chunk-7S6XSTFO-BNMzTLRW.js +2 -0
  151. package/studio/dist/assets/chunk-AQDTSKZB-CEYANohH.js +72 -0
  152. package/studio/dist/assets/chunk-DSNLSHJZ-CDk5EXjH.js +129 -0
  153. package/studio/dist/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  154. package/studio/dist/assets/chunk-HAGFOTED-hNAi1zh_.js +62 -0
  155. package/studio/dist/assets/chunk-HNE4Q36P-COJnSYoZ.js +1 -0
  156. package/studio/dist/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
  157. package/studio/dist/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  158. package/studio/dist/assets/chunk-NGNAAXSQ-C2Wy9Xmz.js +136 -0
  159. package/studio/dist/assets/chunk-NQOKRVIF-BU6KVxRr.js +213 -0
  160. package/studio/dist/assets/chunk-UHW7PFBP-DYvxL9JG.js +1 -0
  161. package/studio/dist/assets/chunk-VQ5W62QI-CuRfk65j.js +1 -0
  162. package/studio/dist/assets/chunk-WQQL4CDK-KaG7x-Mb.js +10 -0
  163. package/studio/dist/assets/chunk-XXDRQBXY-CnbRkih_.js +1 -0
  164. package/studio/dist/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  165. package/studio/dist/assets/chunk-YZO67HFG-DbuqIZmk.js +1 -0
  166. package/studio/dist/assets/chunk-ZAUX2LTX-bk4ivUmc.js +1 -0
  167. package/studio/dist/assets/chunk-ZCHMQSOR-B_LElfwh.js +2 -0
  168. package/studio/dist/assets/classDiagram-v2-4MYWR3UA-DtCJ6H_X.js +217 -0
  169. package/studio/dist/assets/cose-bilkent-JH36ORCC-DMBAZFnj.js +1 -0
  170. package/studio/dist/assets/course-export-DpaOTT3a.js +1 -0
  171. package/studio/dist/assets/cynefin-EF2NZ3EQ-D9btHJvU.js +1 -0
  172. package/studio/dist/assets/cynefinDiagram-WF24UDRP-CsFJuv27.js +62 -0
  173. package/studio/dist/assets/cytoscape.esm-CHBj4VkZ.js +321 -0
  174. package/studio/dist/assets/dagre-NK4GIZVX-Cg1Duec7.js +4 -0
  175. package/studio/dist/assets/defaultLocale-BFoDCU3G.js +1 -0
  176. package/studio/dist/assets/diagram-CBK3MWTC-_KU2m5gd.js +24 -0
  177. package/studio/dist/assets/diagram-I5XIIV2D-5RaBrwUA.js +24 -0
  178. package/studio/dist/assets/diagram-ODIL2UCW-C0VKxoD3.js +30 -0
  179. package/studio/dist/assets/diagram-PFBEJUXE-BaHcZEP2.js +3 -0
  180. package/studio/dist/assets/diagram-RJA3I4VV-cwSAZ90p.js +41 -0
  181. package/studio/dist/assets/diagram-TYUNFSNR-BJImxCEN.js +200 -0
  182. package/studio/dist/assets/dist-CumnGVmJ.js +1 -0
  183. package/studio/dist/assets/ebnfDiagram-V4P3TTPT-OQQLRXcm.js +1 -0
  184. package/studio/dist/assets/elk-QONTBCTQ-BJGhQHxQ.js +27 -0
  185. package/studio/dist/assets/erDiagram-KYQIGQAA-D91EKSep.js +99 -0
  186. package/studio/dist/assets/error-BTdmRKoB.js +1 -0
  187. package/studio/dist/assets/errors-BZa_CNHL.js +1 -0
  188. package/studio/dist/assets/eventmodeling-K75KTNOO-DgdTRgnw.js +1 -0
  189. package/studio/dist/assets/fetch-local-DG3O3hmQ.js +4 -0
  190. package/studio/dist/assets/flowDiagram-IUGLLWBU-CVnJYMum.js +1 -0
  191. package/studio/dist/assets/ganttDiagram-R7GPNTJY-CSYLPWEI.js +292 -0
  192. package/studio/dist/assets/gitGraph-VSP46ZUC-D6GWaV9y.js +1 -0
  193. package/studio/dist/assets/gitGraphDiagram-PDYL7XHY-CaV31bvT.js +106 -0
  194. package/studio/dist/assets/graphlib-DS17s2tU.js +1 -0
  195. package/studio/dist/assets/index-CVenTTOY.css +2 -0
  196. package/studio/dist/assets/index-DioXTZVc.js +313 -0
  197. package/studio/dist/assets/info-OHQRW6UA-BN-x8GoN.js +1 -0
  198. package/studio/dist/assets/infoDiagram-MVDRKAX5-CIose_cy.js +2 -0
  199. package/studio/dist/assets/init-C-OQMol4.js +1 -0
  200. package/studio/dist/assets/ishikawaDiagram-HPEHV2GE-DCihSNBw.js +70 -0
  201. package/studio/dist/assets/journeyDiagram-BOSHW7O7-Bz3o3RIX.js +139 -0
  202. package/studio/dist/assets/js.worker-AD7DjksO.js +4 -0
  203. package/studio/dist/assets/kanban-definition-FNSA4HC5-BUyqvlFE.js +89 -0
  204. package/studio/dist/assets/katex-B_JcIwqj.js +257 -0
  205. package/studio/dist/assets/katex-BgsA2lO1.css +1 -0
  206. package/studio/dist/assets/line-B08T8KlK.js +1 -0
  207. package/studio/dist/assets/linear-C9iwaMOi.js +1 -0
  208. package/studio/dist/assets/mermaid-parser.core-BYwreSUy.js +7 -0
  209. package/studio/dist/assets/mermaid.core-DTO1oDmq.js +44 -0
  210. package/studio/dist/assets/mindmap-definition-6OY57UG3-BGLwKheY.js +98 -0
  211. package/studio/dist/assets/node.browser-BISniYn8.js +1 -0
  212. package/studio/dist/assets/node.browser-HQ5SKBOf.js +1 -0
  213. package/studio/dist/assets/ollama-De5w84tG.js +1 -0
  214. package/studio/dist/assets/openai-compatible-Joy1oK3L.js +1 -0
  215. package/studio/dist/assets/ordinal-BDEzSJ7C.js +1 -0
  216. package/studio/dist/assets/packet-JDAUHWVQ-CDIMjHS_.js +1 -0
  217. package/studio/dist/assets/path-fybaL0A-.js +1 -0
  218. package/studio/dist/assets/pegDiagram-ECIUJNBX-DWXm4mwS.js +1 -0
  219. package/studio/dist/assets/pie-XZMESJXO-CY3QQiKZ.js +1 -0
  220. package/studio/dist/assets/pieDiagram-GNMPY74T-M1aCnI7W.js +39 -0
  221. package/studio/dist/assets/python.worker-CzTrFdd9.js +24 -0
  222. package/studio/dist/assets/quadrantDiagram-D57K4MC3-BFFtO7U5.js +7 -0
  223. package/studio/dist/assets/radar-ABXABTNO-DT0W4_Xn.js +1 -0
  224. package/studio/dist/assets/railroad-I3PHUGI6-_VCpgZR5.js +1 -0
  225. package/studio/dist/assets/railroad-abnf-LNEFI6M7-DkSpQ5YY.js +1 -0
  226. package/studio/dist/assets/railroad-ebnf-DWYD2UWJ-BqWILdGb.js +1 -0
  227. package/studio/dist/assets/railroad-peg-JR7BVNR7-BB0bQL-Z.js +1 -0
  228. package/studio/dist/assets/railroadDiagram-Y72NRBL7-CjLKjIdJ.js +1 -0
  229. package/studio/dist/assets/react-B8SKf8RM.js +1 -0
  230. package/studio/dist/assets/rehype-katex-C-sKddsH.js +259 -0
  231. package/studio/dist/assets/remark-math-C-ox67hE.js +5 -0
  232. package/studio/dist/assets/requirementDiagram-EQYSW5RA-CnwzZqR8.js +84 -0
  233. package/studio/dist/assets/rolldown-runtime-COiEfhsA.js +1 -0
  234. package/studio/dist/assets/rough.esm-Dy-Kn_BL.js +1 -0
  235. package/studio/dist/assets/sankeyDiagram-SY24JHO5-CPDugTUl.js +40 -0
  236. package/studio/dist/assets/schemas-BOc2YsOP.js +55 -0
  237. package/studio/dist/assets/sequenceDiagram-BLEHNHQU-1dLfeU9Y.js +169 -0
  238. package/studio/dist/assets/settings-DhwuyNPU.js +1 -0
  239. package/studio/dist/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  240. package/studio/dist/assets/spec-nAnsSMkw.js +1 -0
  241. package/studio/dist/assets/sql-wasm-C1D_RJuy.wasm +0 -0
  242. package/studio/dist/assets/sql.worker-D7pBHOrq.js +4 -0
  243. package/studio/dist/assets/src-BWF7jMDv.js +1 -0
  244. package/studio/dist/assets/stateDiagram-v2-A6IESKWZ-DR7CmEjj.js +291 -0
  245. package/studio/dist/assets/swimlanes-B3ENRKFQ-BAWB9omQ.js +1 -0
  246. package/studio/dist/assets/swimlanesDiagram-AYQRV4AK-qeuHru16.js +8 -0
  247. package/studio/dist/assets/timeline-definition-JXYKGLGB-DNkj8z77.js +120 -0
  248. package/studio/dist/assets/treeView-D4JQ5SDB-BA-ouhMb.js +1 -0
  249. package/studio/dist/assets/treemap-SAJKECNS-BrrGxsAb.js +1 -0
  250. package/studio/dist/assets/useStream-rdsR6A7P.js +1 -0
  251. package/studio/dist/assets/usecaseDiagram-WPOLBNNX-BB3D0Dt_.js +328 -0
  252. package/studio/dist/assets/vennDiagram-Q3Y3IDCW-BrtqtKTE.js +34 -0
  253. package/studio/dist/assets/wardley-7MLQ67FV-BKkemDql.js +1 -0
  254. package/studio/dist/assets/wardleyDiagram-IVAIDKWA-DFnI3P5z.js +78 -0
  255. package/studio/dist/assets/xychartDiagram-4URNHDU4-Da0DZG_q.js +7 -0
  256. package/studio/dist/index.html +20 -0
  257. package/studio/dist/preview.html +22 -0
  258. package/studio/migrations/0001_init.sql +188 -0
  259. package/studio/migrations/0002_external_ids.sql +20 -0
  260. package/studio/migrations/0003_course_language.sql +12 -0
  261. package/studio/migrations/0004_capstone.sql +51 -0
  262. package/studio/migrations/0005_beta_loop.sql +73 -0
  263. package/studio/migrations/0006_interactive_exercises.sql +49 -0
  264. package/studio/src/lib/activity.js +92 -0
  265. package/studio/src/lib/ai/anthropic.js +109 -0
  266. package/studio/src/lib/ai/bridge.js +126 -0
  267. package/studio/src/lib/ai/catalog.js +160 -0
  268. package/studio/src/lib/ai/config.js +70 -0
  269. package/studio/src/lib/ai/errors.js +95 -0
  270. package/studio/src/lib/ai/fetch-local.js +104 -0
  271. package/studio/src/lib/ai/index.js +194 -0
  272. package/studio/src/lib/ai/ollama.js +136 -0
  273. package/studio/src/lib/ai/openai-compatible.js +101 -0
  274. package/studio/src/lib/ai/provider-utils.js +107 -0
  275. package/studio/src/lib/ai/sse.js +99 -0
  276. package/studio/src/lib/ai/status.js +92 -0
  277. package/studio/src/lib/ai/useStream.js +109 -0
  278. package/studio/src/lib/beta/metrics.js +147 -0
  279. package/studio/src/lib/beta/report.js +134 -0
  280. package/studio/src/lib/capstone-evidence.js +758 -0
  281. package/studio/src/lib/capstone.js +663 -0
  282. package/studio/src/lib/chat-store.js +128 -0
  283. package/studio/src/lib/course-export.js +38 -0
  284. package/studio/src/lib/course.js +187 -0
  285. package/studio/src/lib/exercises/journal-entry.js +259 -0
  286. package/studio/src/lib/exercises/placement.js +31 -0
  287. package/studio/src/lib/exercises/registry.js +19 -0
  288. package/studio/src/lib/exercises/spec.js +129 -0
  289. package/studio/src/lib/i18n/detect.js +162 -0
  290. package/studio/src/lib/i18n/en/app.json +23 -0
  291. package/studio/src/lib/i18n/en/betaReport.json +55 -0
  292. package/studio/src/lib/i18n/en/capstone.json +57 -0
  293. package/studio/src/lib/i18n/en/common.json +25 -0
  294. package/studio/src/lib/i18n/en/course.json +27 -0
  295. package/studio/src/lib/i18n/en/data.json +35 -0
  296. package/studio/src/lib/i18n/en/durability.json +5 -0
  297. package/studio/src/lib/i18n/en/errors.json +20 -0
  298. package/studio/src/lib/i18n/en/exercises.json +55 -0
  299. package/studio/src/lib/i18n/en/externalEvidence.json +76 -0
  300. package/studio/src/lib/i18n/en/home.json +18 -0
  301. package/studio/src/lib/i18n/en/lesson.json +33 -0
  302. package/studio/src/lib/i18n/en/nav.json +8 -0
  303. package/studio/src/lib/i18n/en/newCourse.json +51 -0
  304. package/studio/src/lib/i18n/en/onboarding.json +35 -0
  305. package/studio/src/lib/i18n/en/playwrightTemplate.json +20 -0
  306. package/studio/src/lib/i18n/en/practice.json +79 -0
  307. package/studio/src/lib/i18n/en/provider.json +27 -0
  308. package/studio/src/lib/i18n/en/providerMeta.json +26 -0
  309. package/studio/src/lib/i18n/en/reflection.json +17 -0
  310. package/studio/src/lib/i18n/en/revision.json +52 -0
  311. package/studio/src/lib/i18n/en/runnerNotice.json +14 -0
  312. package/studio/src/lib/i18n/en/settings.json +12 -0
  313. package/studio/src/lib/i18n/en/storage.json +49 -0
  314. package/studio/src/lib/i18n/en/tutor.json +39 -0
  315. package/studio/src/lib/i18n/en/workspace.json +50 -0
  316. package/studio/src/lib/i18n/index.js +144 -0
  317. package/studio/src/lib/i18n/languages.js +93 -0
  318. package/studio/src/lib/i18n/vi/app.json +23 -0
  319. package/studio/src/lib/i18n/vi/betaReport.json +55 -0
  320. package/studio/src/lib/i18n/vi/capstone.json +57 -0
  321. package/studio/src/lib/i18n/vi/common.json +25 -0
  322. package/studio/src/lib/i18n/vi/course.json +27 -0
  323. package/studio/src/lib/i18n/vi/data.json +35 -0
  324. package/studio/src/lib/i18n/vi/durability.json +5 -0
  325. package/studio/src/lib/i18n/vi/errors.json +20 -0
  326. package/studio/src/lib/i18n/vi/exercises.json +55 -0
  327. package/studio/src/lib/i18n/vi/externalEvidence.json +76 -0
  328. package/studio/src/lib/i18n/vi/home.json +18 -0
  329. package/studio/src/lib/i18n/vi/lesson.json +33 -0
  330. package/studio/src/lib/i18n/vi/nav.json +8 -0
  331. package/studio/src/lib/i18n/vi/newCourse.json +51 -0
  332. package/studio/src/lib/i18n/vi/onboarding.json +35 -0
  333. package/studio/src/lib/i18n/vi/playwrightTemplate.json +20 -0
  334. package/studio/src/lib/i18n/vi/practice.json +79 -0
  335. package/studio/src/lib/i18n/vi/provider.json +27 -0
  336. package/studio/src/lib/i18n/vi/providerMeta.json +26 -0
  337. package/studio/src/lib/i18n/vi/reflection.json +17 -0
  338. package/studio/src/lib/i18n/vi/revision.json +52 -0
  339. package/studio/src/lib/i18n/vi/runnerNotice.json +14 -0
  340. package/studio/src/lib/i18n/vi/settings.json +12 -0
  341. package/studio/src/lib/i18n/vi/storage.json +49 -0
  342. package/studio/src/lib/i18n/vi/tutor.json +39 -0
  343. package/studio/src/lib/i18n/vi/workspace.json +50 -0
  344. package/studio/src/lib/ids.js +10 -0
  345. package/studio/src/lib/json.js +26 -0
  346. package/studio/src/lib/markdown.js +74 -0
  347. package/studio/src/lib/prompts/base.js +139 -0
  348. package/studio/src/lib/prompts/capstone.js +777 -0
  349. package/studio/src/lib/prompts/course.js +150 -0
  350. package/studio/src/lib/prompts/lesson.js +275 -0
  351. package/studio/src/lib/prompts/practice.js +511 -0
  352. package/studio/src/lib/prompts/tutor.js +509 -0
  353. package/studio/src/lib/repo/blocked-adapter.js +69 -0
  354. package/studio/src/lib/repo/events.js +239 -0
  355. package/studio/src/lib/repo/idb-adapter.js +226 -0
  356. package/studio/src/lib/repo/index.js +1315 -0
  357. package/studio/src/lib/repo/memory-adapter.js +115 -0
  358. package/studio/src/lib/repo/remote-adapter.js +158 -0
  359. package/studio/src/lib/repo/schema.js +143 -0
  360. package/studio/src/lib/repo/select-adapter.js +345 -0
  361. package/studio/src/lib/router.js +71 -0
  362. package/studio/src/lib/runner/browser.js +244 -0
  363. package/studio/src/lib/runner/checks.js +248 -0
  364. package/studio/src/lib/runner/current-code.js +98 -0
  365. package/studio/src/lib/runner/esm-cjs.js +109 -0
  366. package/studio/src/lib/runner/hash.js +34 -0
  367. package/studio/src/lib/runner/history.js +48 -0
  368. package/studio/src/lib/runner/index.js +168 -0
  369. package/studio/src/lib/runner/languages.js +258 -0
  370. package/studio/src/lib/runner/local.js +139 -0
  371. package/studio/src/lib/runner/path.js +104 -0
  372. package/studio/src/lib/runner/skeleton.js +315 -0
  373. package/studio/src/lib/runner/strip-types.js +134 -0
  374. package/studio/src/lib/settings.js +399 -0
  375. package/studio/src/lib/srs.js +39 -0
  376. package/templates/agent/settings.json +6 -0
  377. package/templates/claude/plugin.json +139 -0
  378. package/templates/claude/settings.json +15 -0
  379. package/templates/cursor/professor.mdc +4 -0
  380. package/templates/cursor/settings.json +18 -0
  381. package/templates/gemini/GEMINI.md +28 -0
  382. package/templates/gemini/settings.json +5 -0
  383. package/templates/opencode/opencode.json +3 -0
  384. package/templates/researcher/README.md +61 -0
  385. package/templates/researcher/settings.json +18 -0
  386. package/web/client/components.json +15 -0
  387. package/web/client/index.html +12 -0
  388. package/web/client/package-lock.json +8732 -0
  389. package/web/client/package.json +39 -0
  390. package/web/client/postcss.config.js +6 -0
  391. package/web/client/src/App.jsx +140 -0
  392. package/web/client/src/api/client.js +357 -0
  393. package/web/client/src/components/ChatPanel.jsx +417 -0
  394. package/web/client/src/components/CommandPills.jsx +50 -0
  395. package/web/client/src/components/DeprecationBanner.jsx +21 -0
  396. package/web/client/src/components/ExerciseEditor.jsx +164 -0
  397. package/web/client/src/components/Header.jsx +119 -0
  398. package/web/client/src/components/LecturePanel.jsx +342 -0
  399. package/web/client/src/components/MobileTabSwitcher.jsx +51 -0
  400. package/web/client/src/components/SplitPane.jsx +42 -0
  401. package/web/client/src/components/ui/alert.jsx +38 -0
  402. package/web/client/src/components/ui/badge.jsx +24 -0
  403. package/web/client/src/components/ui/button.jsx +23 -0
  404. package/web/client/src/components/ui/select.jsx +74 -0
  405. package/web/client/src/hooks/useSSE.js +152 -0
  406. package/web/client/src/hooks/useWebSocket.js +98 -0
  407. package/web/client/src/index.css +23 -0
  408. package/web/client/src/lib/utils.js +6 -0
  409. package/web/client/src/main.jsx +12 -0
  410. package/web/client/src/utils/markdown.js +50 -0
  411. package/web/client/tailwind.config.js +8 -0
  412. package/web/client/vite.config.js +21 -0
  413. package/web/dist/assets/index-C1W0eXIQ.js +294 -0
  414. package/web/dist/assets/index-C3OUx70T.css +1 -0
  415. package/web/dist/index.html +13 -0
  416. package/web/lecture-archive.js +172 -0
  417. package/web/legacy-server.js +1277 -0
  418. package/web/package-lock.json +855 -0
  419. package/web/package.json +10 -0
  420. package/web/security.js +1016 -0
  421. package/web/server.js +390 -0
  422. package/web/studio-api/agents.js +580 -0
  423. package/web/studio-api/bridge.js +199 -0
  424. package/web/studio-api/db.js +66 -0
  425. package/web/studio-api/guards.js +201 -0
  426. package/web/studio-api/health.js +538 -0
  427. package/web/studio-api.js +214 -0
  428. package/web/studio-db.js +380 -0
  429. package/web/studio-runner.js +568 -0
@@ -0,0 +1,1277 @@
1
+ /**
2
+ * web/legacy-server.js — the opt-in legacy HTTP surface.
3
+ *
4
+ * Everything the deprecated React client needs lives here: course read/write routes, agent
5
+ * capability probes, the SSE chat proxy and the notification placeholder. The router is only
6
+ * mounted by `createApp({ legacy: true })`; importing this module has no side effects (no listen,
7
+ * no spawn, no directory creation, no logging).
8
+ *
9
+ * Security contract (Phase 2):
10
+ * - Every route sits behind the same Host -> Origin -> token -> JSON guards as Studio.
11
+ * - Slugs, course filenames and exercise filenames are exact allowlists and every path goes
12
+ * through `security.resolveInside` (decode, lexical + realpath/symlink containment).
13
+ * - Agent spawns reuse the Plan 04 hardened runners (allowlisted env, temp cwd, shell-less,
14
+ * deny-checked argv); no legacy bypass flag/env survives.
15
+ * - Capability/model probes run through a 30s TTL cache backed by the shared shell-less
16
+ * `detectAgents`/`listAgentModels`, never a per-request `which` probe.
17
+ */
18
+ import express from 'express';
19
+ import { spawn } from 'child_process';
20
+ import {
21
+ existsSync,
22
+ lstatSync,
23
+ readFileSync,
24
+ readdirSync,
25
+ realpathSync,
26
+ } from 'fs';
27
+ import { join, resolve, sep } from 'path';
28
+
29
+ import { archiveLecture } from './lecture-archive.js';
30
+ import { installGuards } from './studio-api/guards.js';
31
+ import {
32
+ detectAgents,
33
+ listAgentModels,
34
+ } from './studio-api/health.js';
35
+ import {
36
+ buildAgentArgs,
37
+ defaultAgentRunners,
38
+ } from './studio-api/agents.js';
39
+ import * as security from './security.js';
40
+
41
+
42
+ /* ------------------------------------------------------------------ constants */
43
+
44
+ export const LEGACY_COURSE_FILES = Object.freeze([
45
+ 'COURSE.md',
46
+ 'LECTURE.md',
47
+ 'NOTES.md',
48
+ 'CAPSTONE.md',
49
+ ]);
50
+
51
+ const LEGACY_CAPABILITY_TTL_MS = 30000;
52
+
53
+ // Professor system prompt — instructs the AI to behave as a Socratic teaching assistant and to
54
+ // wrap any course files it creates in <file path="...">...</file> tags so the server can persist
55
+ // them. Moved verbatim from the pre-Phase-2 server.
56
+ export const PROFESSOR_SYSTEM_PROMPT = `You are Professor Claude — a Socratic technology mentor built into a web-based learning app.
57
+
58
+ ## Your role
59
+ Teach users by asking questions, NOT by giving answers. Guide them to discover concepts themselves.
60
+ - Never write working code for the user
61
+ - Never complete exercises on their behalf
62
+ - Always ask "What have you tried?" before offering hints
63
+ - Give hints in layers: conceptual → pattern/tool → pseudo-code only
64
+
65
+ ## Commands you handle
66
+ - \`professor:new-topic\` — Ask what they want to learn and their level (Beginner/Intermediate/Advanced/Expert), then create a course
67
+ - \`professor:next\` — Load the next not-started section into LECTURE.md
68
+ - \`professor:review\` — Socratic review: what's working → question → concept to study → next action
69
+ - \`professor:done\` — Confirm understanding verbally, then mark section complete
70
+ - \`professor:hint\` — Layer 1 (concept) → Layer 2 (tool/pattern) → Layer 3 (pseudo-code only)
71
+ - \`professor:stuck\` — Walk through what they tried → exact sticking point → smaller steps → analogy
72
+ - \`professor:discuss\` — Conceptual Q&A only
73
+ - \`professor:quiz\` — 5 questions matched to their level
74
+ - \`professor:syllabus\` — Describe course outline from COURSE.md
75
+ - \`professor:progress\` — Summarize completed/current/remaining sections
76
+
77
+ ## Creating course files
78
+ When creating or updating course files, include them in your response wrapped in XML tags.
79
+ The app will save them automatically — do NOT mention the tags to the user.
80
+
81
+ When creating a NEW course (professor:new-topic), derive a URL-safe slug from the topic name
82
+ (e.g., "React Hooks" → "react-hooks") and include the slug in the path:
83
+
84
+ <file path="courses/react-hooks/COURSE.md">
85
+ [full file content here]
86
+ </file>
87
+
88
+ <file path="courses/react-hooks/CAPSTONE.md">
89
+ [full file content here]
90
+ </file>
91
+
92
+ When updating an EXISTING course file (professor:next, professor:done, etc.), use just the filename:
93
+
94
+ <file path="LECTURE.md">
95
+ [full file content here]
96
+ </file>
97
+
98
+ <file path="COURSE.md">
99
+ [updated content here]
100
+ </file>
101
+
102
+ ## COURSE.md format
103
+ \`\`\`
104
+ # Course: {Topic Name}
105
+ **Level**: {Beginner/Intermediate/Advanced/Expert}
106
+ **Created**: {date}
107
+ **Last active**: {date}
108
+
109
+ ## Syllabus
110
+ - ⬜ Section 1: {Name}
111
+ - ⬜ Section 2: {Name}
112
+ ...
113
+
114
+ ## Progress Log
115
+ (entries added as sections are completed)
116
+ \`\`\`
117
+
118
+ Status icons: ⬜ Not started | 🔄 In progress | ✅ Done
119
+
120
+ ## LECTURE.md format
121
+ \`\`\`
122
+ # Section N: {Name}
123
+ **Status**: 🔄 In progress
124
+
125
+ ## Concepts
126
+ [key concepts explained clearly]
127
+
128
+ ## Exercise
129
+ [one focused exercise — they must solve it themselves]
130
+
131
+ ## What to do
132
+ Read through this, then attempt the exercise. Use \`professor:review\` when ready, or \`professor:hint\` if stuck.
133
+ \`\`\`
134
+ `;
135
+
136
+ /* ------------------------------------------------------------------ path helpers */
137
+
138
+ function unsafe(message, status = 400) {
139
+ const err = new Error(message);
140
+ err.code = 'unsafe_path';
141
+ err.status = status;
142
+ return err;
143
+ }
144
+
145
+ function isSymlink(path) {
146
+ try {
147
+ return lstatSync(path).isSymbolicLink();
148
+ } catch {
149
+ return false;
150
+ }
151
+ }
152
+
153
+ function isDirectory(path) {
154
+ try {
155
+ return lstatSync(path).isDirectory();
156
+ } catch {
157
+ return false;
158
+ }
159
+ }
160
+
161
+ function realWithin(child, parent) {
162
+ try {
163
+ const realChild = realpathSync.native(child);
164
+ const realParent = realpathSync.native(parent);
165
+ return realChild === realParent || realChild.startsWith(realParent + sep);
166
+ } catch {
167
+ return false;
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Decode a route param exactly once before validation. Express has already decoded it, so a
173
+ * surviving `%` means the value was double encoded and is rejected by the allowlists anyway.
174
+ * @param {unknown} value
175
+ * @returns {string|null}
176
+ */
177
+ function decodeParam(value) {
178
+ if (typeof value !== 'string') return null;
179
+ try {
180
+ return decodeURIComponent(value);
181
+ } catch {
182
+ return null;
183
+ }
184
+ }
185
+
186
+ /**
187
+ * List courses under `coursesDir`. Symlinked course directories are skipped and a symlinked
188
+ * COURSE.md is never read for metadata.
189
+ * @param {string} [coursesDir]
190
+ * @returns {Array<{name: string, slug: string, description: string}>}
191
+ */
192
+ export function getCourses(coursesDir) {
193
+ const root = resolve(coursesDir);
194
+ if (!existsSync(root)) return [];
195
+
196
+ let entries;
197
+ try {
198
+ entries = readdirSync(root, { withFileTypes: true });
199
+ } catch {
200
+ return [];
201
+ }
202
+
203
+ const courses = [];
204
+ for (const entry of entries) {
205
+ if (!entry.isDirectory()) continue;
206
+ if (!security.isSafeSlug(entry.name)) continue;
207
+
208
+ const courseDir = join(root, entry.name);
209
+ if (isSymlink(courseDir)) continue;
210
+
211
+ const metadata = { name: entry.name, slug: entry.name, description: '' };
212
+ const courseFile = join(courseDir, 'COURSE.md');
213
+
214
+ if (existsSync(courseFile) && !isSymlink(courseFile)) {
215
+ try {
216
+ const raw = security.resolveInside(root, entry.name, 'COURSE.md');
217
+ const content = readFileSync(raw, 'utf-8');
218
+ const titleMatch = content.match(/^#\s+(.+)$/m);
219
+ if (titleMatch) metadata.name = titleMatch[1];
220
+ const descMatch = content.match(/^#\s+.+\n\n(.+?)(?:\n\n#|\n$)/m);
221
+ if (descMatch) metadata.description = descMatch[1].substring(0, 200);
222
+ } catch {
223
+ /* unreadable or unsafe: keep the slug-only metadata */
224
+ }
225
+ }
226
+
227
+ courses.push(metadata);
228
+ }
229
+
230
+ return courses;
231
+ }
232
+
233
+ /**
234
+ * Read one of the four known course files.
235
+ * @param {string} slug
236
+ * @param {string} file
237
+ * @param {string} [coursesDir]
238
+ * @returns {string|null}
239
+ */
240
+ export function getCourseFile(slug, file, coursesDir) {
241
+ if (!security.isSafeSlug(slug) || !security.isSafeCourseFile(file)) return null;
242
+
243
+ let filePath;
244
+ try {
245
+ filePath = security.resolveInside(coursesDir, slug, file);
246
+ } catch {
247
+ return null;
248
+ }
249
+
250
+ if (isSymlink(filePath) || !existsSync(filePath)) return null;
251
+ try {
252
+ if (!lstatSync(filePath).isFile()) return null;
253
+ return readFileSync(filePath, 'utf-8');
254
+ } catch {
255
+ return null;
256
+ }
257
+ }
258
+
259
+ /**
260
+ * All exercises for a course. Symlinked exercise files and a symlinked `exercises` directory are
261
+ * skipped, never read.
262
+ * @param {string} slug
263
+ * @param {string} [coursesDir]
264
+ * @returns {Array<{filename: string, path: string, content: string}>}
265
+ */
266
+ export function getExercises(slug, coursesDir) {
267
+ if (!security.isSafeSlug(slug)) return [];
268
+
269
+ let exercisesDir;
270
+ try {
271
+ exercisesDir = security.resolveInside(coursesDir, slug, 'exercises');
272
+ } catch {
273
+ return [];
274
+ }
275
+ if (!isDirectory(exercisesDir) || isSymlink(exercisesDir)) return [];
276
+
277
+ let entries;
278
+ try {
279
+ entries = readdirSync(exercisesDir, { withFileTypes: true });
280
+ } catch {
281
+ return [];
282
+ }
283
+
284
+ const exercises = [];
285
+ for (const entry of entries) {
286
+ if (!entry.isFile()) continue;
287
+ if (!security.isSafeExerciseFilename(entry.name)) continue;
288
+
289
+ let filePath;
290
+ try {
291
+ filePath = security.resolveInside(coursesDir, slug, 'exercises', entry.name);
292
+ } catch {
293
+ continue;
294
+ }
295
+ if (isSymlink(filePath)) continue;
296
+
297
+ try {
298
+ exercises.push({
299
+ filename: entry.name,
300
+ path: `exercises/${entry.name}`,
301
+ content: readFileSync(filePath, 'utf-8'),
302
+ });
303
+ } catch {
304
+ /* skip unreadable file */
305
+ }
306
+ }
307
+
308
+ return exercises;
309
+ }
310
+
311
+ /**
312
+ * Active exercise filename recorded in COURSE.md.
313
+ * @param {string} slug
314
+ * @param {string} [coursesDir]
315
+ * @returns {string|null}
316
+ */
317
+ export function getActiveExercise(slug, coursesDir) {
318
+ const courseContent = getCourseFile(slug, 'COURSE.md', coursesDir);
319
+ if (!courseContent) return null;
320
+ const match = courseContent.match(/Active exercise:\s*exercises\/([^\s]+)/i);
321
+ return match ? match[1] : null;
322
+ }
323
+
324
+ /**
325
+ * Save one of the four course files. The LECTURE archive path is validated before
326
+ * `archiveLecture` is called; a symlinked `lectures` directory rejects the write.
327
+ *
328
+ * @param {string} slug
329
+ * @param {string} file
330
+ * @param {string} content
331
+ * @param {{ coursesDir: string, log?: (...a:any[])=>void }} options
332
+ * @returns {{ success: boolean, error?: string, code?: string, status?: number }}
333
+ */
334
+ export function saveCourseFile(slug, file, content, { coursesDir, log = () => {} } = {}) {
335
+ if (!security.isSafeSlug(slug) || !security.isSafeCourseFile(file)) {
336
+ return { success: false, error: 'Invalid course file', code: 'unsafe_path', status: 400 };
337
+ }
338
+ if (typeof content !== 'string') {
339
+ return { success: false, error: 'Content is required', code: 'invalid_request', status: 400 };
340
+ }
341
+
342
+ const root = resolve(coursesDir);
343
+ let courseDir;
344
+ let filePath;
345
+ try {
346
+ courseDir = security.resolveInside(root, slug);
347
+ filePath = security.resolveInside(root, slug, file);
348
+ } catch (err) {
349
+ const status = isSymlink(join(root, slug)) ? 403 : 400;
350
+ return { success: false, error: err.message, code: 'unsafe_path', status };
351
+ }
352
+
353
+ if (isSymlink(courseDir)) {
354
+ return {
355
+ success: false,
356
+ error: 'Refusing to write through a symlinked course directory',
357
+ code: 'unsafe_path',
358
+ status: 403,
359
+ };
360
+ }
361
+ if (isSymlink(filePath)) {
362
+ return {
363
+ success: false,
364
+ error: 'Refusing to write through a symlinked file',
365
+ code: 'unsafe_path',
366
+ status: 403,
367
+ };
368
+ }
369
+
370
+ if (file === 'LECTURE.md' && existsSync(filePath)) {
371
+ const lecturesDir = join(courseDir, 'lectures');
372
+ let lecturesInfo = null;
373
+ try {
374
+ lecturesInfo = lstatSync(lecturesDir);
375
+ } catch {
376
+ lecturesInfo = null;
377
+ }
378
+ if (lecturesInfo) {
379
+ if (lecturesInfo.isSymbolicLink()) {
380
+ return {
381
+ success: false,
382
+ error: 'Refusing to archive through a symlinked lectures directory',
383
+ code: 'unsafe_path',
384
+ status: 403,
385
+ };
386
+ }
387
+ if (!lecturesInfo.isDirectory() || !realWithin(lecturesDir, courseDir)) {
388
+ return {
389
+ success: false,
390
+ error: 'Unsafe lectures directory',
391
+ code: 'unsafe_path',
392
+ status: 403,
393
+ };
394
+ }
395
+ }
396
+
397
+ const result = archiveLecture(courseDir, content);
398
+ if (result.archived) {
399
+ log(`Archived previous lecture -> courses/${slug}/${result.path}`);
400
+ }
401
+ }
402
+
403
+ try {
404
+ security.safeWriteFile(root, [slug, file], content);
405
+ return { success: true };
406
+ } catch (err) {
407
+ const status = err.code === 'ELOOP' || isSymlink(filePath) ? 403 : 400;
408
+ return {
409
+ success: false,
410
+ error: err.message,
411
+ code: err.code === 'unsafe_path' ? 'unsafe_path' : 'write_failed',
412
+ status,
413
+ };
414
+ }
415
+ }
416
+
417
+ /**
418
+ * Save an exercise file under `<course>/exercises`.
419
+ * @param {string} slug
420
+ * @param {string} filename
421
+ * @param {string} content
422
+ * @param {{ coursesDir: string, log?: (...a:any[])=>void }} options
423
+ * @returns {{ success: boolean, error?: string, code?: string, status?: number }}
424
+ */
425
+ export function saveExerciseFile(slug, filename, content, { coursesDir, log = () => {} } = {}) {
426
+ if (!security.isSafeSlug(slug) || !security.isSafeExerciseFilename(filename)) {
427
+ return { success: false, error: 'Invalid exercise filename', code: 'unsafe_path', status: 400 };
428
+ }
429
+ if (typeof content !== 'string') {
430
+ return { success: false, error: 'Content is required', code: 'invalid_request', status: 400 };
431
+ }
432
+
433
+ const root = resolve(coursesDir);
434
+ let courseDir;
435
+ try {
436
+ courseDir = security.resolveInside(root, slug);
437
+ } catch (err) {
438
+ return { success: false, error: err.message, code: 'unsafe_path', status: 400 };
439
+ }
440
+ if (isSymlink(courseDir)) {
441
+ return {
442
+ success: false,
443
+ error: 'Refusing to write through a symlinked course directory',
444
+ code: 'unsafe_path',
445
+ status: 403,
446
+ };
447
+ }
448
+
449
+ const exercisesDir = join(courseDir, 'exercises');
450
+ if (isSymlink(exercisesDir)) {
451
+ return {
452
+ success: false,
453
+ error: 'Refusing to write through a symlinked exercises directory',
454
+ code: 'unsafe_path',
455
+ status: 403,
456
+ };
457
+ }
458
+ if (existsSync(exercisesDir) && !isDirectory(exercisesDir)) {
459
+ return { success: false, error: 'Invalid exercises path', code: 'unsafe_path', status: 400 };
460
+ }
461
+
462
+ try {
463
+ security.safeWriteFile(root, [slug, 'exercises', filename], content);
464
+ log(`Saved exercise ${filename} -> courses/${slug}/exercises/`);
465
+ return { success: true };
466
+ } catch (err) {
467
+ const status = err.code === 'ELOOP' ? 403 : 400;
468
+ return {
469
+ success: false,
470
+ error: err.message,
471
+ code: err.code === 'unsafe_path' ? 'unsafe_path' : 'write_failed',
472
+ status,
473
+ };
474
+ }
475
+ }
476
+
477
+ /**
478
+ * Parse `<file path="...">...</file>` blocks from an AI response and save them, scoped to the
479
+ * current course (D-25).
480
+ *
481
+ * - With `courseSlug`: only bare `FILE.md` and `courses/<courseSlug>/FILE.md` are honored.
482
+ * - Without: exactly one `courses/<valid-slug>/...` is accepted when that directory does not
483
+ * already exist, and that slug is adopted for the rest of the response.
484
+ *
485
+ * @param {string} fullText
486
+ * @param {string} courseSlug
487
+ * @param {{ coursesDir: string, log?: (...a:any[])=>void }} options
488
+ * @returns {Array<{ slug: string, file: string }>}
489
+ */
490
+ export function saveFilesFromResponse(fullText, courseSlug, { coursesDir, log = () => {} } = {}) {
491
+ const saved = [];
492
+ if (typeof fullText !== 'string' || !coursesDir) return saved;
493
+
494
+ const hasCurrent = typeof courseSlug === 'string' && courseSlug.length > 0;
495
+ if (hasCurrent && !security.isSafeSlug(courseSlug)) return saved;
496
+
497
+ let effectiveSlug = hasCurrent ? courseSlug : '';
498
+ let adopted = false;
499
+
500
+ const fileRegex = /<file path="([^"]+)">([\s\S]*?)<\/file>/g;
501
+ let match;
502
+
503
+ while ((match = fileRegex.exec(fullText)) !== null) {
504
+ const [, rawPath, content] = match;
505
+ const target = String(rawPath || '').trim();
506
+ if (!target) continue;
507
+
508
+ const coursePathMatch = target.match(/^courses\/([^/]+)\/([^/]+)$/);
509
+ let slug;
510
+ let fileName;
511
+
512
+ if (coursePathMatch) {
513
+ const pathSlug = coursePathMatch[1];
514
+ fileName = coursePathMatch[2];
515
+ if (!security.isSafeSlug(pathSlug) || !security.isSafeCourseFile(fileName)) continue;
516
+
517
+ if (effectiveSlug) {
518
+ if (pathSlug !== effectiveSlug) continue;
519
+ } else if (adopted) {
520
+ if (pathSlug !== effectiveSlug) continue;
521
+ } else {
522
+ // Legacy new-topic: allow one brand-new course directory and adopt it.
523
+ let existing = false;
524
+ try {
525
+ existing = existsSync(security.resolveInside(coursesDir, pathSlug));
526
+ } catch {
527
+ continue;
528
+ }
529
+ if (existing) continue;
530
+ effectiveSlug = pathSlug;
531
+ adopted = true;
532
+ }
533
+ slug = pathSlug;
534
+ } else {
535
+ if (target.includes('/') || target.includes('\\')) continue;
536
+ if (!effectiveSlug || !security.isSafeCourseFile(target)) continue;
537
+ slug = effectiveSlug;
538
+ fileName = target;
539
+ }
540
+
541
+ try {
542
+ security.resolveInside(coursesDir, slug, fileName);
543
+ } catch {
544
+ continue;
545
+ }
546
+
547
+ const result = saveCourseFile(slug, fileName, content.trim(), { coursesDir, log });
548
+ if (result.success) {
549
+ saved.push({ slug, file: fileName });
550
+ log(`Saved ${fileName} -> courses/${slug}/`);
551
+ }
552
+ }
553
+
554
+ return saved;
555
+ }
556
+
557
+ /* ------------------------------------------------------------------ capability cache */
558
+
559
+ /**
560
+ * Tiny async TTL cache used for capability and model probes (CONCERNS #6). Keys are independent;
561
+ * concurrent misses for the same key share one in-flight probe.
562
+ *
563
+ * @param {{ ttlMs?: number, now?: () => number,
564
+ * probe: (key: string, args?: object) => any }} options
565
+ * @returns {{ get: (key?: string, args?: object) => Promise<any>,
566
+ * invalidate: (key?: string) => void, size: number }}
567
+ */
568
+ export function createCapabilityCache({
569
+ ttlMs = LEGACY_CAPABILITY_TTL_MS,
570
+ now = Date.now,
571
+ probe,
572
+ } = {}) {
573
+ if (typeof probe !== 'function') {
574
+ throw new TypeError('createCapabilityCache requires a probe function');
575
+ }
576
+
577
+ const entries = new Map();
578
+ const pending = new Map();
579
+
580
+ return {
581
+ async get(key = 'capabilities', args) {
582
+ const hit = entries.get(key);
583
+ if (hit && now() - hit.at < ttlMs) return hit.value;
584
+
585
+ if (pending.has(key)) return pending.get(key);
586
+
587
+ const promise = Promise.resolve()
588
+ .then(() => probe(key, args))
589
+ .then((value) => {
590
+ entries.set(key, { at: now(), value });
591
+ return value;
592
+ })
593
+ .finally(() => {
594
+ pending.delete(key);
595
+ });
596
+
597
+ pending.set(key, promise);
598
+ return promise;
599
+ },
600
+ invalidate(key) {
601
+ if (key === undefined) entries.clear();
602
+ else entries.delete(key);
603
+ },
604
+ get size() {
605
+ return entries.size;
606
+ },
607
+ };
608
+ }
609
+
610
+ /* ------------------------------------------------------------------ capabilities */
611
+
612
+ function legacyCapabilities(base = {}, env = process.env, useCli) {
613
+ const out = {};
614
+ const source = base && typeof base === 'object' ? base : {};
615
+
616
+ const defaults = {
617
+ claude: { installed: false, supportsResume: true, supportsModelSelection: false },
618
+ cursor: { installed: false, supportsResume: true, supportsModelSelection: true },
619
+ opencode: { installed: false, supportsResume: true, supportsModelSelection: true },
620
+ ollama: { installed: false, supportsResume: false, supportsModelSelection: true },
621
+ };
622
+
623
+ for (const [agent, fallback] of Object.entries(defaults)) {
624
+ const entry = source[agent] || {};
625
+ out[agent] = {
626
+ ...fallback,
627
+ ...entry,
628
+ installed: Boolean(entry.installed ?? fallback.installed),
629
+ supportsStreaming: true,
630
+ };
631
+ }
632
+ if (useCli === true) out.claude.installed = true;
633
+ if (out.ollama) {
634
+ out.ollama.daemonReady = Boolean(out.ollama.reachable ?? out.ollama.daemonReady);
635
+ }
636
+
637
+ out.cloud = {
638
+ available: Boolean(
639
+ env.ANTHROPIC_API_KEY || env.CLAUDE_API_KEY || env.OPENAI_API_KEY
640
+ ),
641
+ supportsStreaming: true,
642
+ supportsResume: false,
643
+ supportsModelSelection: true,
644
+ };
645
+
646
+ return out;
647
+ }
648
+
649
+ /**
650
+ * Resolve the provider the legacy chat should use.
651
+ * @param {string} requestedProvider
652
+ * @param {ReturnType<typeof legacyCapabilities>} capabilities
653
+ * @returns {string}
654
+ */
655
+ export function resolveProvider(requestedProvider, capabilities) {
656
+ if (requestedProvider && requestedProvider !== 'auto') {
657
+ if (requestedProvider === 'cloud') {
658
+ return capabilities.cloud?.available ? 'cloud' : 'none';
659
+ }
660
+ if (!capabilities[requestedProvider]?.installed) return 'none';
661
+ return requestedProvider;
662
+ }
663
+
664
+ const priority = ['claude', 'cursor', 'opencode', 'ollama', 'cloud'];
665
+ for (const provider of priority) {
666
+ if (provider === 'cloud' && capabilities.cloud?.available) return provider;
667
+ if (provider !== 'cloud' && capabilities[provider]?.installed) return provider;
668
+ }
669
+ return 'none';
670
+ }
671
+
672
+ function cloudModels(env) {
673
+ return env.OPENAI_API_KEY ? ['gpt-4o', 'gpt-4.1-mini'] : ['claude-sonnet-4-6'];
674
+ }
675
+
676
+ /* ------------------------------------------------------------------ agent runners */
677
+
678
+ /**
679
+ * Claude CLI detection without a shell (replaces the old per-request `which claude` probe).
680
+ * @param {{ platform?: string, pathValue?: string, fs?: object, pathext?: string }} [opts]
681
+ * @returns {boolean}
682
+ */
683
+ export function claudeCLIAvailable(opts = {}) {
684
+ try {
685
+ return Boolean(security.resolveExecutable('claude', opts));
686
+ } catch {
687
+ return false;
688
+ }
689
+ }
690
+
691
+ /**
692
+ * The legacy spawn factory. It delegates to Plan 04's hardened `defaultAgentRunners`, which owns
693
+ * the shell-less spawn, temp cwd, allowlisted env and pre-spawn argv assertion. `extraEnv` is the
694
+ * test-only capture hook; production callers pass nothing.
695
+ *
696
+ * @param {{ extraEnv?: Record<string, string|undefined> }} [options]
697
+ * @returns {Record<string, Function>}
698
+ */
699
+ export function createLegacyAgentRunners({ extraEnv = {} } = {}) {
700
+ return defaultAgentRunners({ extraEnv });
701
+ }
702
+
703
+ /**
704
+ * Safe argv for a legacy chat turn. Plan 04's builder is the single source of flags; the pre-spawn
705
+ * assertion in `runJsonCli` re-checks it.
706
+ * @param {string} agent
707
+ * @param {{ system?: string, prompt: string, model?: string }} ctx
708
+ * @returns {string[]}
709
+ */
710
+ export function legacyAgentArgs(agent, ctx) {
711
+ return buildAgentArgs(agent, ctx);
712
+ }
713
+
714
+ /* ------------------------------------------------------------------ SSE helpers */
715
+
716
+ function sendSSE(res, payload) {
717
+ if (!res.writableEnded) res.write(`data: ${JSON.stringify(payload)}\n\n`);
718
+ }
719
+
720
+ function sendSSEError(res, code, message, details = {}) {
721
+ sendSSE(res, { error: message, errorCode: code, ...details });
722
+ if (!res.writableEnded) res.end();
723
+ }
724
+
725
+ function flattenLegacyMessages(system, messages, includeSystem) {
726
+ const parts = [];
727
+ if (includeSystem && system) parts.push(`[System]\n${system}`);
728
+ for (const message of messages || []) {
729
+ const role = message.role === 'assistant' ? 'ASSISTANT' : 'USER';
730
+ parts.push(`${role}: ${message.content}`);
731
+ }
732
+ return parts.join('\n\n');
733
+ }
734
+
735
+ function completeFromText(res, text, courseSlug, { coursesDir, log }) {
736
+ const saved = saveFilesFromResponse(text, courseSlug, { coursesDir, log });
737
+ if (saved.length > 0) {
738
+ const bySlug = {};
739
+ for (const { slug, file } of saved) {
740
+ if (!bySlug[slug]) bySlug[slug] = [];
741
+ bySlug[slug].push(file);
742
+ }
743
+ for (const [slug, files] of Object.entries(bySlug)) {
744
+ sendSSE(res, { filesUpdated: files, courseSlug: slug });
745
+ }
746
+ }
747
+ if (!res.writableEnded) {
748
+ res.write('data: [DONE]\n\n');
749
+ res.end();
750
+ }
751
+ }
752
+
753
+ /* ------------------------------------------------------------------ dev server */
754
+
755
+ /**
756
+ * Spawn Vite only in legacy dev mode, without a shell. Windows `.cmd` shims are unsupported for
757
+ * beta and return the shared structured error instead of an opaque failure (D-16).
758
+ *
759
+ * @param {{ clientDir: string, spawnImpl?: Function, platform?: string,
760
+ * log?: (...a:any[])=>void, env?: NodeJS.ProcessEnv }} [options]
761
+ * @returns {{ child: object|null, error: { code: string, message: string }|null,
762
+ * kill: () => void }}
763
+ */
764
+ export function startLegacyDevServer({
765
+ clientDir,
766
+ spawnImpl = spawn,
767
+ platform = process.platform,
768
+ log = () => {},
769
+ env = process.env,
770
+ } = {}) {
771
+ if (platform === 'win32') {
772
+ const message = security.unsupportedWindowsShimMessage('npm', 'npm.cmd');
773
+ log(`[legacy] ${message}`);
774
+ return { child: null, error: { code: 'unsupported_windows_shim', message }, kill() {} };
775
+ }
776
+
777
+ let command = 'npm';
778
+ try {
779
+ const resolved = security.resolveExecutable('npm', {
780
+ platform,
781
+ pathValue: env?.PATH,
782
+ });
783
+ if (resolved) command = resolved;
784
+ } catch {
785
+ /* fall back to the bare command */
786
+ }
787
+
788
+ const child = spawnImpl(command, ['run', 'dev'], {
789
+ cwd: clientDir,
790
+ shell: false,
791
+ stdio: 'inherit',
792
+ env,
793
+ });
794
+
795
+ child?.on?.('error', (err) => {
796
+ log(`[legacy] Failed to start Vite: ${err.message}`);
797
+ });
798
+
799
+ return {
800
+ child,
801
+ error: null,
802
+ kill() {
803
+ child?.kill?.('SIGTERM');
804
+ },
805
+ };
806
+ }
807
+
808
+ /* ------------------------------------------------------------------ router */
809
+
810
+ /**
811
+ * Build the guarded legacy router.
812
+ *
813
+ * @param {object} options
814
+ * @param {string} options.coursesDir absolute or relative courses root
815
+ * @param {string} [options.token] static token (back-compat)
816
+ * @param {() => string} options.getToken token getter
817
+ * @param {Set<string>|string|string[]} [options.origins]
818
+ * @param {boolean} [options.allowNonLoopback]
819
+ * @param {string[]} [options.extraHosts]
820
+ * @param {Function} [options.spawnImpl]
821
+ * @param {() => object} [options.capabilities]
822
+ * @param {object} [options.capabilityCache]
823
+ * @param {(agent: string, deps: object) => Promise<object>} [options.listAgentModels]
824
+ * @param {Record<string, Function>} [options.runners]
825
+ * @param {Record<string, string|undefined>} [options.extraEnv]
826
+ * @param {boolean} [options.useCli]
827
+ * @param {() => number} [options.now]
828
+ * @param {NodeJS.ProcessEnv} [options.env]
829
+ * @param {Function} [options.fetchImpl]
830
+ * @param {(...a:any[])=>void} [options.log]
831
+ * @returns {import('express').Router}
832
+ */
833
+ export function createLegacyRouter({
834
+ coursesDir,
835
+ token,
836
+ getToken,
837
+ origins,
838
+ allowNonLoopback = false,
839
+ extraHosts = [],
840
+ spawnImpl,
841
+ capabilities = detectAgents,
842
+ capabilityCache,
843
+ listAgentModels: listModels = listAgentModels,
844
+ runners,
845
+ extraEnv = {},
846
+ useCli = false,
847
+ now = Date.now,
848
+ env = process.env,
849
+ fetchImpl = fetch,
850
+ log = () => {},
851
+ } = {}) {
852
+ if (!coursesDir) throw new TypeError('createLegacyRouter requires coursesDir');
853
+ if (typeof getToken !== 'function') {
854
+ throw new TypeError('createLegacyRouter requires a getToken function');
855
+ }
856
+
857
+ const root = resolve(coursesDir);
858
+ const capabilitiesFn =
859
+ typeof capabilities === 'function' ? capabilities : () => capabilities || {};
860
+
861
+ const cache =
862
+ capabilityCache ||
863
+ createCapabilityCache({
864
+ ttlMs: LEGACY_CAPABILITY_TTL_MS,
865
+ now,
866
+ probe: async (key, args = {}) => {
867
+ if (key === 'capabilities') {
868
+ const base = await capabilitiesFn();
869
+ return legacyCapabilities(base, env, useCli);
870
+ }
871
+ if (typeof key === 'string' && key.startsWith('models:')) {
872
+ return listModels(key.slice('models:'.length), {
873
+ env,
874
+ installed: args.installed !== false,
875
+ });
876
+ }
877
+ throw new Error(`Unknown capability cache key: ${key}`);
878
+ },
879
+ });
880
+
881
+ const agentRunners = runners || createLegacyAgentRunners({ extraEnv });
882
+
883
+ const router = express.Router();
884
+ const api = express.Router();
885
+
886
+ installGuards(api, {
887
+ token,
888
+ getToken,
889
+ origins,
890
+ allowNonLoopback,
891
+ extraHosts,
892
+ });
893
+
894
+ /* ---------------------------------------------------------------- course reads */
895
+
896
+ api.get('/courses', (req, res) => {
897
+ res.json(getCourses(root));
898
+ });
899
+
900
+ api.get('/courses/:slug/exercises', (req, res) => {
901
+ const slug = decodeParam(req.params.slug);
902
+ if (!security.isSafeSlug(slug)) {
903
+ res.status(400).json({ error: 'Invalid course slug', code: 'unsafe_path' });
904
+ return;
905
+ }
906
+ res.json({
907
+ exercises: getExercises(slug, root),
908
+ activeExercise: getActiveExercise(slug, root),
909
+ });
910
+ });
911
+
912
+ api.get('/courses/:slug/exercises/:filename', (req, res) => {
913
+ const slug = decodeParam(req.params.slug);
914
+ const filename = decodeParam(req.params.filename);
915
+ if (!security.isSafeSlug(slug) || !security.isSafeExerciseFilename(filename)) {
916
+ res.status(400).json({ error: 'Invalid exercise path', code: 'unsafe_path' });
917
+ return;
918
+ }
919
+
920
+ let filePath;
921
+ try {
922
+ filePath = security.resolveInside(root, slug, 'exercises', filename);
923
+ } catch (err) {
924
+ res.status(403).json({ error: err.message, code: 'unsafe_path' });
925
+ return;
926
+ }
927
+ if (isSymlink(filePath)) {
928
+ res.status(403).json({ error: 'Unsafe exercise path', code: 'unsafe_path' });
929
+ return;
930
+ }
931
+ if (!existsSync(filePath)) {
932
+ res.status(404).json({ error: 'Exercise not found', code: 'not_found' });
933
+ return;
934
+ }
935
+ try {
936
+ const content = readFileSync(filePath, 'utf-8');
937
+ res.json({ content, filename });
938
+ } catch (err) {
939
+ res.status(500).json({ error: err.message });
940
+ }
941
+ });
942
+
943
+ api.get('/courses/:slug/:file', (req, res) => {
944
+ const slug = decodeParam(req.params.slug);
945
+ const file = decodeParam(req.params.file);
946
+ if (!security.isSafeSlug(slug) || !security.isSafeCourseFile(file)) {
947
+ res.status(400).json({ error: 'Invalid course file', code: 'unsafe_path' });
948
+ return;
949
+ }
950
+ const content = getCourseFile(slug, file, root);
951
+ if (content === null) {
952
+ res.status(404).json({ error: 'File not found', code: 'not_found' });
953
+ return;
954
+ }
955
+ res.json({ content });
956
+ });
957
+
958
+ /* ---------------------------------------------------------------- course writes */
959
+
960
+ api.post('/courses/:slug/exercises/:filename', (req, res) => {
961
+ const slug = decodeParam(req.params.slug);
962
+ const filename = decodeParam(req.params.filename);
963
+ if (!security.isSafeSlug(slug) || !security.isSafeExerciseFilename(filename)) {
964
+ res.status(400).json({ error: 'Invalid exercise path', code: 'unsafe_path' });
965
+ return;
966
+ }
967
+ const { content } = req.body || {};
968
+ if (!content) {
969
+ res.status(400).json({ error: 'Content is required' });
970
+ return;
971
+ }
972
+ const result = saveExerciseFile(slug, filename, content, { coursesDir: root, log });
973
+ if (!result.success) {
974
+ res.status(result.status || 400).json({ error: result.error, code: result.code });
975
+ return;
976
+ }
977
+ res.json({ success: true });
978
+ });
979
+
980
+ api.post('/courses/:slug/:file', (req, res) => {
981
+ const slug = decodeParam(req.params.slug);
982
+ const file = decodeParam(req.params.file);
983
+ if (!security.isSafeSlug(slug) || !security.isSafeCourseFile(file)) {
984
+ res.status(400).json({ error: 'Invalid course file', code: 'unsafe_path' });
985
+ return;
986
+ }
987
+ const { content } = req.body || {};
988
+ if (!content) {
989
+ res.status(400).json({ error: 'Content is required' });
990
+ return;
991
+ }
992
+ const result = saveCourseFile(slug, file, content, { coursesDir: root, log });
993
+ if (!result.success) {
994
+ res.status(result.status || 400).json({ error: result.error, code: result.code });
995
+ return;
996
+ }
997
+ res.json({ success: true });
998
+ });
999
+
1000
+ /* ---------------------------------------------------------------- agents */
1001
+
1002
+ api.get('/agents/capabilities', async (req, res) => {
1003
+ try {
1004
+ const capabilitiesValue = await cache.get('capabilities');
1005
+ res.json({ capabilities: capabilitiesValue });
1006
+ } catch (err) {
1007
+ res.status(500).json({ error: err.message, code: err.code || 'server' });
1008
+ }
1009
+ });
1010
+
1011
+ api.get('/agents/models', async (req, res) => {
1012
+ const provider = String(req.query.provider || 'auto');
1013
+ try {
1014
+ const capabilitiesValue = await cache.get('capabilities');
1015
+ const resolved = resolveProvider(provider, capabilitiesValue);
1016
+
1017
+ if (resolved === 'none') {
1018
+ res.json({ provider: resolved, supportsModelSelection: false, allowCustomModel: false, models: [] });
1019
+ return;
1020
+ }
1021
+ if (resolved === 'cloud') {
1022
+ res.json({
1023
+ provider: resolved,
1024
+ supportsModelSelection: true,
1025
+ allowCustomModel: false,
1026
+ models: cloudModels(env),
1027
+ });
1028
+ return;
1029
+ }
1030
+ if (resolved === 'claude') {
1031
+ res.json({
1032
+ provider: resolved,
1033
+ supportsModelSelection: false,
1034
+ allowCustomModel: false,
1035
+ models: [],
1036
+ });
1037
+ return;
1038
+ }
1039
+
1040
+ const result = await cache.get(`models:${resolved}`, {
1041
+ agent: resolved,
1042
+ installed: capabilitiesValue[resolved]?.installed !== false,
1043
+ });
1044
+ const models = (result?.models || [])
1045
+ .map((model) => (typeof model === 'string' ? model : model?.id))
1046
+ .filter(Boolean);
1047
+
1048
+ res.json({
1049
+ provider: resolved,
1050
+ supportsModelSelection: true,
1051
+ allowCustomModel: true,
1052
+ models,
1053
+ });
1054
+ } catch (err) {
1055
+ res.status(500).json({ error: err.message, code: err.code || 'server' });
1056
+ }
1057
+ });
1058
+
1059
+ /* ---------------------------------------------------------------- chat */
1060
+
1061
+ api.post('/chat', async (req, res) => {
1062
+ const body = req.body || {};
1063
+ const messages = Array.isArray(body.messages) ? body.messages : [];
1064
+ const courseSlug = typeof body.courseSlug === 'string' ? body.courseSlug : '';
1065
+ const provider = typeof body.provider === 'string' ? body.provider : 'auto';
1066
+ const model = typeof body.model === 'string' ? body.model : undefined;
1067
+
1068
+ res.setHeader('Content-Type', 'text/event-stream');
1069
+ res.setHeader('Cache-Control', 'no-cache');
1070
+ res.setHeader('Connection', 'keep-alive');
1071
+ res.flushHeaders?.();
1072
+
1073
+ const lastUser = [...messages].reverse().find((message) => message?.role === 'user');
1074
+ if (!lastUser) {
1075
+ sendSSEError(res, 'missing_message', 'No user message provided.');
1076
+ return;
1077
+ }
1078
+
1079
+ let capabilitiesValue;
1080
+ try {
1081
+ capabilitiesValue = await cache.get('capabilities');
1082
+ } catch (err) {
1083
+ sendSSEError(res, 'capabilities_failed', err.message);
1084
+ return;
1085
+ }
1086
+
1087
+ const selectedProvider = resolveProvider(provider, capabilitiesValue);
1088
+ if (selectedProvider === 'none') {
1089
+ sendSSEError(
1090
+ res,
1091
+ 'no_provider_available',
1092
+ 'No local provider or cloud API is available.'
1093
+ );
1094
+ return;
1095
+ }
1096
+
1097
+ sendSSE(res, { provider: selectedProvider });
1098
+
1099
+ if (selectedProvider === 'cloud') {
1100
+ await streamViaCloud({
1101
+ res,
1102
+ messages,
1103
+ courseSlug,
1104
+ root,
1105
+ env,
1106
+ fetchImpl,
1107
+ log,
1108
+ });
1109
+ return;
1110
+ }
1111
+
1112
+ const runner = agentRunners[selectedProvider];
1113
+ if (typeof runner !== 'function') {
1114
+ sendSSEError(res, 'no_provider_available', `No runner for provider ${selectedProvider}.`);
1115
+ return;
1116
+ }
1117
+
1118
+ const system = PROFESSOR_SYSTEM_PROMPT;
1119
+ const includeSystem = selectedProvider !== 'claude';
1120
+ const prompt = flattenLegacyMessages(system, messages, includeSystem);
1121
+
1122
+ let fullText = '';
1123
+ let ended = false;
1124
+ let handle = null;
1125
+
1126
+ const finish = () => {
1127
+ if (ended) return;
1128
+ ended = true;
1129
+ completeFromText(res, fullText, courseSlug, { coursesDir: root, log });
1130
+ };
1131
+
1132
+ try {
1133
+ handle = runner({
1134
+ system,
1135
+ prompt,
1136
+ model,
1137
+ messages,
1138
+ onText(text) {
1139
+ if (typeof text !== 'string' || !text || ended) return;
1140
+ fullText += text;
1141
+ sendSSE(res, { content: text });
1142
+ },
1143
+ onError(error) {
1144
+ if (ended) return;
1145
+ ended = true;
1146
+ sendSSEError(res, error?.code || 'agent_failed', error?.message || 'Agent failed.');
1147
+ },
1148
+ onDone: finish,
1149
+ log,
1150
+ });
1151
+ } catch (err) {
1152
+ ended = true;
1153
+ sendSSEError(res, 'agent_failed', err.message);
1154
+ return;
1155
+ }
1156
+
1157
+ res.on('close', () => {
1158
+ if (!res.writableEnded) {
1159
+ ended = true;
1160
+ handle?.kill?.();
1161
+ }
1162
+ });
1163
+ });
1164
+
1165
+ api.post('/notify', (req, res) => {
1166
+ res.json({ success: true, message: 'Notification sent' });
1167
+ });
1168
+
1169
+ router.use('/api', api);
1170
+
1171
+ return router;
1172
+ }
1173
+
1174
+ /* ------------------------------------------------------------------ cloud fallback */
1175
+
1176
+ async function streamViaCloud({ res, messages, courseSlug, root, env, fetchImpl, log }) {
1177
+ const apiKey =
1178
+ env.ANTHROPIC_API_KEY || env.CLAUDE_API_KEY || env.OPENAI_API_KEY;
1179
+
1180
+ if (!apiKey) {
1181
+ sendSSEError(res, 'no_api_key', 'No API key configured. Run: export ANTHROPIC_API_KEY=your-key');
1182
+ return;
1183
+ }
1184
+
1185
+ const apiMessages = messages
1186
+ .filter((message) => message?.content && String(message.content).trim())
1187
+ .map((message) => ({
1188
+ role: message.role === 'user' ? 'user' : 'assistant',
1189
+ content: message.content,
1190
+ }));
1191
+
1192
+ const isOpenAI =
1193
+ Boolean(env.OPENAI_API_KEY) && !env.ANTHROPIC_API_KEY && !env.CLAUDE_API_KEY;
1194
+
1195
+ const apiUrl = isOpenAI
1196
+ ? 'https://api.openai.com/v1/chat/completions'
1197
+ : 'https://api.anthropic.com/v1/messages';
1198
+ const headers = isOpenAI
1199
+ ? { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` }
1200
+ : {
1201
+ 'Content-Type': 'application/json',
1202
+ 'x-api-key': apiKey,
1203
+ 'anthropic-version': '2023-06-01',
1204
+ };
1205
+ const requestBody = isOpenAI
1206
+ ? {
1207
+ model: 'gpt-4o',
1208
+ messages: [{ role: 'system', content: PROFESSOR_SYSTEM_PROMPT }, ...apiMessages],
1209
+ stream: true,
1210
+ }
1211
+ : {
1212
+ model: 'claude-sonnet-4-6',
1213
+ max_tokens: 4096,
1214
+ system: PROFESSOR_SYSTEM_PROMPT,
1215
+ messages: apiMessages,
1216
+ stream: true,
1217
+ };
1218
+
1219
+ let fullText = '';
1220
+ let ended = false;
1221
+ const finalize = () => {
1222
+ if (ended) return;
1223
+ ended = true;
1224
+ completeFromText(res, fullText, courseSlug, { coursesDir: root, log });
1225
+ };
1226
+
1227
+ try {
1228
+ const response = await fetchImpl(apiUrl, {
1229
+ method: 'POST',
1230
+ headers,
1231
+ body: JSON.stringify(requestBody),
1232
+ });
1233
+ if (!response.ok) {
1234
+ const text = await response.text().catch(() => '');
1235
+ sendSSEError(res, 'api_error', `API error ${response.status}: ${text.slice(0, 200)}`);
1236
+ return;
1237
+ }
1238
+
1239
+ const reader = response.body.getReader();
1240
+ const decoder = new TextDecoder();
1241
+ let buffer = '';
1242
+
1243
+ while (true) {
1244
+ const { done, value } = await reader.read();
1245
+ if (done) break;
1246
+ buffer += decoder.decode(value, { stream: true });
1247
+ const lines = buffer.split('\n');
1248
+ buffer = lines.pop() || '';
1249
+ for (const line of lines) {
1250
+ if (!line.startsWith('data: ')) continue;
1251
+ const data = line.slice(6);
1252
+ if (data === '[DONE]') {
1253
+ finalize();
1254
+ return;
1255
+ }
1256
+ try {
1257
+ const parsed = JSON.parse(data);
1258
+ const text = isOpenAI
1259
+ ? parsed.choices?.[0]?.delta?.content
1260
+ : parsed.type === 'content_block_delta'
1261
+ ? parsed.delta?.text
1262
+ : null;
1263
+ if (text) {
1264
+ fullText += text;
1265
+ sendSSE(res, { content: text });
1266
+ }
1267
+ } catch {
1268
+ /* skip malformed stream line */
1269
+ }
1270
+ }
1271
+ }
1272
+
1273
+ finalize();
1274
+ } catch (err) {
1275
+ sendSSEError(res, 'api_error', err.message);
1276
+ }
1277
+ }