@m6d/cortex-server 1.8.0 → 2.0.1

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 (354) 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/rich-text.ts +207 -0
  10. package/contracts/runtime.ts +243 -0
  11. package/contracts/wire.ts +143 -0
  12. package/dist/contracts/graph/embed.d.ts +22 -0
  13. package/dist/{src/lib → contracts}/graph/helpers.d.ts +16 -14
  14. package/dist/{src/lib → contracts}/graph/neo4j.d.ts +5 -5
  15. package/dist/contracts/graph/schema.d.ts +62 -0
  16. package/dist/{src/lib → contracts}/graph/types.d.ts +1 -1
  17. package/dist/contracts/graph.d.ts +14 -0
  18. package/dist/contracts/rich-text.d.ts +32 -0
  19. package/dist/contracts/runtime.d.ts +310 -0
  20. package/dist/contracts/wire.d.ts +120 -0
  21. package/dist/src/lib/adapters/database/index.d.ts +61 -0
  22. package/dist/src/lib/adapters/database/message-content.d.ts +30 -0
  23. package/dist/src/lib/adapters/database/mssql/attachments.d.ts +100 -0
  24. package/dist/src/lib/adapters/database/mssql/client.d.ts +8 -0
  25. package/dist/src/lib/adapters/database/mssql/index.d.ts +194 -0
  26. package/dist/src/lib/adapters/database/mssql/llm-requests.d.ts +17 -0
  27. package/dist/src/lib/adapters/database/mssql/messages.d.ts +37 -0
  28. package/dist/src/lib/adapters/database/mssql/threads.d.ts +50 -0
  29. package/dist/src/lib/adapters/database/postgres/attachments.d.ts +113 -0
  30. package/dist/src/lib/adapters/database/postgres/client.d.ts +8 -0
  31. package/dist/src/lib/adapters/database/postgres/index.d.ts +207 -0
  32. package/dist/src/lib/adapters/database/postgres/llm-requests.d.ts +17 -0
  33. package/dist/src/lib/adapters/database/postgres/messages.d.ts +37 -0
  34. package/dist/src/lib/adapters/database/postgres/threads.d.ts +50 -0
  35. package/{src/lib/adapters/storage.ts → dist/src/lib/adapters/storage/index.d.ts} +1 -1
  36. package/dist/src/lib/adapters/{minio.d.ts → storage/minio.d.ts} +1 -1
  37. package/dist/src/lib/ai/active-runs.d.ts +63 -0
  38. package/dist/src/lib/ai/attachments.d.ts +30 -0
  39. package/dist/src/lib/ai/backend-url.d.ts +16 -0
  40. package/dist/src/lib/ai/cc-runtime.d.ts +61 -0
  41. package/dist/src/lib/ai/commit-gate.d.ts +21 -0
  42. package/dist/src/lib/ai/context/builder.d.ts +6 -7
  43. package/dist/src/lib/ai/context/compression-middleware.d.ts +15 -0
  44. package/dist/src/lib/ai/context/compressor.d.ts +2 -13
  45. package/dist/src/lib/ai/context/intra-turn-compressor.d.ts +9 -9
  46. package/dist/src/lib/ai/context/optimize-thread-context.d.ts +9 -0
  47. package/dist/src/lib/ai/context/summarizer.d.ts +3 -3
  48. package/dist/src/lib/ai/context/token-estimator.d.ts +5 -8
  49. package/dist/src/lib/ai/fetch.d.ts +1 -1
  50. package/dist/src/lib/ai/finish-turn.d.ts +23 -0
  51. package/dist/src/lib/ai/helpers.d.ts +37 -4
  52. package/dist/src/lib/ai/index.d.ts +6 -3
  53. package/dist/src/lib/ai/inspector.d.ts +41 -0
  54. package/dist/src/lib/ai/interceptors/request-interceptor.d.ts +6 -5
  55. package/dist/src/lib/ai/prompt.d.ts +5 -4
  56. package/dist/src/lib/ai/redis-runs.d.ts +41 -0
  57. package/dist/src/lib/ai/redis-stream-log.d.ts +39 -0
  58. package/dist/src/lib/ai/tools/execute-code.tool.d.ts +18 -4
  59. package/dist/src/lib/ai/tools/query-graph.tool.d.ts +13 -5
  60. package/dist/src/lib/ai/tools/read-attachment.tool.d.ts +21 -0
  61. package/dist/src/lib/ai/tools/search-common.d.ts +17 -0
  62. package/dist/src/lib/ai/tools/search-knowledge.tool.d.ts +15 -0
  63. package/dist/src/lib/ai/tools/search-services.tool.d.ts +12 -0
  64. package/dist/src/lib/ai/tools/search-tools.tool.d.ts +12 -0
  65. package/dist/src/lib/ai/turn-tools.d.ts +39 -0
  66. package/dist/src/lib/ai/vision/rasterize-pdf.d.ts +26 -0
  67. package/dist/src/lib/ai/vision/rasterize-pdf.worker.d.ts +1 -0
  68. package/dist/src/lib/ai/vision/vision-reader.d.ts +45 -0
  69. package/dist/src/lib/cc/client.d.ts +183 -0
  70. package/dist/src/lib/cc/config-cache.d.ts +20 -0
  71. package/dist/src/lib/cc/format.d.ts +23 -0
  72. package/dist/src/lib/cc/registry.d.ts +34 -0
  73. package/dist/src/lib/cc/types.d.ts +27 -0
  74. package/dist/src/lib/config.d.ts +81 -64
  75. package/dist/src/lib/db/drizzle.config.mssql.d.ts +2 -0
  76. package/dist/src/lib/db/drizzle.config.pg.d.ts +2 -0
  77. package/dist/src/lib/db/migrate.d.ts +7 -1
  78. package/dist/src/lib/db/{schema.d.ts → schema.mssql.d.ts} +138 -29
  79. package/dist/src/lib/db/schema.pg.d.ts +546 -0
  80. package/dist/src/lib/factory.d.ts +2 -12
  81. package/dist/src/lib/graph/index.d.ts +10 -11
  82. package/dist/src/lib/graph/resolver.d.ts +2 -3
  83. package/dist/src/lib/index.d.ts +3 -3
  84. package/dist/src/lib/redis.d.ts +19 -0
  85. package/dist/src/lib/routes/chat.d.ts +1 -1
  86. package/dist/src/lib/routes/files.d.ts +1 -1
  87. package/dist/src/lib/routes/owned-thread.d.ts +17 -0
  88. package/dist/src/lib/routes/threads.d.ts +1 -1
  89. package/dist/src/lib/routes/ws.d.ts +1 -1
  90. package/dist/src/lib/types.d.ts +20 -37
  91. package/dist/src/lib/ws/connections.d.ts +2 -1
  92. package/package.json +33 -18
  93. package/src/lib/adapters/database/index.ts +78 -0
  94. package/src/lib/adapters/database/message-content.ts +39 -0
  95. package/src/lib/adapters/database/mssql/attachments.ts +90 -0
  96. package/src/lib/adapters/database/mssql/client.ts +11 -0
  97. package/src/lib/adapters/database/mssql/index.ts +23 -0
  98. package/src/lib/adapters/database/mssql/llm-requests.ts +43 -0
  99. package/src/lib/adapters/database/mssql/messages.ts +92 -0
  100. package/src/lib/adapters/database/mssql/threads.ts +83 -0
  101. package/src/lib/adapters/database/postgres/attachments.ts +88 -0
  102. package/src/lib/adapters/database/postgres/client.ts +11 -0
  103. package/src/lib/adapters/database/postgres/index.ts +23 -0
  104. package/src/lib/adapters/database/postgres/llm-requests.ts +45 -0
  105. package/src/lib/adapters/database/postgres/messages.ts +92 -0
  106. package/src/lib/adapters/database/postgres/threads.ts +84 -0
  107. package/{dist/src/lib/adapters/storage.d.ts → src/lib/adapters/storage/index.ts} +1 -1
  108. package/src/lib/adapters/{minio.ts → storage/minio.ts} +5 -5
  109. package/src/lib/ai/active-runs.ts +157 -0
  110. package/src/lib/ai/attachments.ts +144 -0
  111. package/src/lib/ai/backend-url.ts +27 -0
  112. package/src/lib/ai/cc-runtime.ts +63 -0
  113. package/src/lib/ai/commit-gate.ts +116 -0
  114. package/src/lib/ai/context/builder.ts +12 -14
  115. package/src/lib/ai/context/compression-middleware.ts +44 -0
  116. package/src/lib/ai/context/compressor.ts +67 -59
  117. package/src/lib/ai/context/intra-turn-compressor.ts +121 -204
  118. package/src/lib/ai/context/optimize-thread-context.ts +50 -0
  119. package/src/lib/ai/context/summarizer.ts +28 -30
  120. package/src/lib/ai/context/token-estimator.ts +35 -30
  121. package/src/lib/ai/fetch.ts +10 -5
  122. package/src/lib/ai/finish-turn.ts +75 -0
  123. package/src/lib/ai/helpers.ts +83 -15
  124. package/src/lib/ai/index.ts +366 -329
  125. package/src/lib/ai/inspector.ts +112 -0
  126. package/src/lib/ai/interceptors/request-interceptor.ts +70 -42
  127. package/src/lib/ai/prompt.ts +126 -125
  128. package/src/lib/ai/redis-runs.ts +167 -0
  129. package/src/lib/ai/redis-stream-log.ts +219 -0
  130. package/src/lib/ai/tools/execute-code.tool.ts +178 -67
  131. package/src/lib/ai/tools/query-graph.tool.ts +7 -8
  132. package/src/lib/ai/tools/read-attachment.tool.ts +59 -0
  133. package/src/lib/ai/tools/search-common.ts +15 -0
  134. package/src/lib/ai/tools/search-knowledge.tool.ts +33 -0
  135. package/src/lib/ai/tools/search-services.tool.ts +31 -0
  136. package/src/lib/ai/tools/search-tools.tool.ts +29 -0
  137. package/src/lib/ai/turn-tools.ts +154 -0
  138. package/src/lib/ai/vision/rasterize-pdf.ts +69 -0
  139. package/src/lib/ai/vision/rasterize-pdf.worker.ts +81 -0
  140. package/src/lib/ai/vision/vision-reader.ts +130 -0
  141. package/src/lib/auth/middleware.ts +5 -3
  142. package/src/lib/cc/client.ts +273 -0
  143. package/src/lib/cc/config-cache.ts +32 -0
  144. package/src/lib/cc/format.ts +92 -0
  145. package/src/lib/cc/registry.ts +62 -0
  146. package/src/lib/cc/types.ts +44 -0
  147. package/src/lib/config.ts +102 -71
  148. package/src/lib/db/drizzle.config.mssql.ts +9 -0
  149. package/src/lib/db/drizzle.config.pg.ts +9 -0
  150. package/src/lib/db/migrate.ts +45 -10
  151. package/src/lib/db/migrations/mssql/20260729092726_talented_wilson_fisk/migration.sql +20 -0
  152. package/src/lib/db/migrations/mssql/20260729092726_talented_wilson_fisk/snapshot.json +497 -0
  153. package/src/lib/db/migrations/mssql/20260801003652_perpetual_blue_shield/migration.sql +1 -0
  154. package/src/lib/db/migrations/mssql/20260801003652_perpetual_blue_shield/snapshot.json +516 -0
  155. package/src/lib/db/migrations/mssql/20260812174642_user_id_text/migration.sql +2 -0
  156. package/src/lib/db/migrations/mssql/20260812174642_user_id_text/snapshot.json +516 -0
  157. package/src/lib/db/migrations/pg/20260801084117_thick_ben_grimm/migration.sql +53 -0
  158. package/src/lib/db/migrations/pg/20260801084117_thick_ben_grimm/snapshot.json +584 -0
  159. package/src/lib/db/migrations/pg/20260812174622_user_id_text/migration.sql +2 -0
  160. package/src/lib/db/migrations/pg/20260812174622_user_id_text/snapshot.json +584 -0
  161. package/src/lib/db/{schema.ts → schema.mssql.ts} +29 -18
  162. package/src/lib/db/schema.pg.ts +95 -0
  163. package/src/lib/factory.ts +44 -89
  164. package/src/lib/graph/index.ts +12 -40
  165. package/src/lib/graph/resolver.ts +146 -116
  166. package/src/lib/index.ts +11 -4
  167. package/src/lib/redis.ts +44 -0
  168. package/src/lib/routes/chat.ts +91 -62
  169. package/src/lib/routes/files.ts +105 -83
  170. package/src/lib/routes/owned-thread.ts +17 -0
  171. package/src/lib/routes/threads.ts +14 -30
  172. package/src/lib/routes/ws.ts +9 -3
  173. package/src/lib/types.ts +37 -36
  174. package/src/lib/ws/connections.ts +9 -1
  175. package/tsconfig.json +48 -0
  176. package/dist/src/lib/adapters/database.d.ts +0 -45
  177. package/dist/src/lib/adapters/mssql.d.ts +0 -3
  178. package/dist/src/lib/ai/active-streams.d.ts +0 -14
  179. package/dist/src/lib/ai/context/index.d.ts +0 -16
  180. package/dist/src/lib/ai/tools/capture-files.tool.d.ts +0 -6
  181. package/dist/src/lib/cli/extract-endpoints.d.ts +0 -6
  182. package/dist/src/lib/graph/expand-domains.d.ts +0 -2
  183. package/dist/src/lib/graph/generate-cypher.d.ts +0 -22
  184. package/dist/src/lib/graph/seed.d.ts +0 -19
  185. package/dist/src/lib/graph/validate.d.ts +0 -2
  186. package/dist/src/lib/routes/index.d.ts +0 -4
  187. package/dist/src/lib/ws/events.d.ts +0 -39
  188. package/dist/src/lib/ws/index.d.ts +0 -3
  189. package/dist/src/lib/ws/notify.d.ts +0 -2
  190. package/src/lib/adapters/database.ts +0 -48
  191. package/src/lib/adapters/mssql.ts +0 -231
  192. package/src/lib/ai/active-streams.ts +0 -123
  193. package/src/lib/ai/context/index.ts +0 -80
  194. package/src/lib/ai/tools/capture-files.tool.ts +0 -20
  195. package/src/lib/cli/extract-endpoints.ts +0 -550
  196. package/src/lib/graph/expand-domains.ts +0 -276
  197. package/src/lib/graph/generate-cypher.ts +0 -192
  198. package/src/lib/graph/seed.ts +0 -162
  199. package/src/lib/graph/validate.ts +0 -78
  200. package/src/lib/routes/index.ts +0 -4
  201. package/src/lib/ws/events.ts +0 -39
  202. package/src/lib/ws/index.ts +0 -11
  203. package/src/lib/ws/notify.ts +0 -9
  204. package/src/sample/db/client.ts +0 -9
  205. package/src/sample/db/migrations/20260411023125_rich_purple_man/migration.sql +0 -5
  206. package/src/sample/db/migrations/20260411023125_rich_purple_man/snapshot.json +0 -50
  207. package/src/sample/db/schema.ts +0 -10
  208. package/src/sample/domains/account/concepts/session.concept.ts +0 -17
  209. package/src/sample/domains/account/endpoints/listCurrentSessions.endpoint.ts +0 -31
  210. package/src/sample/domains/account/endpoints/revokeAllOtherSessions.endpoint.ts +0 -22
  211. package/src/sample/domains/account/endpoints/revokeCurrentSession.endpoint.ts +0 -33
  212. package/src/sample/domains/account/index.ts +0 -18
  213. package/src/sample/domains/appraisals/concepts/appraisalCycle.concept.ts +0 -15
  214. package/src/sample/domains/appraisals/concepts/appraisalRecord.concept.ts +0 -20
  215. package/src/sample/domains/appraisals/concepts/appraisalRecordCompetency.concept.ts +0 -10
  216. package/src/sample/domains/appraisals/concepts/appraisalRecordFunctionalRequirement.concept.ts +0 -10
  217. package/src/sample/domains/appraisals/concepts/appraisalRecordGoal.concept.ts +0 -17
  218. package/src/sample/domains/appraisals/endpoints/getAppraisalRecordById.endpoint.ts +0 -321
  219. package/src/sample/domains/appraisals/endpoints/getAppraisalRecordCompetencies.endpoint.ts +0 -120
  220. package/src/sample/domains/appraisals/endpoints/getAppraisalRecordFunctionalRequirements.endpoint.ts +0 -126
  221. package/src/sample/domains/appraisals/endpoints/getAppraisalRecordGoals.endpoint.ts +0 -104
  222. package/src/sample/domains/appraisals/endpoints/getAppraisalRecordScore.endpoint.ts +0 -58
  223. package/src/sample/domains/appraisals/endpoints/listAppraisalCyclesSimple.endpoint.ts +0 -52
  224. package/src/sample/domains/appraisals/endpoints/listAppraisalRecords.endpoint.ts +0 -245
  225. package/src/sample/domains/appraisals/endpoints/listAppraisalTemplatesSimple.endpoint.ts +0 -52
  226. package/src/sample/domains/appraisals/index.ts +0 -40
  227. package/src/sample/domains/appraisals/rules/appraisalRecordScoping.rule.ts +0 -7
  228. package/src/sample/domains/attendance/concepts/attendancePermission.concept.ts +0 -17
  229. package/src/sample/domains/attendance/concepts/attendanceTransaction.concept.ts +0 -17
  230. package/src/sample/domains/attendance/concepts/publicHoliday.concept.ts +0 -10
  231. package/src/sample/domains/attendance/concepts/punch.concept.ts +0 -19
  232. package/src/sample/domains/attendance/endpoints/getAttendanceTransactionById.endpoint.ts +0 -444
  233. package/src/sample/domains/attendance/endpoints/getCurrentAttendanceProfile.endpoint.ts +0 -886
  234. package/src/sample/domains/attendance/endpoints/getCurrentAttendanceStatistics.endpoint.ts +0 -49
  235. package/src/sample/domains/attendance/endpoints/listAttendancePermissions.endpoint.ts +0 -176
  236. package/src/sample/domains/attendance/endpoints/listAttendanceTransactionStates.endpoint.ts +0 -26
  237. package/src/sample/domains/attendance/endpoints/listAttendanceTransactions.endpoint.ts +0 -373
  238. package/src/sample/domains/attendance/endpoints/listPublicHolidaysSimple.endpoint.ts +0 -52
  239. package/src/sample/domains/attendance/endpoints/listPunchTypes.endpoint.ts +0 -25
  240. package/src/sample/domains/attendance/endpoints/listPunches.endpoint.ts +0 -178
  241. package/src/sample/domains/attendance/index.ts +0 -41
  242. package/src/sample/domains/attendance/services/attendancePermissions.service.ts +0 -15
  243. package/src/sample/domains/employees/concepts/employee.concept.ts +0 -20
  244. package/src/sample/domains/employees/concepts/employeeBankAccount.concept.ts +0 -19
  245. package/src/sample/domains/employees/concepts/employeeChild.concept.ts +0 -19
  246. package/src/sample/domains/employees/concepts/employeeDocument.concept.ts +0 -21
  247. package/src/sample/domains/employees/concepts/employeeEvent.concept.ts +0 -21
  248. package/src/sample/domains/employees/concepts/employeeExperience.concept.ts +0 -18
  249. package/src/sample/domains/employees/concepts/employeeJobLevelChange.concept.ts +0 -21
  250. package/src/sample/domains/employees/concepts/employeeMedal.concept.ts +0 -20
  251. package/src/sample/domains/employees/concepts/employeeQualification.concept.ts +0 -20
  252. package/src/sample/domains/employees/concepts/employeeSpouse.concept.ts +0 -21
  253. package/src/sample/domains/employees/concepts/employeeViolation.concept.ts +0 -19
  254. package/src/sample/domains/employees/endpoints/getCurrentEmployee.endpoint.ts +0 -1651
  255. package/src/sample/domains/employees/endpoints/getCurrentIdentity.endpoint.ts +0 -197
  256. package/src/sample/domains/employees/endpoints/getCurrentManagers.endpoint.ts +0 -142
  257. package/src/sample/domains/employees/endpoints/getEmployeeById.endpoint.ts +0 -1659
  258. package/src/sample/domains/employees/endpoints/getEmployeeStatistics.endpoint.ts +0 -43
  259. package/src/sample/domains/employees/endpoints/listBankAccounts.endpoint.ts +0 -223
  260. package/src/sample/domains/employees/endpoints/listChildren.endpoint.ts +0 -211
  261. package/src/sample/domains/employees/endpoints/listDocuments.endpoint.ts +0 -222
  262. package/src/sample/domains/employees/endpoints/listEmployeesSimple.endpoint.ts +0 -156
  263. package/src/sample/domains/employees/endpoints/listEvents.endpoint.ts +0 -120
  264. package/src/sample/domains/employees/endpoints/listExperiences.endpoint.ts +0 -188
  265. package/src/sample/domains/employees/endpoints/listJobLevelChanges.endpoint.ts +0 -240
  266. package/src/sample/domains/employees/endpoints/listMedals.endpoint.ts +0 -266
  267. package/src/sample/domains/employees/endpoints/listQualifications.endpoint.ts +0 -265
  268. package/src/sample/domains/employees/endpoints/listSpouses.endpoint.ts +0 -278
  269. package/src/sample/domains/employees/endpoints/listViolations.endpoint.ts +0 -245
  270. package/src/sample/domains/employees/index.ts +0 -75
  271. package/src/sample/domains/employees/services/employees.service.ts +0 -181
  272. package/src/sample/domains/index.ts +0 -10
  273. package/src/sample/domains/leaves/concepts/leave.concept.ts +0 -21
  274. package/src/sample/domains/leaves/concepts/leaveBalance.concept.ts +0 -17
  275. package/src/sample/domains/leaves/concepts/leaveBalanceTransaction.concept.ts +0 -16
  276. package/src/sample/domains/leaves/concepts/leaveType.concept.ts +0 -13
  277. package/src/sample/domains/leaves/concepts/leaveTypes.concept.ts +0 -205
  278. package/src/sample/domains/leaves/endpoints/getBalance.endpoint.ts +0 -53
  279. package/src/sample/domains/leaves/endpoints/getLeaveById.endpoint.ts +0 -53
  280. package/src/sample/domains/leaves/endpoints/listBalanceTransactions.endpoint.ts +0 -196
  281. package/src/sample/domains/leaves/endpoints/listBalanceTypes.endpoint.ts +0 -26
  282. package/src/sample/domains/leaves/endpoints/listBalances.endpoint.ts +0 -201
  283. package/src/sample/domains/leaves/endpoints/listLeaveTypes.endpoint.ts +0 -28
  284. package/src/sample/domains/leaves/endpoints/listLeaves.endpoint.ts +0 -234
  285. package/src/sample/domains/leaves/index.ts +0 -38
  286. package/src/sample/domains/leaves/services/leaveRequests.service.ts +0 -232
  287. package/src/sample/domains/notifications/concepts/notification.concept.ts +0 -19
  288. package/src/sample/domains/notifications/endpoints/countMyNotifications.endpoint.ts +0 -21
  289. package/src/sample/domains/notifications/endpoints/getMyNotification.endpoint.ts +0 -57
  290. package/src/sample/domains/notifications/endpoints/listMyNotifications.endpoint.ts +0 -59
  291. package/src/sample/domains/notifications/endpoints/markMyNotificationAsRead.endpoint.ts +0 -32
  292. package/src/sample/domains/notifications/index.ts +0 -20
  293. package/src/sample/domains/payroll/concepts/payslip.concept.ts +0 -18
  294. package/src/sample/domains/payroll/concepts/salaryCertificate.concept.ts +0 -17
  295. package/src/sample/domains/payroll/concepts/salaryCertificateRequestingEntity.concept.ts +0 -8
  296. package/src/sample/domains/payroll/endpoints/getPayslipById.endpoint.ts +0 -238
  297. package/src/sample/domains/payroll/endpoints/listPayslips.endpoint.ts +0 -216
  298. package/src/sample/domains/payroll/endpoints/listSalaryCertificateLanguages.endpoint.ts +0 -25
  299. package/src/sample/domains/payroll/endpoints/listSalaryCertificateRequestingEntities.endpoint.ts +0 -62
  300. package/src/sample/domains/payroll/endpoints/listSalaryCertificateTypes.endpoint.ts +0 -24
  301. package/src/sample/domains/payroll/endpoints/listSalaryCertificates.endpoint.ts +0 -122
  302. package/src/sample/domains/payroll/endpoints/previewSalaryCertificate.endpoint.ts +0 -45
  303. package/src/sample/domains/payroll/index.ts +0 -32
  304. package/src/sample/domains/payroll/rules/payrollEmployeeContext.rule.ts +0 -7
  305. package/src/sample/domains/payroll/services/salaryCertificates.service.ts +0 -15
  306. package/src/sample/domains/servicing/concepts/service.concept.ts +0 -6
  307. package/src/sample/domains/servicing/concepts/serviceRequest.concept.ts +0 -12
  308. package/src/sample/domains/servicing/concepts/serviceRequestApproval.concept.ts +0 -9
  309. package/src/sample/domains/servicing/endpoints/cancelServiceRequest.endpoint.ts +0 -21
  310. package/src/sample/domains/servicing/endpoints/createServiceRequest.endpoint.ts +0 -511
  311. package/src/sample/domains/servicing/endpoints/getServiceRequest.endpoint.ts +0 -352
  312. package/src/sample/domains/servicing/endpoints/getServiceRequestFormItems.endpoint.ts +0 -219
  313. package/src/sample/domains/servicing/endpoints/getServiceRequestTransactionFormItems.endpoint.ts +0 -216
  314. package/src/sample/domains/servicing/endpoints/getServiceStates.endpoint.ts +0 -47
  315. package/src/sample/domains/servicing/endpoints/invokeServiceRequestAction.endpoint.ts +0 -139
  316. package/src/sample/domains/servicing/endpoints/listServiceRequests.endpoint.ts +0 -292
  317. package/src/sample/domains/servicing/endpoints/listServices.endpoint.ts +0 -108
  318. package/src/sample/domains/servicing/endpoints/updateServiceRequest.endpoint.ts +0 -355
  319. package/src/sample/domains/servicing/index.ts +0 -44
  320. package/src/sample/domains/servicing/rules/checkValidActions.rule.ts +0 -7
  321. package/src/sample/domains/servicing/rules/createServiceRequest.rule.ts +0 -7
  322. package/src/sample/domains/servicing/rules/filterServiceRequestsByState.rule.ts +0 -7
  323. package/src/sample/domains/servicing/rules/passingOptionFields.rule.ts +0 -7
  324. package/src/sample/domains/shared/rules/pagination.rule.ts +0 -7
  325. package/src/sample/domains/suggestions/concepts/suggestion.concept.ts +0 -19
  326. package/src/sample/domains/suggestions/concepts/suggestionCategory.concept.ts +0 -7
  327. package/src/sample/domains/suggestions/concepts/suggestionImpactLevel.concept.ts +0 -7
  328. package/src/sample/domains/suggestions/endpoints/createSuggestion.endpoint.ts +0 -705
  329. package/src/sample/domains/suggestions/endpoints/deleteSuggestion.endpoint.ts +0 -32
  330. package/src/sample/domains/suggestions/endpoints/getSuggestionById.endpoint.ts +0 -635
  331. package/src/sample/domains/suggestions/endpoints/listSuggestionCategories.endpoint.ts +0 -62
  332. package/src/sample/domains/suggestions/endpoints/listSuggestionImpactLevels.endpoint.ts +0 -62
  333. package/src/sample/domains/suggestions/endpoints/listSuggestionStates.endpoint.ts +0 -24
  334. package/src/sample/domains/suggestions/endpoints/listSuggestions.endpoint.ts +0 -132
  335. package/src/sample/domains/suggestions/endpoints/updateSuggestion.endpoint.ts +0 -690
  336. package/src/sample/domains/suggestions/endpoints/updateSuggestionState.endpoint.ts +0 -39
  337. package/src/sample/domains/suggestions/index.ts +0 -34
  338. package/src/sample/domains/suggestions/rules/suggestionScope.rule.ts +0 -7
  339. package/src/sample/domains/surveys/concepts/survey.concept.ts +0 -10
  340. package/src/sample/domains/surveys/concepts/surveyResponse.concept.ts +0 -14
  341. package/src/sample/domains/surveys/endpoints/getSurveyResponseById.endpoint.ts +0 -131
  342. package/src/sample/domains/surveys/endpoints/getTargetedSurvey.endpoint.ts +0 -129
  343. package/src/sample/domains/surveys/endpoints/listTargetedSurveys.endpoint.ts +0 -160
  344. package/src/sample/domains/surveys/endpoints/respondToSurvey.endpoint.ts +0 -144
  345. package/src/sample/domains/surveys/index.ts +0 -21
  346. package/src/sample/drizzle.config.ts +0 -11
  347. package/src/sample/index.bak.ts +0 -341
  348. package/src/sample/index.ts +0 -318
  349. package/src/sample/official-statements/defaults.ts +0 -57
  350. package/src/sample/official-statements/routes.ts +0 -137
  351. package/src/sample/official-statements/service.ts +0 -148
  352. package/src/sample/official-statements/types.ts +0 -23
  353. /package/src/lib/db/migrations/{20260326231647_nice_speedball → mssql/20260326231647_nice_speedball}/migration.sql +0 -0
  354. /package/src/lib/db/migrations/{20260326231647_nice_speedball → mssql/20260326231647_nice_speedball}/snapshot.json +0 -0
@@ -0,0 +1,50 @@
1
+ import type { ThreadContextMeta } from "../../../ai/context/types";
2
+ import type { PostgresDb } from "./client";
3
+ import type { StorageAdapter } from "../../../adapters/storage/index";
4
+ export declare function createThreadsRepository(db: PostgresDb, storage?: StorageAdapter): {
5
+ list(userId: string, agentId: string): Promise<{
6
+ createdAt: Date;
7
+ updatedAt: Date;
8
+ id: string;
9
+ userId: string;
10
+ agentId: string;
11
+ title: string | null;
12
+ session: Record<string, unknown> | null;
13
+ contextMeta: ThreadContextMeta | null;
14
+ }[]>;
15
+ getById(userId: string, threadId: string): Promise<{
16
+ id: string;
17
+ userId: string;
18
+ agentId: string;
19
+ title: string | null;
20
+ session: Record<string, unknown> | null;
21
+ contextMeta: ThreadContextMeta | null;
22
+ createdAt: Date;
23
+ updatedAt: Date;
24
+ } | null>;
25
+ create(userId: string, agentId: string): Promise<{
26
+ id: string;
27
+ userId: string;
28
+ agentId: string;
29
+ title: string | null;
30
+ session: Record<string, unknown> | null;
31
+ contextMeta: ThreadContextMeta | null;
32
+ createdAt: Date;
33
+ updatedAt: Date;
34
+ }>;
35
+ /** Object storage has no foreign keys, so attachment paths must be swept before row cascade. */
36
+ delete(userId: string, threadId: string): Promise<void>;
37
+ touch(threadId: string): Promise<{
38
+ id: string;
39
+ userId: string;
40
+ agentId: string;
41
+ title: string | null;
42
+ session: Record<string, unknown> | null;
43
+ contextMeta: ThreadContextMeta | null;
44
+ createdAt: Date;
45
+ updatedAt: Date;
46
+ }>;
47
+ updateTitle(threadId: string, title: string): Promise<void>;
48
+ updateSession(threadId: string, session: Record<string, unknown>): Promise<void>;
49
+ updateContextMeta(threadId: string, meta: ThreadContextMeta): Promise<void>;
50
+ };
@@ -2,5 +2,5 @@ export type StorageAdapter = {
2
2
  put(path: string, data: string): Promise<boolean>;
3
3
  get(path: string): Promise<string | false>;
4
4
  delete(paths: string[]): Promise<boolean>;
5
- stream(path: string): Promise<ReadableStream>;
5
+ stream(path: string): Promise<ReadableStream<Uint8Array>>;
6
6
  };
@@ -1,4 +1,4 @@
1
- import type { StorageAdapter } from "./storage";
1
+ import type { StorageAdapter } from "./index";
2
2
  export type MinioConfig = {
3
3
  endPoint: string;
4
4
  port: number;
@@ -0,0 +1,63 @@
1
+ import { type StreamDurability } from "@tanstack/ai";
2
+ /**
3
+ * The live turn on a thread. Generation runs detached from the HTTP request that
4
+ * started it, so this registry — not the request — owns the run's lifetime: it is
5
+ * how abort reaches a producer and how a reconnecting client finds the run to
6
+ * rejoin.
7
+ */
8
+ export type ActiveRun = {
9
+ runId: string;
10
+ abortController: AbortController;
11
+ };
12
+ /**
13
+ * One backend owns both halves of a live run: the thread→run claim registry and
14
+ * the durability log the run streams through. In-memory is the single-process
15
+ * default; `createCortex({ redis })` swaps in the Redis coordinator so claims,
16
+ * aborts, and logs survive a producer restart and reach every instance.
17
+ */
18
+ export type RunCoordinator = {
19
+ /** Claims the thread for a new run, aborting whatever was running on it. */
20
+ startRun: (threadId: string) => Promise<ActiveRun>;
21
+ getRunId: (threadId: string) => Promise<string | undefined>;
22
+ /** Which of `threadIds` have a live run — one round trip, for list views. */
23
+ runningThreadIds: (threadIds: string[]) => Promise<Set<string>>;
24
+ /** Aborts the thread's live run. False when there was none to abort — the
25
+ * caller must not report an abort that never happened. */
26
+ abortRun: (threadId: string) => Promise<boolean>;
27
+ /** Releases the thread, but only for the run that still holds it — a
28
+ * superseded run finishing late must not evict its replacement. */
29
+ endRun: (threadId: string, runId: string) => Promise<void>;
30
+ /** The producer's sink: `resumeFrom()` is null, so appends flow into the log. */
31
+ producerLog: (runId: string) => StreamDurability;
32
+ /** A reader on the run's log, replaying from `offset` and tailing until close.
33
+ * Takes the thread too: the thread's claim is how a reader can tell a live
34
+ * producer from a dead one. */
35
+ joinLog: (threadId: string, runId: string, offset?: string) => StreamDurability;
36
+ /**
37
+ * Whether a client-supplied resume offset belongs to `runId`. The offset is
38
+ * the adapter's own opaque token and names the log it replays — so an offset
39
+ * naming another run would replay that run's log to whoever presents it.
40
+ */
41
+ offsetBelongsToRun: (offset: string, runId: string) => boolean;
42
+ };
43
+ /**
44
+ * How long a joiner waits for a run's first chunk. The adapter arms this on any
45
+ * empty log, and it cannot tell "the producer died" from "the producer has not
46
+ * reached the model yet" — so it has to clear the worst case: a compression
47
+ * middleware's extra summarization call plus the model's time to first token.
48
+ * It is generous because it is only a backstop: a producer that fails writes its
49
+ * own terminal event into the log, and a run that ended is gone from the
50
+ * registry, so neither ever reaches this timer.
51
+ */
52
+ export declare const JOIN_FIRST_CHUNK_TIMEOUT_MS: number;
53
+ /** `createCortex` swaps the backend in once at startup; everything below delegates. */
54
+ export declare function configureRunCoordination(backend: RunCoordinator): void;
55
+ export declare function startRun(threadId: string): Promise<ActiveRun>;
56
+ export declare function getRunId(threadId: string): Promise<string | undefined>;
57
+ export declare function isRunning(threadId: string): Promise<boolean>;
58
+ export declare function runningThreadIds(threadIds: string[]): Promise<Set<string>>;
59
+ export declare function abortRun(threadId: string): Promise<boolean>;
60
+ export declare function endRun(threadId: string, runId: string): Promise<void>;
61
+ export declare function producerLog(runId: string): StreamDurability<string>;
62
+ export declare function joinLog(threadId: string, runId: string, offset?: string): StreamDurability<string>;
63
+ export declare function offsetBelongsToRun(offset: string, runId: string): boolean;
@@ -0,0 +1,30 @@
1
+ import type { ResolvedCortexAgentConfig } from "../config";
2
+ import type { Attachment, ChatMessage } from "../types";
3
+ type PrepareAttachmentsOptions = {
4
+ config: ResolvedCortexAgentConfig;
5
+ threadId: string;
6
+ userId: string;
7
+ message: ChatMessage;
8
+ abortSignal?: AbortSignal;
9
+ };
10
+ type AttachmentCapabilities = {
11
+ readAttachment: boolean;
12
+ attachmentSentinels: boolean;
13
+ };
14
+ export declare function prepareAttachmentsForTurn(options: PrepareAttachmentsOptions): Promise<{
15
+ id: string;
16
+ userId: string;
17
+ createdAt: Date;
18
+ updatedAt: Date;
19
+ threadId: string;
20
+ messageId: string | null;
21
+ filename: string;
22
+ contentType: string;
23
+ sizeBytes: number;
24
+ storageKey: string;
25
+ status: "pending" | "described" | "failed" | "skipped";
26
+ description: string | null;
27
+ }[]>;
28
+ export declare function buildAttachmentListing(attachmentRows: Attachment[], currentMessageId: string | undefined, capabilities: AttachmentCapabilities): string | undefined;
29
+ export declare function sanitizeAttachmentText(value: string, maxLength?: number): string;
30
+ export {};
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Resolves a backend call target, refusing anything that leaves the configured
3
+ * origin or escapes its base path.
4
+ *
5
+ * `path` arrives from code the model wrote inside the sandbox, so it is untrusted.
6
+ * Concatenating it onto `baseUrl` was unsafe: when `baseUrl` carries no trailing
7
+ * slash — the form the docs show — a path of `@evil.test/x` produces
8
+ * `https://api.example.com@evil.test/x`, where everything before the `@` is read
9
+ * as userinfo and the host becomes `evil.test`. The request carries the service
10
+ * API key and the caller's token, so that is a credential leak, not just an SSRF.
11
+ *
12
+ * Resolving against an explicitly slash-terminated base also neutralizes
13
+ * protocol-relative (`//host`) and absolute (`https://host`) paths, which the
14
+ * origin check below then rejects outright.
15
+ */
16
+ export declare function resolveBackendUrl(baseUrl: string, path: string): URL;
@@ -0,0 +1,61 @@
1
+ import type { ResolvedCortexAgentConfig } from "../config";
2
+ import type { Thread } from "../types";
3
+ import type { ControlCenterClient } from "../cc/client";
4
+ import type { CcToolRegistry } from "../cc/registry";
5
+ import type { ResolveResponse, RuntimeAgentConfig } from "../cc/types";
6
+ type CcRuntimeOptions = {
7
+ ccClient: ControlCenterClient | null;
8
+ ccConfig: RuntimeAgentConfig | null;
9
+ ccResolved: ResolveResponse | null;
10
+ config: ResolvedCortexAgentConfig;
11
+ thread: Thread;
12
+ userId: string;
13
+ token: string;
14
+ turnKey: string;
15
+ abortSignal: AbortSignal;
16
+ getStepIndex: () => number;
17
+ /** Reports Control Center tools invoked from inside the sandbox, which the
18
+ * outer tool instrumentation never sees — it only observes `executeCode`. */
19
+ onToolProgress: (toolName: string, toolCallId: string, status: "started" | "finished") => void;
20
+ };
21
+ /**
22
+ * Builds the per-turn Control Center runtime, or undefined when the agent has no
23
+ * Control Center configured — every consumer treats that as "skip CC entirely".
24
+ *
25
+ * Owns the call-index counter, which must restart at zero on each new step so
26
+ * idempotency keys stay stable when a step is retried.
27
+ */
28
+ export declare function createCcRuntime(options: CcRuntimeOptions): {
29
+ client: ControlCenterClient;
30
+ agentId: string;
31
+ config: {
32
+ agentId: string;
33
+ systemPrompt: string;
34
+ promptVariables: ("userName" | "channel" | "locale" | "utcTime" | "timezone")[];
35
+ catalogBlurb: string;
36
+ defaultLocale: "ar" | "en";
37
+ metaTools: {
38
+ searchKnowledge: boolean;
39
+ searchTools: boolean;
40
+ searchServices: boolean;
41
+ };
42
+ limits: {
43
+ resolveTokenBudget: number;
44
+ executeTimeoutMs: number;
45
+ maxResponseBytes: number;
46
+ };
47
+ catalogVersion: string;
48
+ publishedAt: string;
49
+ };
50
+ registry: CcToolRegistry;
51
+ threadId: string;
52
+ turnKey: string;
53
+ userId: string;
54
+ locale: "ar" | "en";
55
+ endUserToken: string;
56
+ abortSignal: AbortSignal;
57
+ getStepIndex: () => number;
58
+ nextCallIndex(stepIndex: number): number;
59
+ onToolProgress: (toolName: string, toolCallId: string, status: "started" | "finished") => void;
60
+ } | undefined;
61
+ export {};
@@ -0,0 +1,21 @@
1
+ import { EventType, type StreamChunk, type UIMessage } from "@tanstack/ai";
2
+ type CommitGateOptions = {
3
+ /** Persists the run's messages. Its rejection is reported to the client. */
4
+ commit: (messages: UIMessage[]) => Promise<void>;
5
+ isAborted: () => boolean;
6
+ };
7
+ /**
8
+ * Rebuilds the run's messages from its own chunks and holds the run's terminal
9
+ * event back until they are committed, so a client that refetches when the
10
+ * stream ends can never race the database.
11
+ *
12
+ * Only the terminal event ever waits, and it has to be the *last* one rather
13
+ * than the first: the agent loop emits a terminal event per iteration, and which
14
+ * one ends the run is only knowable once the stream is exhausted.
15
+ */
16
+ export declare function commitBeforeTerminal(stream: AsyncIterable<StreamChunk>, options: CommitGateOptions): AsyncGenerator<import("@tanstack/ai").AGUIEvent | {
17
+ type: EventType.RUN_ERROR;
18
+ timestamp: number;
19
+ message: string;
20
+ }, void, unknown>;
21
+ export {};
@@ -1,7 +1,6 @@
1
- import type { UIMessage } from "ai";
2
- import type { DatabaseAdapter } from "../../adapters/database.ts";
3
- import type { MessageMetadata, Thread } from "../../types.ts";
4
- import type { ContextConfig } from "./types.ts";
1
+ import type { DatabaseAdapter } from "../../adapters/database/index";
2
+ import type { ChatMessage, Thread } from "../../types";
3
+ import type { ContextConfig } from "./types";
5
4
  /**
6
5
  * Builds a token-aware context window from stored messages.
7
6
  *
@@ -13,12 +12,12 @@ import type { ContextConfig } from "./types.ts";
13
12
  * 6. Prepends summary as synthetic message if older messages were trimmed
14
13
  */
15
14
  export declare function buildContextMessages(userId: string, thread: Thread, db: DatabaseAdapter, contextConfig: ContextConfig): Promise<{
16
- messages: UIMessage<MessageMetadata, import("ai").UIDataTypes, import("ai").UITools>[];
17
- allMessages: UIMessage<MessageMetadata, import("ai").UIDataTypes, import("ai").UITools>[];
15
+ messages: ChatMessage[];
16
+ allMessages: ChatMessage[];
18
17
  summary: string | null;
19
18
  }>;
20
19
  /**
21
20
  * Drops the oldest messages until the total estimated tokens fit within `budget`.
22
21
  * Always keeps at least the most recent message.
23
22
  */
24
- export declare function trimMessagesToFit(messages: UIMessage<MessageMetadata>[], budget: number): UIMessage<MessageMetadata, import("ai").UIDataTypes, import("ai").UITools>[];
23
+ export declare function trimMessagesToFit(messages: ChatMessage[], budget: number): ChatMessage[];
@@ -0,0 +1,15 @@
1
+ import type { ResolvedCortexAgentConfig } from "../../config";
2
+ /**
3
+ * Keeps a single turn's tool results inside the context window as steps accumulate.
4
+ *
5
+ * `onConfig` runs before every model call in the agent loop. Truncating older results
6
+ * is free, so it always happens; summarizing costs an extra model call and only
7
+ * happens if truncation left us over the threshold. A failed summarization is logged
8
+ * and swallowed — degrading to the merely-truncated prompt beats failing the turn.
9
+ */
10
+ export declare function createCompressionMiddleware(config: ResolvedCortexAgentConfig): {
11
+ name: string;
12
+ onConfig(_ctx: import("@tanstack/ai").ChatMiddlewareContext<unknown>, { messages }: import("@tanstack/ai").ChatMiddlewareConfig): Promise<{
13
+ messages: import("@tanstack/ai").ModelMessage<string | import("@tanstack/ai").ContentPart<unknown, unknown, unknown, unknown, unknown>[] | null>[];
14
+ }>;
15
+ };
@@ -1,18 +1,7 @@
1
- import type { UIMessage } from "ai";
2
- import type { MessageMetadata } from "../../types.ts";
1
+ import type { ChatMessage } from "../../types";
3
2
  /**
4
3
  * Returns a new array of messages with large tool outputs truncated
5
4
  * to `maxTokensPerResult`. Does not mutate the input messages.
6
5
  */
7
- export declare function compressToolResults(messages: UIMessage<MessageMetadata>[], maxTokensPerResult: number): UIMessage<MessageMetadata, import("ai").UIDataTypes, import("ai").UITools>[];
8
- /**
9
- * Structurally compresses a value to fit within a character budget.
10
- * Understands JSON arrays, error objects, and nested objects — preserving
11
- * semantic meaning better than naive string truncation.
12
- */
13
- export declare function smartStructuralCompress(value: unknown, charBudget: number): string;
14
- /**
15
- * Produces a short human-readable summary of a value's shape and key data.
16
- * Used both for inline object-key placeholders and for tool result one-liners.
17
- */
6
+ export declare function compressToolResults(messages: ChatMessage[], maxTokensPerResult: number): ChatMessage[];
18
7
  export declare function summarizeValue(val: unknown): string;
@@ -1,24 +1,24 @@
1
- import type { LanguageModelV3Prompt } from "@ai-sdk/provider";
2
- import type { ContextConfig } from "./types.ts";
1
+ import type { ModelMessage } from "@tanstack/ai";
2
+ import type { ContextConfig } from "./types";
3
3
  type SummarizationModelConfig = NonNullable<ContextConfig["summarizationModel"]>;
4
4
  /**
5
5
  * Compresses tool results from older steps in the prompt.
6
6
  *
7
7
  * On step N, tool results from steps 1..N-2 are aggressively compressed
8
- * to short one-liners. Only the most recent tool result stays in full.
9
- * Does not mutate the input — returns a new prompt array.
8
+ * to short one-liners. Only the most recent step's results stay in full.
9
+ * Does not mutate the input — returns a new array.
10
10
  */
11
- export declare function compressIntraTurnToolResults(prompt: LanguageModelV3Prompt, toolResultMaxTokens: number): LanguageModelV3Prompt;
11
+ export declare function compressIntraTurnToolResults(messages: ModelMessage[], toolResultMaxTokens: number): ModelMessage<string | import("@tanstack/ai").ContentPart<unknown, unknown, unknown, unknown, unknown>[] | null>[];
12
12
  /**
13
13
  * Estimates the total token count of tool results in the prompt.
14
14
  */
15
- export declare function estimateToolResultTokens(prompt: LanguageModelV3Prompt): number;
15
+ export declare function estimateToolResultTokens(messages: ModelMessage[]): number;
16
16
  /**
17
17
  * When accumulated tool result tokens exceed the threshold, summarizes
18
18
  * older step results using a lightweight LLM call.
19
19
  *
20
- * Replaces all tool results except the last two with a single synthetic
21
- * summary in the oldest tool message.
20
+ * Replaces every tool result before the last two steps with a single
21
+ * synthetic summary in the oldest tool message.
22
22
  */
23
- export declare function summarizeOldStepResults(prompt: LanguageModelV3Prompt, thresholdTokens: number, modelConfig: SummarizationModelConfig): Promise<LanguageModelV3Prompt>;
23
+ export declare function summarizeOldStepResults(messages: ModelMessage[], thresholdTokens: number, modelConfig: SummarizationModelConfig): Promise<ModelMessage<string | import("@tanstack/ai").ContentPart<unknown, unknown, unknown, unknown, unknown>[] | null>[]>;
24
24
  export {};
@@ -0,0 +1,9 @@
1
+ import type { ResolvedCortexAgentConfig } from "../../config";
2
+ import type { ChatMessage, Thread } from "../../types";
3
+ /**
4
+ * Post-response context optimization, called fire-and-forget from onFinish.
5
+ *
6
+ * Below the summarization threshold this only refreshes the token estimate —
7
+ * summarizing early would burn a model call to compress context that still fits.
8
+ */
9
+ export declare function optimizeThreadContext(thread: Thread, messages: ChatMessage[], config: ResolvedCortexAgentConfig): Promise<void>;
@@ -1,5 +1,5 @@
1
- import type { UIMessage } from "ai";
2
- import type { ContextConfig } from "./types.ts";
1
+ import type { ChatMessage } from "../../types";
2
+ import type { ContextConfig } from "./types";
3
3
  type SummarizationModelConfig = NonNullable<ContextConfig["summarizationModel"]>;
4
- export declare function summarizeMessages(messages: UIMessage[], existingSummary: string | null, modelConfig: SummarizationModelConfig): Promise<string>;
4
+ export declare function summarizeMessages(messages: ChatMessage[], existingSummary: string | null, modelConfig: SummarizationModelConfig): Promise<string>;
5
5
  export {};
@@ -1,4 +1,4 @@
1
- import type { UIMessage } from "ai";
1
+ import type { ChatMessage } from "../../types";
2
2
  /** Average characters per token for English text. Used by the heuristic estimator. */
3
3
  export declare const CHARS_PER_TOKEN = 4;
4
4
  /**
@@ -6,15 +6,12 @@ export declare const CHARS_PER_TOKEN = 4;
6
6
  * ~10% accuracy for English text — good enough for budget decisions.
7
7
  */
8
8
  export declare function estimateTokens(text: string): number;
9
+ export declare function estimateMessageTokens(message: ChatMessage): number;
9
10
  /**
10
- * Estimates token count for a single UIMessage by walking its parts.
11
- */
12
- export declare function estimateMessageTokens(message: UIMessage): number;
13
- /**
14
- * Estimates token counts for an array of UIMessages.
11
+ * Estimates token counts for an array of messages.
15
12
  * Returns per-message estimates in the same order.
16
13
  */
17
- export declare function estimateMessagesTokens(messages: UIMessage[]): {
18
- message: UIMessage<unknown, import("ai").UIDataTypes, import("ai").UITools>;
14
+ export declare function estimateMessagesTokens(messages: ChatMessage[]): {
15
+ message: ChatMessage;
19
16
  tokens: number;
20
17
  }[];
@@ -1,2 +1,2 @@
1
- import type { ResolvedCortexAgentConfig } from "../config.ts";
1
+ import type { ResolvedCortexAgentConfig } from "../config";
2
2
  export declare function fetchBackend(path: string, backendFetch: NonNullable<ResolvedCortexAgentConfig["backendFetch"]>, token: string, options?: RequestInit): Promise<Response>;
@@ -0,0 +1,23 @@
1
+ import type { ResolvedCortexAgentConfig } from "../config";
2
+ import type { ChatMessage, Thread } from "../types";
3
+ import type { CapturedStep } from "./inspector";
4
+ type FinishTurnOptions = {
5
+ /** What this run produced — the only messages the turn writes. */
6
+ messages: ChatMessage[];
7
+ /** The thread including them, which is what a summary has to be judged against. */
8
+ threadMessages: ChatMessage[];
9
+ isAborted: boolean;
10
+ assistantMessageId: string | undefined;
11
+ thread: Thread;
12
+ userId: string;
13
+ capturedSteps: CapturedStep[];
14
+ config: ResolvedCortexAgentConfig;
15
+ };
16
+ /**
17
+ * Persists everything a completed turn produced, then tells the client to refetch.
18
+ *
19
+ * The thread is re-read first: it may have been deleted mid-stream, in which case
20
+ * there is nothing to write to and the whole turn is discarded.
21
+ */
22
+ export declare function finishTurn(options: FinishTurnOptions): Promise<void>;
23
+ export {};
@@ -1,5 +1,38 @@
1
- import type { ResolvedCortexAgentConfig } from "../config.ts";
2
- export declare function createModel(config: ResolvedCortexAgentConfig["model"]): import("@ai-sdk/provider").LanguageModelV3;
3
- export declare function createEmbeddingModel(config: ResolvedCortexAgentConfig["embedding"]): import("@ai-sdk/provider").EmbeddingModelV3;
1
+ import { OpenAICompatibleChatAdapter } from "@tanstack/ai-openai/compatible";
2
+ /** Everything cortex needs to reach one OpenAI-compatible chat endpoint. */
3
+ export type ProviderConfig = {
4
+ baseURL: string;
5
+ apiKey: string;
6
+ modelName: string;
7
+ providerName?: string;
8
+ };
9
+ /**
10
+ * `openaiCompatible()` drops streamed reasoning: its `extractReasoning` hook is
11
+ * a no-op and nothing shipped overrides it. Cortex renders thinking parts, so it
12
+ * takes the sanctioned subclass seam and reads the `reasoning_content` delta.
13
+ */
14
+ declare class ReasoningChatAdapter extends OpenAICompatibleChatAdapter<string> {
15
+ protected extractReasoning(chunk: unknown): {
16
+ text: string;
17
+ } | undefined;
18
+ }
19
+ /**
20
+ * `fetch` is how the caller observes or rewrites the raw HTTP exchange — the LLM
21
+ * inspector captures through it, the vision model adapts `max_tokens` through it.
22
+ */
23
+ export declare function createModel(config: ProviderConfig, options?: {
24
+ name?: string;
25
+ fetch?: typeof globalThis.fetch;
26
+ }): ReasoningChatAdapter;
27
+ /** Vision calls cap output tokens, so they need the max_tokens parameter shim. */
28
+ export declare function createVisionModel(config: ProviderConfig): ReasoningChatAdapter;
4
29
  export declare function streamToBase64(stream: ReadableStream<Uint8Array>): Promise<string>;
5
- export declare function tokenToUserId(token: string): string;
30
+ /**
31
+ * OpenAI's newer models reject `max_tokens` in favor of `max_completion_tokens`,
32
+ * while most OpenAI-compatible gateways only accept `max_tokens`. Retry once on
33
+ * that specific rejection and remember the answer for this fetch's lifetime.
34
+ */
35
+ export declare function createMaxTokensAdaptingFetch(): ((input: string | URL | Request, init?: RequestInit) => Promise<Response>) & {
36
+ preconnect: typeof fetch.preconnect;
37
+ };
38
+ export {};
@@ -1,4 +1,7 @@
1
- import type { ResolvedCortexAgentConfig } from "../config.ts";
2
- import type { Thread } from "../types.ts";
3
- export declare function stream(messages: unknown[], thread: Thread, userId: string, token: string, requestContext: Record<string, unknown>, config: ResolvedCortexAgentConfig): Promise<Response>;
1
+ import { chatParamsFromRequest } from "@tanstack/ai";
2
+ import type { ResolvedCortexAgentConfig } from "../config";
3
+ import type { Thread } from "../types";
4
+ /** The AG-UI request body, as the route parsed it. */
5
+ export type TurnParams = Awaited<ReturnType<typeof chatParamsFromRequest>>;
6
+ export declare function startTurn(params: TurnParams, thread: Thread, userId: string, token: string, requestContext: Record<string, unknown>, config: ResolvedCortexAgentConfig): Promise<Response | null>;
4
7
  export declare function generateTitle(threadId: string, prompt: string, userId: string, config: ResolvedCortexAgentConfig): Promise<void>;
@@ -0,0 +1,41 @@
1
+ import type { ChatMiddleware, TokenUsage as ProviderTokenUsage } from "@tanstack/ai";
2
+ import type { TokenUsage } from "../types";
3
+ /** One model call's raw exchange, as the LLM request inspector renders it. */
4
+ export type CapturedStep = {
5
+ prompt: string;
6
+ output: string | null;
7
+ tokenUsage: TokenUsage | null;
8
+ };
9
+ /**
10
+ * Watches one turn's model calls. The SDK's `debug` logger reports call metadata
11
+ * but never raw bodies, so the raw exchange is captured where it actually
12
+ * exists — on the HTTP client — while usage arrives through middleware.
13
+ */
14
+ export declare function createInspector(): {
15
+ steps: CapturedStep[];
16
+ middleware: ChatMiddleware<unknown>;
17
+ fetch: ((input: string | URL | Request, init?: RequestInit) => Promise<Response>) & {
18
+ preconnect: typeof fetch.preconnect;
19
+ };
20
+ readonly modelId: string;
21
+ readonly tokenUsage: TokenUsage | undefined;
22
+ };
23
+ /**
24
+ * Flattens the provider's usage shape into ours. The provider reports cached and
25
+ * cache-written prompt tokens but no uncached counter, so that dimension is the
26
+ * remainder — which is what makes the client's breakdown add up to the total.
27
+ */
28
+ export declare function toTokenUsage(usage: ProviderTokenUsage): {
29
+ input: {
30
+ noCache: number;
31
+ cacheRead: number;
32
+ cacheWrite: number;
33
+ total: number;
34
+ };
35
+ output: {
36
+ reasoning: number;
37
+ text: number;
38
+ total: number;
39
+ };
40
+ total: number;
41
+ };
@@ -1,5 +1,5 @@
1
- import type { DatabaseAdapter } from "../../adapters/database.ts";
2
- import type { StorageAdapter } from "../../adapters/storage.ts";
1
+ import type { DatabaseAdapter } from "../../adapters/database/index";
2
+ import type { StorageAdapter } from "../../adapters/storage/index";
3
3
  export type ResolvedFile = {
4
4
  name: string;
5
5
  bytes: string;
@@ -7,6 +7,7 @@ export type ResolvedFile = {
7
7
  export type RequestInterceptorOptions = {
8
8
  transformFile?: (file: ResolvedFile) => unknown;
9
9
  };
10
- export declare function createRequestInterceptor(db: DatabaseAdapter, storage: StorageAdapter, options?: RequestInterceptorOptions): (body: Record<string, unknown>, context: {
11
- token: string;
12
- }) => Promise<Record<string, unknown>>;
10
+ export declare function createRequestInterceptor(db: DatabaseAdapter, storage: StorageAdapter, options: RequestInterceptorOptions & {
11
+ threadId: string;
12
+ userId: string;
13
+ }): (body: Record<string, unknown>) => Promise<Record<string, unknown>>;
@@ -1,9 +1,10 @@
1
- import type { ResolvedContext } from "../graph/resolver.ts";
2
- import type { PromptContext, ResolvedCortexAgentConfig } from "../config.ts";
3
- import type { Thread } from "../types.ts";
1
+ import type { ResolvedContext } from "../graph/resolver";
2
+ import type { PromptContext, ResolvedCortexAgentConfig } from "../config";
3
+ import type { Thread } from "../types";
4
+ import type { CcPromptInput } from "../cc/format";
4
5
  /**
5
6
  * Resolves session data for the thread, loading from the configured
6
7
  * session loader if not already cached on the thread.
7
8
  */
8
9
  export declare function resolveSession(config: ResolvedCortexAgentConfig, thread: Thread, token: string): Promise<Record<string, unknown> | null>;
9
- export declare function buildSystemPrompt(config: ResolvedCortexAgentConfig, resolved: ResolvedContext | null, promptContext: PromptContext): Promise<string>;
10
+ export declare function buildSystemPrompt(config: ResolvedCortexAgentConfig, resolved: ResolvedContext | null, promptContext: PromptContext, cc?: CcPromptInput, attachmentListing?: string): Promise<string>;
@@ -0,0 +1,41 @@
1
+ import type { RedisConnections } from "../redis";
2
+ import type { ActiveRun } from "./active-runs";
3
+ import { offsetBelongsToRun } from "./redis-stream-log";
4
+ type RedisRunOptions = {
5
+ streamTtlSeconds?: number;
6
+ };
7
+ export declare function createRedisRuns(connections: RedisConnections, options?: RedisRunOptions): {
8
+ startRun(threadId: string): Promise<ActiveRun>;
9
+ getRunId(threadId: string): Promise<string | undefined>;
10
+ runningThreadIds(threadIds: string[]): Promise<Set<string>>;
11
+ abortRun: (threadId: string) => Promise<boolean>;
12
+ endRun(threadId: string, runId: string): Promise<void>;
13
+ producerLog(runId: string): {
14
+ resumeFrom: () => string | null;
15
+ append: (chunks: import("@tanstack/ai").AGUIEvent[]) => Promise<string[]>;
16
+ snapshot: () => Promise<{
17
+ offset: string;
18
+ chunk: import("@tanstack/ai").StreamChunk;
19
+ }[]>;
20
+ close: () => Promise<void>;
21
+ read: (offset: string, signal?: AbortSignal) => AsyncGenerator<{
22
+ offset: string;
23
+ chunk: import("@tanstack/ai").StreamChunk;
24
+ }, void, any>;
25
+ };
26
+ joinLog(threadId: string, runId: string, offset?: string | undefined): {
27
+ resumeFrom: () => string | null;
28
+ append: (chunks: import("@tanstack/ai").AGUIEvent[]) => Promise<string[]>;
29
+ snapshot: () => Promise<{
30
+ offset: string;
31
+ chunk: import("@tanstack/ai").StreamChunk;
32
+ }[]>;
33
+ close: () => Promise<void>;
34
+ read: (offset: string, signal?: AbortSignal) => AsyncGenerator<{
35
+ offset: string;
36
+ chunk: import("@tanstack/ai").StreamChunk;
37
+ }, void, any>;
38
+ };
39
+ offsetBelongsToRun: typeof offsetBelongsToRun;
40
+ };
41
+ export {};