@m6d/cortex-server 1.8.0 → 2.0.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 (352) hide show
  1. package/README.md +8 -3
  2. package/contracts/README.md +23 -0
  3. package/contracts/graph/embed.ts +50 -0
  4. package/{src/lib → contracts}/graph/helpers.ts +4 -10
  5. package/{src/lib → contracts}/graph/neo4j.ts +14 -27
  6. package/contracts/graph/schema.ts +65 -0
  7. package/{src/lib → contracts}/graph/types.ts +2 -29
  8. package/contracts/graph.ts +36 -0
  9. package/contracts/runtime.ts +208 -0
  10. package/contracts/wire.ts +143 -0
  11. package/dist/contracts/graph/embed.d.ts +22 -0
  12. package/dist/{src/lib → contracts}/graph/helpers.d.ts +16 -14
  13. package/dist/{src/lib → contracts}/graph/neo4j.d.ts +5 -5
  14. package/dist/contracts/graph/schema.d.ts +62 -0
  15. package/dist/{src/lib → contracts}/graph/types.d.ts +1 -1
  16. package/dist/contracts/graph.d.ts +14 -0
  17. package/dist/contracts/runtime.d.ts +278 -0
  18. package/dist/contracts/wire.d.ts +120 -0
  19. package/dist/src/lib/adapters/database/index.d.ts +61 -0
  20. package/dist/src/lib/adapters/database/message-content.d.ts +30 -0
  21. package/dist/src/lib/adapters/database/mssql/attachments.d.ts +100 -0
  22. package/dist/src/lib/adapters/database/mssql/client.d.ts +8 -0
  23. package/dist/src/lib/adapters/database/mssql/index.d.ts +194 -0
  24. package/dist/src/lib/adapters/database/mssql/llm-requests.d.ts +17 -0
  25. package/dist/src/lib/adapters/database/mssql/messages.d.ts +37 -0
  26. package/dist/src/lib/adapters/database/mssql/threads.d.ts +50 -0
  27. package/dist/src/lib/adapters/database/postgres/attachments.d.ts +113 -0
  28. package/dist/src/lib/adapters/database/postgres/client.d.ts +8 -0
  29. package/dist/src/lib/adapters/database/postgres/index.d.ts +207 -0
  30. package/dist/src/lib/adapters/database/postgres/llm-requests.d.ts +17 -0
  31. package/dist/src/lib/adapters/database/postgres/messages.d.ts +37 -0
  32. package/dist/src/lib/adapters/database/postgres/threads.d.ts +50 -0
  33. package/{src/lib/adapters/storage.ts → dist/src/lib/adapters/storage/index.d.ts} +1 -1
  34. package/dist/src/lib/adapters/{minio.d.ts → storage/minio.d.ts} +1 -1
  35. package/dist/src/lib/ai/active-runs.d.ts +63 -0
  36. package/dist/src/lib/ai/attachments.d.ts +30 -0
  37. package/dist/src/lib/ai/backend-url.d.ts +16 -0
  38. package/dist/src/lib/ai/cc-runtime.d.ts +61 -0
  39. package/dist/src/lib/ai/commit-gate.d.ts +21 -0
  40. package/dist/src/lib/ai/context/builder.d.ts +6 -7
  41. package/dist/src/lib/ai/context/compression-middleware.d.ts +15 -0
  42. package/dist/src/lib/ai/context/compressor.d.ts +2 -13
  43. package/dist/src/lib/ai/context/intra-turn-compressor.d.ts +9 -9
  44. package/dist/src/lib/ai/context/optimize-thread-context.d.ts +9 -0
  45. package/dist/src/lib/ai/context/summarizer.d.ts +3 -3
  46. package/dist/src/lib/ai/context/token-estimator.d.ts +5 -8
  47. package/dist/src/lib/ai/fetch.d.ts +1 -1
  48. package/dist/src/lib/ai/finish-turn.d.ts +23 -0
  49. package/dist/src/lib/ai/helpers.d.ts +37 -4
  50. package/dist/src/lib/ai/index.d.ts +6 -3
  51. package/dist/src/lib/ai/inspector.d.ts +41 -0
  52. package/dist/src/lib/ai/interceptors/request-interceptor.d.ts +6 -5
  53. package/dist/src/lib/ai/prompt.d.ts +5 -4
  54. package/dist/src/lib/ai/redis-runs.d.ts +41 -0
  55. package/dist/src/lib/ai/redis-stream-log.d.ts +39 -0
  56. package/dist/src/lib/ai/tools/execute-code.tool.d.ts +18 -4
  57. package/dist/src/lib/ai/tools/query-graph.tool.d.ts +13 -5
  58. package/dist/src/lib/ai/tools/read-attachment.tool.d.ts +21 -0
  59. package/dist/src/lib/ai/tools/search-common.d.ts +17 -0
  60. package/dist/src/lib/ai/tools/search-knowledge.tool.d.ts +15 -0
  61. package/dist/src/lib/ai/tools/search-services.tool.d.ts +12 -0
  62. package/dist/src/lib/ai/tools/search-tools.tool.d.ts +12 -0
  63. package/dist/src/lib/ai/turn-tools.d.ts +39 -0
  64. package/dist/src/lib/ai/vision/rasterize-pdf.d.ts +26 -0
  65. package/dist/src/lib/ai/vision/rasterize-pdf.worker.d.ts +1 -0
  66. package/dist/src/lib/ai/vision/vision-reader.d.ts +45 -0
  67. package/dist/src/lib/cc/client.d.ts +183 -0
  68. package/dist/src/lib/cc/config-cache.d.ts +20 -0
  69. package/dist/src/lib/cc/format.d.ts +23 -0
  70. package/dist/src/lib/cc/registry.d.ts +34 -0
  71. package/dist/src/lib/cc/types.d.ts +27 -0
  72. package/dist/src/lib/config.d.ts +81 -64
  73. package/dist/src/lib/db/drizzle.config.mssql.d.ts +2 -0
  74. package/dist/src/lib/db/drizzle.config.pg.d.ts +2 -0
  75. package/dist/src/lib/db/migrate.d.ts +7 -1
  76. package/dist/src/lib/db/{schema.d.ts → schema.mssql.d.ts} +138 -29
  77. package/dist/src/lib/db/schema.pg.d.ts +546 -0
  78. package/dist/src/lib/factory.d.ts +2 -12
  79. package/dist/src/lib/graph/index.d.ts +10 -11
  80. package/dist/src/lib/graph/resolver.d.ts +2 -3
  81. package/dist/src/lib/index.d.ts +3 -3
  82. package/dist/src/lib/redis.d.ts +19 -0
  83. package/dist/src/lib/routes/chat.d.ts +1 -1
  84. package/dist/src/lib/routes/files.d.ts +1 -1
  85. package/dist/src/lib/routes/owned-thread.d.ts +17 -0
  86. package/dist/src/lib/routes/threads.d.ts +1 -1
  87. package/dist/src/lib/routes/ws.d.ts +1 -1
  88. package/dist/src/lib/types.d.ts +20 -37
  89. package/dist/src/lib/ws/connections.d.ts +2 -1
  90. package/package.json +33 -18
  91. package/src/lib/adapters/database/index.ts +78 -0
  92. package/src/lib/adapters/database/message-content.ts +39 -0
  93. package/src/lib/adapters/database/mssql/attachments.ts +90 -0
  94. package/src/lib/adapters/database/mssql/client.ts +11 -0
  95. package/src/lib/adapters/database/mssql/index.ts +23 -0
  96. package/src/lib/adapters/database/mssql/llm-requests.ts +43 -0
  97. package/src/lib/adapters/database/mssql/messages.ts +92 -0
  98. package/src/lib/adapters/database/mssql/threads.ts +83 -0
  99. package/src/lib/adapters/database/postgres/attachments.ts +88 -0
  100. package/src/lib/adapters/database/postgres/client.ts +11 -0
  101. package/src/lib/adapters/database/postgres/index.ts +23 -0
  102. package/src/lib/adapters/database/postgres/llm-requests.ts +45 -0
  103. package/src/lib/adapters/database/postgres/messages.ts +92 -0
  104. package/src/lib/adapters/database/postgres/threads.ts +84 -0
  105. package/{dist/src/lib/adapters/storage.d.ts → src/lib/adapters/storage/index.ts} +1 -1
  106. package/src/lib/adapters/{minio.ts → storage/minio.ts} +5 -5
  107. package/src/lib/ai/active-runs.ts +157 -0
  108. package/src/lib/ai/attachments.ts +144 -0
  109. package/src/lib/ai/backend-url.ts +27 -0
  110. package/src/lib/ai/cc-runtime.ts +63 -0
  111. package/src/lib/ai/commit-gate.ts +116 -0
  112. package/src/lib/ai/context/builder.ts +12 -14
  113. package/src/lib/ai/context/compression-middleware.ts +44 -0
  114. package/src/lib/ai/context/compressor.ts +67 -59
  115. package/src/lib/ai/context/intra-turn-compressor.ts +121 -204
  116. package/src/lib/ai/context/optimize-thread-context.ts +50 -0
  117. package/src/lib/ai/context/summarizer.ts +28 -30
  118. package/src/lib/ai/context/token-estimator.ts +35 -30
  119. package/src/lib/ai/fetch.ts +10 -5
  120. package/src/lib/ai/finish-turn.ts +75 -0
  121. package/src/lib/ai/helpers.ts +83 -15
  122. package/src/lib/ai/index.ts +359 -329
  123. package/src/lib/ai/inspector.ts +112 -0
  124. package/src/lib/ai/interceptors/request-interceptor.ts +70 -42
  125. package/src/lib/ai/prompt.ts +126 -125
  126. package/src/lib/ai/redis-runs.ts +167 -0
  127. package/src/lib/ai/redis-stream-log.ts +219 -0
  128. package/src/lib/ai/tools/execute-code.tool.ts +178 -67
  129. package/src/lib/ai/tools/query-graph.tool.ts +7 -8
  130. package/src/lib/ai/tools/read-attachment.tool.ts +59 -0
  131. package/src/lib/ai/tools/search-common.ts +15 -0
  132. package/src/lib/ai/tools/search-knowledge.tool.ts +33 -0
  133. package/src/lib/ai/tools/search-services.tool.ts +31 -0
  134. package/src/lib/ai/tools/search-tools.tool.ts +29 -0
  135. package/src/lib/ai/turn-tools.ts +154 -0
  136. package/src/lib/ai/vision/rasterize-pdf.ts +69 -0
  137. package/src/lib/ai/vision/rasterize-pdf.worker.ts +81 -0
  138. package/src/lib/ai/vision/vision-reader.ts +130 -0
  139. package/src/lib/auth/middleware.ts +5 -3
  140. package/src/lib/cc/client.ts +273 -0
  141. package/src/lib/cc/config-cache.ts +32 -0
  142. package/src/lib/cc/format.ts +96 -0
  143. package/src/lib/cc/registry.ts +62 -0
  144. package/src/lib/cc/types.ts +44 -0
  145. package/src/lib/config.ts +102 -71
  146. package/src/lib/db/drizzle.config.mssql.ts +9 -0
  147. package/src/lib/db/drizzle.config.pg.ts +9 -0
  148. package/src/lib/db/migrate.ts +45 -10
  149. package/src/lib/db/migrations/mssql/20260729092726_talented_wilson_fisk/migration.sql +20 -0
  150. package/src/lib/db/migrations/mssql/20260729092726_talented_wilson_fisk/snapshot.json +497 -0
  151. package/src/lib/db/migrations/mssql/20260801003652_perpetual_blue_shield/migration.sql +1 -0
  152. package/src/lib/db/migrations/mssql/20260801003652_perpetual_blue_shield/snapshot.json +516 -0
  153. package/src/lib/db/migrations/mssql/20260812174642_user_id_text/migration.sql +2 -0
  154. package/src/lib/db/migrations/mssql/20260812174642_user_id_text/snapshot.json +516 -0
  155. package/src/lib/db/migrations/pg/20260801084117_thick_ben_grimm/migration.sql +53 -0
  156. package/src/lib/db/migrations/pg/20260801084117_thick_ben_grimm/snapshot.json +584 -0
  157. package/src/lib/db/migrations/pg/20260812174622_user_id_text/migration.sql +2 -0
  158. package/src/lib/db/migrations/pg/20260812174622_user_id_text/snapshot.json +584 -0
  159. package/src/lib/db/{schema.ts → schema.mssql.ts} +29 -18
  160. package/src/lib/db/schema.pg.ts +95 -0
  161. package/src/lib/factory.ts +44 -89
  162. package/src/lib/graph/index.ts +12 -40
  163. package/src/lib/graph/resolver.ts +146 -116
  164. package/src/lib/index.ts +11 -4
  165. package/src/lib/redis.ts +44 -0
  166. package/src/lib/routes/chat.ts +91 -62
  167. package/src/lib/routes/files.ts +105 -83
  168. package/src/lib/routes/owned-thread.ts +17 -0
  169. package/src/lib/routes/threads.ts +14 -30
  170. package/src/lib/routes/ws.ts +9 -3
  171. package/src/lib/types.ts +37 -36
  172. package/src/lib/ws/connections.ts +9 -1
  173. package/tsconfig.json +48 -0
  174. package/dist/src/lib/adapters/database.d.ts +0 -45
  175. package/dist/src/lib/adapters/mssql.d.ts +0 -3
  176. package/dist/src/lib/ai/active-streams.d.ts +0 -14
  177. package/dist/src/lib/ai/context/index.d.ts +0 -16
  178. package/dist/src/lib/ai/tools/capture-files.tool.d.ts +0 -6
  179. package/dist/src/lib/cli/extract-endpoints.d.ts +0 -6
  180. package/dist/src/lib/graph/expand-domains.d.ts +0 -2
  181. package/dist/src/lib/graph/generate-cypher.d.ts +0 -22
  182. package/dist/src/lib/graph/seed.d.ts +0 -19
  183. package/dist/src/lib/graph/validate.d.ts +0 -2
  184. package/dist/src/lib/routes/index.d.ts +0 -4
  185. package/dist/src/lib/ws/events.d.ts +0 -39
  186. package/dist/src/lib/ws/index.d.ts +0 -3
  187. package/dist/src/lib/ws/notify.d.ts +0 -2
  188. package/src/lib/adapters/database.ts +0 -48
  189. package/src/lib/adapters/mssql.ts +0 -231
  190. package/src/lib/ai/active-streams.ts +0 -123
  191. package/src/lib/ai/context/index.ts +0 -80
  192. package/src/lib/ai/tools/capture-files.tool.ts +0 -20
  193. package/src/lib/cli/extract-endpoints.ts +0 -550
  194. package/src/lib/graph/expand-domains.ts +0 -276
  195. package/src/lib/graph/generate-cypher.ts +0 -192
  196. package/src/lib/graph/seed.ts +0 -162
  197. package/src/lib/graph/validate.ts +0 -78
  198. package/src/lib/routes/index.ts +0 -4
  199. package/src/lib/ws/events.ts +0 -39
  200. package/src/lib/ws/index.ts +0 -11
  201. package/src/lib/ws/notify.ts +0 -9
  202. package/src/sample/db/client.ts +0 -9
  203. package/src/sample/db/migrations/20260411023125_rich_purple_man/migration.sql +0 -5
  204. package/src/sample/db/migrations/20260411023125_rich_purple_man/snapshot.json +0 -50
  205. package/src/sample/db/schema.ts +0 -10
  206. package/src/sample/domains/account/concepts/session.concept.ts +0 -17
  207. package/src/sample/domains/account/endpoints/listCurrentSessions.endpoint.ts +0 -31
  208. package/src/sample/domains/account/endpoints/revokeAllOtherSessions.endpoint.ts +0 -22
  209. package/src/sample/domains/account/endpoints/revokeCurrentSession.endpoint.ts +0 -33
  210. package/src/sample/domains/account/index.ts +0 -18
  211. package/src/sample/domains/appraisals/concepts/appraisalCycle.concept.ts +0 -15
  212. package/src/sample/domains/appraisals/concepts/appraisalRecord.concept.ts +0 -20
  213. package/src/sample/domains/appraisals/concepts/appraisalRecordCompetency.concept.ts +0 -10
  214. package/src/sample/domains/appraisals/concepts/appraisalRecordFunctionalRequirement.concept.ts +0 -10
  215. package/src/sample/domains/appraisals/concepts/appraisalRecordGoal.concept.ts +0 -17
  216. package/src/sample/domains/appraisals/endpoints/getAppraisalRecordById.endpoint.ts +0 -321
  217. package/src/sample/domains/appraisals/endpoints/getAppraisalRecordCompetencies.endpoint.ts +0 -120
  218. package/src/sample/domains/appraisals/endpoints/getAppraisalRecordFunctionalRequirements.endpoint.ts +0 -126
  219. package/src/sample/domains/appraisals/endpoints/getAppraisalRecordGoals.endpoint.ts +0 -104
  220. package/src/sample/domains/appraisals/endpoints/getAppraisalRecordScore.endpoint.ts +0 -58
  221. package/src/sample/domains/appraisals/endpoints/listAppraisalCyclesSimple.endpoint.ts +0 -52
  222. package/src/sample/domains/appraisals/endpoints/listAppraisalRecords.endpoint.ts +0 -245
  223. package/src/sample/domains/appraisals/endpoints/listAppraisalTemplatesSimple.endpoint.ts +0 -52
  224. package/src/sample/domains/appraisals/index.ts +0 -40
  225. package/src/sample/domains/appraisals/rules/appraisalRecordScoping.rule.ts +0 -7
  226. package/src/sample/domains/attendance/concepts/attendancePermission.concept.ts +0 -17
  227. package/src/sample/domains/attendance/concepts/attendanceTransaction.concept.ts +0 -17
  228. package/src/sample/domains/attendance/concepts/publicHoliday.concept.ts +0 -10
  229. package/src/sample/domains/attendance/concepts/punch.concept.ts +0 -19
  230. package/src/sample/domains/attendance/endpoints/getAttendanceTransactionById.endpoint.ts +0 -444
  231. package/src/sample/domains/attendance/endpoints/getCurrentAttendanceProfile.endpoint.ts +0 -886
  232. package/src/sample/domains/attendance/endpoints/getCurrentAttendanceStatistics.endpoint.ts +0 -49
  233. package/src/sample/domains/attendance/endpoints/listAttendancePermissions.endpoint.ts +0 -176
  234. package/src/sample/domains/attendance/endpoints/listAttendanceTransactionStates.endpoint.ts +0 -26
  235. package/src/sample/domains/attendance/endpoints/listAttendanceTransactions.endpoint.ts +0 -373
  236. package/src/sample/domains/attendance/endpoints/listPublicHolidaysSimple.endpoint.ts +0 -52
  237. package/src/sample/domains/attendance/endpoints/listPunchTypes.endpoint.ts +0 -25
  238. package/src/sample/domains/attendance/endpoints/listPunches.endpoint.ts +0 -178
  239. package/src/sample/domains/attendance/index.ts +0 -41
  240. package/src/sample/domains/attendance/services/attendancePermissions.service.ts +0 -15
  241. package/src/sample/domains/employees/concepts/employee.concept.ts +0 -20
  242. package/src/sample/domains/employees/concepts/employeeBankAccount.concept.ts +0 -19
  243. package/src/sample/domains/employees/concepts/employeeChild.concept.ts +0 -19
  244. package/src/sample/domains/employees/concepts/employeeDocument.concept.ts +0 -21
  245. package/src/sample/domains/employees/concepts/employeeEvent.concept.ts +0 -21
  246. package/src/sample/domains/employees/concepts/employeeExperience.concept.ts +0 -18
  247. package/src/sample/domains/employees/concepts/employeeJobLevelChange.concept.ts +0 -21
  248. package/src/sample/domains/employees/concepts/employeeMedal.concept.ts +0 -20
  249. package/src/sample/domains/employees/concepts/employeeQualification.concept.ts +0 -20
  250. package/src/sample/domains/employees/concepts/employeeSpouse.concept.ts +0 -21
  251. package/src/sample/domains/employees/concepts/employeeViolation.concept.ts +0 -19
  252. package/src/sample/domains/employees/endpoints/getCurrentEmployee.endpoint.ts +0 -1651
  253. package/src/sample/domains/employees/endpoints/getCurrentIdentity.endpoint.ts +0 -197
  254. package/src/sample/domains/employees/endpoints/getCurrentManagers.endpoint.ts +0 -142
  255. package/src/sample/domains/employees/endpoints/getEmployeeById.endpoint.ts +0 -1659
  256. package/src/sample/domains/employees/endpoints/getEmployeeStatistics.endpoint.ts +0 -43
  257. package/src/sample/domains/employees/endpoints/listBankAccounts.endpoint.ts +0 -223
  258. package/src/sample/domains/employees/endpoints/listChildren.endpoint.ts +0 -211
  259. package/src/sample/domains/employees/endpoints/listDocuments.endpoint.ts +0 -222
  260. package/src/sample/domains/employees/endpoints/listEmployeesSimple.endpoint.ts +0 -156
  261. package/src/sample/domains/employees/endpoints/listEvents.endpoint.ts +0 -120
  262. package/src/sample/domains/employees/endpoints/listExperiences.endpoint.ts +0 -188
  263. package/src/sample/domains/employees/endpoints/listJobLevelChanges.endpoint.ts +0 -240
  264. package/src/sample/domains/employees/endpoints/listMedals.endpoint.ts +0 -266
  265. package/src/sample/domains/employees/endpoints/listQualifications.endpoint.ts +0 -265
  266. package/src/sample/domains/employees/endpoints/listSpouses.endpoint.ts +0 -278
  267. package/src/sample/domains/employees/endpoints/listViolations.endpoint.ts +0 -245
  268. package/src/sample/domains/employees/index.ts +0 -75
  269. package/src/sample/domains/employees/services/employees.service.ts +0 -181
  270. package/src/sample/domains/index.ts +0 -10
  271. package/src/sample/domains/leaves/concepts/leave.concept.ts +0 -21
  272. package/src/sample/domains/leaves/concepts/leaveBalance.concept.ts +0 -17
  273. package/src/sample/domains/leaves/concepts/leaveBalanceTransaction.concept.ts +0 -16
  274. package/src/sample/domains/leaves/concepts/leaveType.concept.ts +0 -13
  275. package/src/sample/domains/leaves/concepts/leaveTypes.concept.ts +0 -205
  276. package/src/sample/domains/leaves/endpoints/getBalance.endpoint.ts +0 -53
  277. package/src/sample/domains/leaves/endpoints/getLeaveById.endpoint.ts +0 -53
  278. package/src/sample/domains/leaves/endpoints/listBalanceTransactions.endpoint.ts +0 -196
  279. package/src/sample/domains/leaves/endpoints/listBalanceTypes.endpoint.ts +0 -26
  280. package/src/sample/domains/leaves/endpoints/listBalances.endpoint.ts +0 -201
  281. package/src/sample/domains/leaves/endpoints/listLeaveTypes.endpoint.ts +0 -28
  282. package/src/sample/domains/leaves/endpoints/listLeaves.endpoint.ts +0 -234
  283. package/src/sample/domains/leaves/index.ts +0 -38
  284. package/src/sample/domains/leaves/services/leaveRequests.service.ts +0 -232
  285. package/src/sample/domains/notifications/concepts/notification.concept.ts +0 -19
  286. package/src/sample/domains/notifications/endpoints/countMyNotifications.endpoint.ts +0 -21
  287. package/src/sample/domains/notifications/endpoints/getMyNotification.endpoint.ts +0 -57
  288. package/src/sample/domains/notifications/endpoints/listMyNotifications.endpoint.ts +0 -59
  289. package/src/sample/domains/notifications/endpoints/markMyNotificationAsRead.endpoint.ts +0 -32
  290. package/src/sample/domains/notifications/index.ts +0 -20
  291. package/src/sample/domains/payroll/concepts/payslip.concept.ts +0 -18
  292. package/src/sample/domains/payroll/concepts/salaryCertificate.concept.ts +0 -17
  293. package/src/sample/domains/payroll/concepts/salaryCertificateRequestingEntity.concept.ts +0 -8
  294. package/src/sample/domains/payroll/endpoints/getPayslipById.endpoint.ts +0 -238
  295. package/src/sample/domains/payroll/endpoints/listPayslips.endpoint.ts +0 -216
  296. package/src/sample/domains/payroll/endpoints/listSalaryCertificateLanguages.endpoint.ts +0 -25
  297. package/src/sample/domains/payroll/endpoints/listSalaryCertificateRequestingEntities.endpoint.ts +0 -62
  298. package/src/sample/domains/payroll/endpoints/listSalaryCertificateTypes.endpoint.ts +0 -24
  299. package/src/sample/domains/payroll/endpoints/listSalaryCertificates.endpoint.ts +0 -122
  300. package/src/sample/domains/payroll/endpoints/previewSalaryCertificate.endpoint.ts +0 -45
  301. package/src/sample/domains/payroll/index.ts +0 -32
  302. package/src/sample/domains/payroll/rules/payrollEmployeeContext.rule.ts +0 -7
  303. package/src/sample/domains/payroll/services/salaryCertificates.service.ts +0 -15
  304. package/src/sample/domains/servicing/concepts/service.concept.ts +0 -6
  305. package/src/sample/domains/servicing/concepts/serviceRequest.concept.ts +0 -12
  306. package/src/sample/domains/servicing/concepts/serviceRequestApproval.concept.ts +0 -9
  307. package/src/sample/domains/servicing/endpoints/cancelServiceRequest.endpoint.ts +0 -21
  308. package/src/sample/domains/servicing/endpoints/createServiceRequest.endpoint.ts +0 -511
  309. package/src/sample/domains/servicing/endpoints/getServiceRequest.endpoint.ts +0 -352
  310. package/src/sample/domains/servicing/endpoints/getServiceRequestFormItems.endpoint.ts +0 -219
  311. package/src/sample/domains/servicing/endpoints/getServiceRequestTransactionFormItems.endpoint.ts +0 -216
  312. package/src/sample/domains/servicing/endpoints/getServiceStates.endpoint.ts +0 -47
  313. package/src/sample/domains/servicing/endpoints/invokeServiceRequestAction.endpoint.ts +0 -139
  314. package/src/sample/domains/servicing/endpoints/listServiceRequests.endpoint.ts +0 -292
  315. package/src/sample/domains/servicing/endpoints/listServices.endpoint.ts +0 -108
  316. package/src/sample/domains/servicing/endpoints/updateServiceRequest.endpoint.ts +0 -355
  317. package/src/sample/domains/servicing/index.ts +0 -44
  318. package/src/sample/domains/servicing/rules/checkValidActions.rule.ts +0 -7
  319. package/src/sample/domains/servicing/rules/createServiceRequest.rule.ts +0 -7
  320. package/src/sample/domains/servicing/rules/filterServiceRequestsByState.rule.ts +0 -7
  321. package/src/sample/domains/servicing/rules/passingOptionFields.rule.ts +0 -7
  322. package/src/sample/domains/shared/rules/pagination.rule.ts +0 -7
  323. package/src/sample/domains/suggestions/concepts/suggestion.concept.ts +0 -19
  324. package/src/sample/domains/suggestions/concepts/suggestionCategory.concept.ts +0 -7
  325. package/src/sample/domains/suggestions/concepts/suggestionImpactLevel.concept.ts +0 -7
  326. package/src/sample/domains/suggestions/endpoints/createSuggestion.endpoint.ts +0 -705
  327. package/src/sample/domains/suggestions/endpoints/deleteSuggestion.endpoint.ts +0 -32
  328. package/src/sample/domains/suggestions/endpoints/getSuggestionById.endpoint.ts +0 -635
  329. package/src/sample/domains/suggestions/endpoints/listSuggestionCategories.endpoint.ts +0 -62
  330. package/src/sample/domains/suggestions/endpoints/listSuggestionImpactLevels.endpoint.ts +0 -62
  331. package/src/sample/domains/suggestions/endpoints/listSuggestionStates.endpoint.ts +0 -24
  332. package/src/sample/domains/suggestions/endpoints/listSuggestions.endpoint.ts +0 -132
  333. package/src/sample/domains/suggestions/endpoints/updateSuggestion.endpoint.ts +0 -690
  334. package/src/sample/domains/suggestions/endpoints/updateSuggestionState.endpoint.ts +0 -39
  335. package/src/sample/domains/suggestions/index.ts +0 -34
  336. package/src/sample/domains/suggestions/rules/suggestionScope.rule.ts +0 -7
  337. package/src/sample/domains/surveys/concepts/survey.concept.ts +0 -10
  338. package/src/sample/domains/surveys/concepts/surveyResponse.concept.ts +0 -14
  339. package/src/sample/domains/surveys/endpoints/getSurveyResponseById.endpoint.ts +0 -131
  340. package/src/sample/domains/surveys/endpoints/getTargetedSurvey.endpoint.ts +0 -129
  341. package/src/sample/domains/surveys/endpoints/listTargetedSurveys.endpoint.ts +0 -160
  342. package/src/sample/domains/surveys/endpoints/respondToSurvey.endpoint.ts +0 -144
  343. package/src/sample/domains/surveys/index.ts +0 -21
  344. package/src/sample/drizzle.config.ts +0 -11
  345. package/src/sample/index.bak.ts +0 -341
  346. package/src/sample/index.ts +0 -318
  347. package/src/sample/official-statements/defaults.ts +0 -57
  348. package/src/sample/official-statements/routes.ts +0 -137
  349. package/src/sample/official-statements/service.ts +0 -148
  350. package/src/sample/official-statements/types.ts +0 -23
  351. /package/src/lib/db/migrations/{20260326231647_nice_speedball → mssql/20260326231647_nice_speedball}/migration.sql +0 -0
  352. /package/src/lib/db/migrations/{20260326231647_nice_speedball → mssql/20260326231647_nice_speedball}/snapshot.json +0 -0
@@ -1,107 +1,129 @@
1
+ import {
2
+ ATTACHMENT_MAX_BYTES,
3
+ MAX_ATTACHMENTS_PER_MESSAGE,
4
+ checkAttachmentPolicy,
5
+ } from "@cortex/contracts/wire";
1
6
  import { Hono } from "hono";
2
- import { zValidator } from "@hono/zod-validator";
3
- import z from "zod";
7
+ import { bodyLimit } from "hono/body-limit";
4
8
  import { HTTPException } from "hono/http-exception";
5
- import { safeValidateUIMessages, type ToolUIPart, type UIMessage } from "ai";
6
- import type { CortexAppEnv } from "../types.ts";
7
- import { requireAuth } from "../auth/middleware.ts";
9
+ import { toAttachmentSummary, type CortexAppEnv } from "@/types";
10
+ import { requireAuth } from "@/auth/middleware";
11
+ import type { ResolvedCortexAgentConfig } from "@/config";
12
+ import { requireOwnedThread } from "./owned-thread";
8
13
 
9
14
  export function createFileRoutes() {
10
15
  const app = new Hono<CortexAppEnv>();
11
16
 
17
+ app.post(
18
+ "/threads/:threadId/files",
19
+ requireAuth,
20
+ bodyLimit({ maxSize: ATTACHMENT_MAX_BYTES + 64 * 1024 }),
21
+ async function (c) {
22
+ const config = c.get("agentConfig");
23
+ const storage = requireStorage(config);
24
+
25
+ const threadId = c.req.param("threadId");
26
+ const userId = c.get("user").id;
27
+ await requireOwnedThread(c, threadId);
28
+
29
+ const file = (await c.req.parseBody())["file"];
30
+ if (!(file instanceof File)) {
31
+ throw new HTTPException(400, { message: "File is required" });
32
+ }
33
+
34
+ const policy = checkAttachmentPolicy(file.type, file.size);
35
+ if (policy !== "ok") {
36
+ throw new HTTPException(422, { message: `Attachment rejected: ${policy}` });
37
+ }
38
+
39
+ const storageKey = `attachments/${crypto.randomUUID()}`;
40
+ const bytes = Buffer.from(await file.arrayBuffer()).toString("base64");
41
+ if (!(await storage.put(storageKey, bytes))) {
42
+ throw new HTTPException(500, { message: "File upload failed" });
43
+ }
44
+
45
+ const attachment = await config.db.attachments
46
+ .createPending(
47
+ {
48
+ threadId,
49
+ userId,
50
+ messageId: null,
51
+ filename: file.name,
52
+ contentType: file.type,
53
+ sizeBytes: file.size,
54
+ storageKey,
55
+ status: "pending",
56
+ },
57
+ MAX_ATTACHMENTS_PER_MESSAGE,
58
+ )
59
+ .catch(async function (error: unknown) {
60
+ await storage.delete([storageKey]);
61
+ throw error;
62
+ });
63
+ if (!attachment) {
64
+ await storage.delete([storageKey]);
65
+ throw new HTTPException(422, { message: "Attachment limit reached" });
66
+ }
67
+
68
+ return c.json(toAttachmentSummary(attachment));
69
+ },
70
+ );
71
+
12
72
  app.get("/files/:id", requireAuth, async function (c) {
13
73
  const config = c.get("agentConfig");
14
- const id = c.req.param("id");
15
- const { id: userId } = c.get("user");
16
- const file = await config.db.capturedFiles.getById(id, userId);
74
+ const storage = requireStorage(config);
17
75
 
18
- if (!file) {
76
+ const attachment = await config.db.attachments.getById(c.req.param("id"), c.get("user").id);
77
+ if (!attachment) {
19
78
  throw new HTTPException(404, { message: "File not found" });
20
79
  }
80
+ await requireOwnedThread(c, attachment.threadId);
21
81
 
22
- const fileStream = await config.storage.stream(`captured_files/${id}`);
23
- return new Response(fileStream, {
82
+ const filename = attachment.filename
83
+ .replace(/[\r\n"\\]/g, "")
84
+ .replace(/[^\u0020-\u007e]/g, "_");
85
+
86
+ return new Response(await storage.stream(attachment.storageKey), {
24
87
  headers: {
25
- "Content-Type": "application/octet-stream",
26
- "Content-Disposition": `attachment; filename="${file.name}"`,
88
+ "Content-Type": attachment.contentType,
89
+ "Content-Disposition": `attachment; filename="${filename}"; filename*=UTF-8''${encodeURIComponent(attachment.filename)}`,
90
+ "X-Content-Type-Options": "nosniff",
27
91
  },
28
92
  });
29
93
  });
30
94
 
31
- app.post(
32
- "/files",
33
- requireAuth,
34
- zValidator(
35
- "json",
36
- z.object({
37
- toolCallId: z.string(),
38
- message: z.unknown().transform(async (message, ctx) => {
39
- const result = await safeValidateUIMessages({
40
- messages: [message],
41
- });
42
- if (!result.success) {
43
- ctx.addIssue({
44
- code: "custom",
45
- path: ["message"],
46
- message: "Invalid message format",
47
- });
48
- return z.NEVER;
49
- }
50
-
51
- return result.data[0]!;
52
- }),
53
- files: z.array(
54
- z.object({
55
- id: z.string(),
56
- file: z.object({
57
- name: z.string(),
58
- bytes: z.string(),
59
- }),
60
- }),
61
- ),
62
- }),
63
- ),
64
- async function (c) {
65
- const config = c.get("agentConfig");
66
- const { message, toolCallId, files } = c.req.valid("json");
67
- const { id: userId } = c.get("user");
68
-
69
- function isTool(value: UIMessage["parts"][number]): value is ToolUIPart {
70
- return value.type.startsWith("tool-");
71
- }
95
+ app.delete("/files/:id", requireAuth, async function (c) {
96
+ const config = c.get("agentConfig");
97
+ const storage = requireStorage(config);
72
98
 
73
- const toolPart = message.parts.filter(isTool).find((x) => x.toolCallId === toolCallId);
99
+ const id = c.req.param("id");
100
+ const userId = c.get("user").id;
101
+ const attachment = await config.db.attachments.getById(id, userId);
102
+ if (!attachment) {
103
+ throw new HTTPException(404, { message: "File not found" });
104
+ }
105
+ await requireOwnedThread(c, attachment.threadId);
106
+ if (attachment.messageId !== null) {
107
+ throw new HTTPException(409, { message: "File is attached to a message" });
108
+ }
74
109
 
75
- if (!toolPart) {
76
- throw new HTTPException(423, {
77
- message: "Invalid tool call id",
78
- });
79
- }
110
+ if (!(await storage.delete([attachment.storageKey]))) {
111
+ throw new HTTPException(502, { message: "File deletion failed" });
112
+ }
80
113
 
81
- const result = await config.db.capturedFiles.create(
82
- userId,
83
- message.id,
84
- toolPart,
85
- files,
86
- );
87
-
88
- // Store file bytes
89
- const uploadResults = await Promise.all(
90
- result.map(async (r, i) => {
91
- return await config.storage.put(
92
- `captured_files/${r.uploadId}`,
93
- files[i]!.file.bytes,
94
- );
95
- }),
96
- );
97
-
98
- if (uploadResults.some((x) => !x)) {
99
- throw new HTTPException(400, { message: "Some or all files failed to upload" });
100
- }
114
+ if (!(await config.db.attachments.remove(id, userId))) {
115
+ throw new HTTPException(404, { message: "File not found" });
116
+ }
101
117
 
102
- return c.json(result);
103
- },
104
- );
118
+ return c.body(null, 204);
119
+ });
105
120
 
106
121
  return app;
107
122
  }
123
+
124
+ function requireStorage(config: ResolvedCortexAgentConfig) {
125
+ if (!config.storage) {
126
+ throw new HTTPException(503, { message: "File storage is not configured" });
127
+ }
128
+ return config.storage;
129
+ }
@@ -0,0 +1,17 @@
1
+ import type { Context } from "hono";
2
+ import { HTTPException } from "hono/http-exception";
3
+ import type { CortexAppEnv } from "@/types";
4
+
5
+ /**
6
+ * Loads a thread and asserts it belongs to both the caller and the agent in the
7
+ * path. A thread owned by another agent 404s rather than 403 on purpose — a 403
8
+ * would confirm the thread exists, making cross-agent ids probeable.
9
+ */
10
+ export async function requireOwnedThread(c: Context<CortexAppEnv>, threadId: string) {
11
+ const thread = await c.get("agentConfig").db.threads.getById(c.get("user").id, threadId);
12
+ if (!thread || thread.agentId !== c.get("agentId")) {
13
+ throw new HTTPException(404, { message: "Not found" });
14
+ }
15
+
16
+ return thread;
17
+ }
@@ -1,12 +1,12 @@
1
1
  import { Hono } from "hono";
2
2
  import { zValidator } from "@hono/zod-validator";
3
3
  import z from "zod";
4
- import type { CortexAppEnv } from "../types.ts";
5
- import { requireAuth } from "../auth/middleware.ts";
6
- import { generateTitle } from "../ai/index.ts";
7
- import { abortStream, isStreamRunning } from "../ai/active-streams.ts";
8
- import { notify } from "../ws/index.ts";
9
- import { toThreadSummary } from "../types.ts";
4
+ import type { CortexAppEnv } from "@/types";
5
+ import { requireAuth } from "@/auth/middleware";
6
+ import { abortRun, runningThreadIds } from "@/ai/active-runs";
7
+ import { notify } from "@/ws/connections";
8
+ import { requireOwnedThread } from "./owned-thread";
9
+ import { toThreadSummary } from "@/types";
10
10
 
11
11
  export function createThreadRoutes() {
12
12
  const app = new Hono<CortexAppEnv>();
@@ -14,21 +14,19 @@ export function createThreadRoutes() {
14
14
  app.get("/threads", requireAuth, async function (c) {
15
15
  const config = c.get("agentConfig");
16
16
  const agentId = c.get("agentId");
17
- const threads = await config.db.threads
18
- .list(c.get("user").id, agentId)
19
- .then((x) => x.map((y) => toThreadSummary(y, isStreamRunning(y.id))));
20
- return c.json(threads);
17
+ const threads = await config.db.threads.list(c.get("user").id, agentId);
18
+ const running = await runningThreadIds(threads.map((thread) => thread.id));
19
+ return c.json(threads.map((thread) => toThreadSummary(thread, running.has(thread.id))));
21
20
  });
22
21
 
23
22
  app.post(
24
23
  "/threads",
25
24
  requireAuth,
26
- zValidator("json", z.object({ prompt: z.string() })),
25
+ zValidator("json", z.object({ prompt: z.string().optional() })),
27
26
  async function (c) {
28
27
  const config = c.get("agentConfig");
29
28
  const agentId = c.get("agentId");
30
29
  const userId = c.get("user").id;
31
- const { prompt } = c.req.valid("json");
32
30
  const thread = await config.db.threads.create(userId, agentId);
33
31
 
34
32
  notify(userId, agentId, {
@@ -36,8 +34,6 @@ export function createThreadRoutes() {
36
34
  payload: { thread: toThreadSummary(thread, false) },
37
35
  });
38
36
 
39
- generateTitle(thread.id, prompt, userId, config);
40
-
41
37
  return c.json(toThreadSummary(thread, false));
42
38
  },
43
39
  );
@@ -48,12 +44,9 @@ export function createThreadRoutes() {
48
44
  const userId = c.get("user").id;
49
45
  const threadId = c.req.param("threadId");
50
46
 
51
- const thread = await config.db.threads.getById(userId, threadId);
52
- if (!thread || thread.agentId !== agentId) {
53
- return c.body(null, 404);
54
- }
47
+ await requireOwnedThread(c, threadId);
55
48
 
56
- abortStream(threadId);
49
+ await abortRun(threadId);
57
50
  await config.db.threads.delete(userId, threadId);
58
51
 
59
52
  notify(userId, agentId, {
@@ -66,13 +59,9 @@ export function createThreadRoutes() {
66
59
 
67
60
  app.get("/threads/:threadId/messages", requireAuth, async function (c) {
68
61
  const config = c.get("agentConfig");
69
- const agentId = c.get("agentId");
70
62
  const userId = c.get("user").id;
71
63
  const threadId = c.req.param("threadId");
72
- const thread = await config.db.threads.getById(userId, threadId);
73
- if (!thread || thread.agentId !== agentId) {
74
- return c.body(null, 404);
75
- }
64
+ await requireOwnedThread(c, threadId);
76
65
 
77
66
  const messages = await config.db.messages
78
67
  .list(userId, threadId)
@@ -93,14 +82,9 @@ export function createThreadRoutes() {
93
82
  zValidator("json", z.object({ session: z.record(z.string(), z.unknown()) })),
94
83
  async function (c) {
95
84
  const config = c.get("agentConfig");
96
- const agentId = c.get("agentId");
97
- const userId = c.get("user").id;
98
85
  const threadId = c.req.param("threadId");
99
86
  const { session } = c.req.valid("json");
100
- const thread = await config.db.threads.getById(userId, threadId);
101
- if (!thread || thread.agentId !== agentId) {
102
- return c.body(null, 404);
103
- }
87
+ await requireOwnedThread(c, threadId);
104
88
 
105
89
  await config.db.threads.updateSession(threadId, session);
106
90
  return c.body(null, 204);
@@ -1,7 +1,7 @@
1
1
  import { Hono } from "hono";
2
2
  import { upgradeWebSocket } from "hono/bun";
3
- import type { AppEnv } from "../types.ts";
4
- import { addConnection, removeConnection } from "../ws/index.ts";
3
+ import type { AppEnv } from "@/types";
4
+ import { addConnection, removeConnection } from "@/ws/connections";
5
5
 
6
6
  type WsRouteOptions = {
7
7
  useAgentParam?: boolean;
@@ -10,7 +10,9 @@ type WsRouteOptions = {
10
10
  export function createWsRoute(options?: WsRouteOptions) {
11
11
  const app = new Hono<AppEnv>();
12
12
  const handleUpgrade = upgradeWebSocket(function (c) {
13
- const userId = c.get("user")?.id;
13
+ // upgradeWebSocket erases the app's env generic, so the context reads as any.
14
+ const user = c.get("user") as AppEnv["Variables"]["user"];
15
+ const userId = user?.id;
14
16
  const agentId =
15
17
  options?.useAgentParam === true ? c.req.param("agentId") : c.req.query("agentId");
16
18
 
@@ -40,6 +42,10 @@ export function createWsRoute(options?: WsRouteOptions) {
40
42
  return c.json({ error: "agentId is required" }, 400);
41
43
  }
42
44
 
45
+ // upgradeWebSocket types as a void middleware while tsc requires the route
46
+ // to produce a Response; the lint checker resolves the generics differently
47
+ // and would auto-strip the bridge cast, so pin it.
48
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
43
49
  return handleUpgrade(c, next) as unknown as Response;
44
50
  });
45
51
 
package/src/lib/types.ts CHANGED
@@ -1,47 +1,31 @@
1
+ import type { MessagePart } from "@tanstack/ai";
1
2
  import type { ResolvedCortexAgentConfig } from "./config";
2
3
  import type { InferSelectModel } from "drizzle-orm";
3
- import type { messages, threads } from "./db/schema";
4
+ import type { attachments, messages, threads } from "./db/schema.mssql";
4
5
 
5
- export type Thread = InferSelectModel<typeof threads>;
6
+ export type {
7
+ CortexMessage,
8
+ MessageMetadata,
9
+ ThreadSummary,
10
+ TokenUsage,
11
+ } from "@cortex/contracts/wire";
6
12
 
7
- export type StoredMessage = InferSelectModel<typeof messages>;
13
+ import type { AttachmentSummary, CortexMessage, ThreadSummary } from "@cortex/contracts/wire";
8
14
 
9
- export type ThreadSummary = {
10
- id: string;
11
- title?: string;
12
- createdAt: Date;
13
- updatedAt: Date;
14
- isRunning: boolean;
15
- };
15
+ /** A message as cortex persists and serves it: SDK parts plus cortex's envelope. */
16
+ export type ChatMessage = CortexMessage<MessagePart>;
16
17
 
17
- export type TokenUsage = {
18
- input: {
19
- noCache: number;
20
- cacheRead: number;
21
- cacheWrite: number;
22
- total: number;
23
- };
24
- output: {
25
- reasoning: number;
26
- text: number;
27
- total: number;
28
- };
29
- total: number;
30
- };
18
+ export type Thread = InferSelectModel<typeof threads>;
31
19
 
32
- export type MessageMetadata = {
33
- modelId: string;
34
- providerMetadata: unknown;
35
- isAborted?: boolean;
36
- tokenUsage?: TokenUsage;
37
- };
20
+ export type StoredMessage = InferSelectModel<typeof messages>;
38
21
 
39
- export type CapturedFileInput = {
40
- id: string;
41
- file: { name: string; bytes: string };
42
- };
22
+ export type Attachment = InferSelectModel<typeof attachments>;
23
+
24
+ export type NewAttachment = typeof attachments.$inferInsert;
43
25
 
44
26
  export type AppEnv = {
27
+ // Hono's env generics only stay assignable across helpers with the {} idiom.
28
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
45
29
  Bindings: {};
46
30
  Variables: {
47
31
  user: { id: string; token: string } | undefined;
@@ -49,6 +33,8 @@ export type AppEnv = {
49
33
  };
50
34
 
51
35
  export type AuthedAppEnv = {
36
+ // Hono's env generics only stay assignable across helpers with the {} idiom.
37
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
52
38
  Bindings: {};
53
39
  Variables: {
54
40
  user: { id: string; token: string };
@@ -56,6 +42,8 @@ export type AuthedAppEnv = {
56
42
  };
57
43
 
58
44
  export type CortexAppEnv = {
45
+ // Hono's env generics only stay assignable across helpers with the {} idiom.
46
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
59
47
  Bindings: {};
60
48
  Variables: {
61
49
  user: { id: string; token: string };
@@ -64,12 +52,25 @@ export type CortexAppEnv = {
64
52
  };
65
53
  };
66
54
 
55
+ /** Maps a stored row to the wire shape. Dates become ISO strings — the same bytes
56
+ * `JSON.stringify` would have produced, but now the type says so. */
67
57
  export function toThreadSummary(thread: Thread, isRunning: boolean) {
68
58
  return {
69
59
  id: thread.id,
70
60
  title: thread.title ?? undefined,
71
- createdAt: thread.createdAt,
72
- updatedAt: thread.updatedAt,
61
+ createdAt: thread.createdAt.toISOString(),
62
+ updatedAt: thread.updatedAt.toISOString(),
73
63
  isRunning,
74
64
  } satisfies ThreadSummary;
75
65
  }
66
+
67
+ export function toAttachmentSummary(attachment: Attachment) {
68
+ return {
69
+ id: attachment.id,
70
+ filename: attachment.filename,
71
+ contentType: attachment.contentType,
72
+ sizeBytes: attachment.sizeBytes,
73
+ status: attachment.status,
74
+ description: attachment.description ?? undefined,
75
+ } satisfies AttachmentSummary;
76
+ }
@@ -1,4 +1,5 @@
1
1
  import type { WSContext } from "hono/ws";
2
+ import type { WsEvent } from "@cortex/contracts/wire";
2
3
 
3
4
  const connections = new Map<string, WSContext[]>();
4
5
 
@@ -24,6 +25,13 @@ export function removeConnection(userId: string, agentId: string, ws: WSContext)
24
25
  }
25
26
  }
26
27
 
27
- export function getConnections(userId: string, agentId: string) {
28
+ function getConnections(userId: string, agentId: string) {
28
29
  return connections.get(getConnectionKey(userId, agentId)) ?? [];
29
30
  }
31
+
32
+ export function notify(userId: string, agentId: string, event: WsEvent) {
33
+ const message = JSON.stringify(event);
34
+ for (const ws of getConnections(userId, agentId)) {
35
+ ws.send(message);
36
+ }
37
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "compilerOptions": {
3
+ // Environment setup & latest features
4
+ "lib": ["ESNext"],
5
+ // Named explicitly: auto-inclusion of @types/* is an editor-dependent
6
+ // heuristic, and the `Bun` global comes from here.
7
+ "types": ["bun"],
8
+ "target": "ESNext",
9
+ "module": "Preserve",
10
+ "moduleDetection": "force",
11
+ "jsx": "react-jsx",
12
+ "allowJs": true,
13
+ "baseUrl": ".",
14
+
15
+ // Bundler mode
16
+ "moduleResolution": "bundler",
17
+ "verbatimModuleSyntax": true,
18
+ "noEmit": true,
19
+ "paths": {
20
+ "@m6d/cortex-server": ["./index.ts"],
21
+ // The API contracts live in internal/contracts, a private workspace
22
+ // package that never publishes; this package ships raw source, so
23
+ // `vendor` copies them into ./contracts for build and pack. The first
24
+ // candidate exists only then (and in the published tarball) — inside
25
+ // the repo resolution falls through to the workspace source.
26
+ "@cortex/contracts/*": ["./contracts/*", "../../internal/contracts/*"],
27
+ // Internal-only. tsc does not rewrite aliases on emit, so `build` runs
28
+ // tsc-alias to turn these back into relative paths in dist/**/*.d.ts —
29
+ // a consumer's tsc knows nothing about our `@/`. The published raw src
30
+ // keeps `@/`, which resolves because Bun reads this file (hence its
31
+ // presence in package.json `files`).
32
+ "@/*": ["./src/lib/*"]
33
+ },
34
+
35
+ // Best practices
36
+ "strict": true,
37
+ "skipLibCheck": true,
38
+ "noFallthroughCasesInSwitch": true,
39
+ "noUncheckedIndexedAccess": true,
40
+ "noImplicitOverride": true,
41
+
42
+ // Some stricter flags (disabled by default)
43
+ "noUnusedLocals": false,
44
+ "noUnusedParameters": false,
45
+ "noPropertyAccessFromIndexSignature": false
46
+ },
47
+ "include": ["src/lib/**/*.ts", "scripts/**/*.ts", "index.ts"]
48
+ }
@@ -1,45 +0,0 @@
1
- import type { ToolUIPart, UIMessage } from "ai";
2
- import type { Thread, StoredMessage, CapturedFileInput, TokenUsage } from "../types";
3
- import type { ThreadContextMeta } from "../ai/context/types.ts";
4
- export type DatabaseAdapter = {
5
- threads: {
6
- list(userId: string, agentId: string): Promise<Thread[]>;
7
- getById(userId: string, threadId: string): Promise<Thread | null>;
8
- create(userId: string, agentId: string): Promise<Thread>;
9
- delete(userId: string, threadId: string): Promise<void>;
10
- touch(threadId: string): Promise<Thread>;
11
- updateTitle(threadId: string, title: string): Promise<void>;
12
- updateSession(threadId: string, session: Record<string, unknown>): Promise<void>;
13
- updateContextMeta(threadId: string, meta: ThreadContextMeta): Promise<void>;
14
- };
15
- messages: {
16
- list(userId: string, threadId: string, opts?: {
17
- limit?: number;
18
- }): Promise<StoredMessage[]>;
19
- upsert(threadId: string, messages: UIMessage[]): Promise<void>;
20
- };
21
- llmRequests: {
22
- insert(requests: {
23
- messageId: string;
24
- stepNumber: number;
25
- prompt: string;
26
- output: string | null;
27
- tokenUsage: TokenUsage | null;
28
- }[]): Promise<void>;
29
- listByMessageId(messageId: string): Promise<{
30
- id: string;
31
- prompt: string;
32
- output: string | null;
33
- tokenUsage: TokenUsage | null;
34
- }[]>;
35
- };
36
- capturedFiles: {
37
- create(userId: string, messageId: string, toolPart: ToolUIPart, files: CapturedFileInput[]): Promise<{
38
- id: string;
39
- uploadId: string;
40
- }[]>;
41
- getById(id: string, userId: string): Promise<{
42
- name: string;
43
- } | null>;
44
- };
45
- };
@@ -1,3 +0,0 @@
1
- import type { DatabaseAdapter } from "./database";
2
- import type { StorageAdapter } from "./storage";
3
- export declare function createMssqlAdapter(connectionString: string, storage: StorageAdapter): DatabaseAdapter;
@@ -1,14 +0,0 @@
1
- type ActiveStream = {
2
- id: string;
3
- abortController: AbortController;
4
- buffer: string[];
5
- subscribers: Set<ReadableStreamDefaultController<string>>;
6
- isComplete: boolean;
7
- };
8
- export declare function registerStream(threadId: string, abortController: AbortController): ActiveStream;
9
- export declare function attachSseStream(threadId: string, sseStream: ReadableStream<string>): void;
10
- export declare function subscribe(threadId: string): ReadableStream<string> | null;
11
- export declare function abortStream(threadId: string): boolean;
12
- export declare function isStreamRunning(threadId: string): boolean;
13
- export declare function removeStream(threadId: string, streamId?: string): void;
14
- export {};
@@ -1,16 +0,0 @@
1
- export type { ContextConfig, ThreadContextMeta } from "./types.ts";
2
- export { DEFAULT_CONTEXT_CONFIG } from "./types.ts";
3
- export { CHARS_PER_TOKEN, estimateTokens, estimateMessageTokens, estimateMessagesTokens, } from "./token-estimator.ts";
4
- export { compressToolResults, smartStructuralCompress, summarizeValue } from "./compressor.ts";
5
- export { summarizeMessages } from "./summarizer.ts";
6
- export { buildContextMessages, trimMessagesToFit } from "./builder.ts";
7
- export { compressIntraTurnToolResults, estimateToolResultTokens, summarizeOldStepResults, } from "./intra-turn-compressor.ts";
8
- import type { UIMessage } from "ai";
9
- import type { ResolvedCortexAgentConfig } from "../../config.ts";
10
- import type { Thread } from "../../types.ts";
11
- /**
12
- * Post-response context optimization.
13
- * Called fire-and-forget from onFinish — summarizes older messages
14
- * when token usage exceeds the configured threshold.
15
- */
16
- export declare function optimizeThreadContext(thread: Thread, messages: UIMessage[], config: ResolvedCortexAgentConfig): Promise<void>;
@@ -1,6 +0,0 @@
1
- export declare const captureFilesTool: import("ai").Tool<{
2
- files: {
3
- id: string;
4
- label: string;
5
- }[];
6
- }, never>;
@@ -1,6 +0,0 @@
1
- export type ExtractEndpointsOptions = {
2
- swaggerUrl: string;
3
- domainsDir: string;
4
- write?: boolean;
5
- };
6
- export declare function extractEndpoints(options: ExtractEndpointsOptions): Promise<void>;
@@ -1,2 +0,0 @@
1
- import type { DomainDef } from "./types.ts";
2
- export declare function expandDomains(domains: Record<string, DomainDef>): Record<string, DomainDef>;