@m6d/cortex-server 1.6.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/src/{adapters → lib/adapters}/database.d.ts +16 -1
  3. package/dist/src/lib/ai/context/compressor.d.ts +18 -0
  4. package/dist/src/{ai → lib/ai}/context/index.d.ts +2 -1
  5. package/dist/src/lib/ai/context/intra-turn-compressor.d.ts +24 -0
  6. package/dist/src/{ai → lib/ai}/context/types.d.ts +2 -0
  7. package/dist/src/lib/config.d.ts +153 -0
  8. package/dist/src/{db → lib/db}/schema.d.ts +104 -1
  9. package/dist/src/{index.d.ts → lib/index.d.ts} +2 -2
  10. package/dist/src/{types.d.ts → lib/types.d.ts} +15 -14
  11. package/index.ts +1 -1
  12. package/package.json +8 -3
  13. package/src/{adapters → lib/adapters}/database.ts +20 -1
  14. package/src/{adapters → lib/adapters}/minio.ts +2 -1
  15. package/src/{adapters → lib/adapters}/mssql.ts +38 -2
  16. package/src/lib/ai/context/compressor.ts +259 -0
  17. package/src/{ai → lib/ai}/context/index.ts +6 -1
  18. package/src/lib/ai/context/intra-turn-compressor.ts +264 -0
  19. package/src/{ai → lib/ai}/context/types.ts +4 -1
  20. package/src/{ai → lib/ai}/index.ts +114 -13
  21. package/src/lib/ai/prompt.ts +354 -0
  22. package/src/{ai → lib/ai}/tools/execute-code.tool.ts +5 -2
  23. package/src/{auth → lib/auth}/middleware.ts +7 -0
  24. package/src/lib/config.ts +181 -0
  25. package/src/{db/migrations/20260309012148_cloudy_maria_hill → lib/db/migrations/20260326231647_nice_speedball}/migration.sql +12 -0
  26. package/src/{db/migrations/20260309012148_cloudy_maria_hill → lib/db/migrations/20260326231647_nice_speedball}/snapshot.json +106 -1
  27. package/src/{db → lib/db}/schema.ts +15 -2
  28. package/src/{factory.ts → lib/factory.ts} +1 -0
  29. package/src/{index.ts → lib/index.ts} +3 -1
  30. package/src/{routes → lib/routes}/files.ts +9 -2
  31. package/src/{routes → lib/routes}/threads.ts +8 -1
  32. package/src/{types.ts → lib/types.ts} +16 -15
  33. package/src/sample/db/client.ts +9 -0
  34. package/src/sample/db/migrations/20260411023125_rich_purple_man/migration.sql +5 -0
  35. package/src/sample/db/migrations/20260411023125_rich_purple_man/snapshot.json +50 -0
  36. package/src/sample/db/schema.ts +10 -0
  37. package/src/sample/domains/account/concepts/session.concept.ts +17 -0
  38. package/src/sample/domains/account/endpoints/listCurrentSessions.endpoint.ts +31 -0
  39. package/src/sample/domains/account/endpoints/revokeAllOtherSessions.endpoint.ts +22 -0
  40. package/src/sample/domains/account/endpoints/revokeCurrentSession.endpoint.ts +33 -0
  41. package/src/sample/domains/account/index.ts +18 -0
  42. package/src/sample/domains/appraisals/concepts/appraisalCycle.concept.ts +15 -0
  43. package/src/sample/domains/appraisals/concepts/appraisalRecord.concept.ts +20 -0
  44. package/src/sample/domains/appraisals/concepts/appraisalRecordCompetency.concept.ts +10 -0
  45. package/src/sample/domains/appraisals/concepts/appraisalRecordFunctionalRequirement.concept.ts +10 -0
  46. package/src/sample/domains/appraisals/concepts/appraisalRecordGoal.concept.ts +17 -0
  47. package/src/sample/domains/appraisals/endpoints/getAppraisalRecordById.endpoint.ts +321 -0
  48. package/src/sample/domains/appraisals/endpoints/getAppraisalRecordCompetencies.endpoint.ts +120 -0
  49. package/src/sample/domains/appraisals/endpoints/getAppraisalRecordFunctionalRequirements.endpoint.ts +126 -0
  50. package/src/sample/domains/appraisals/endpoints/getAppraisalRecordGoals.endpoint.ts +104 -0
  51. package/src/sample/domains/appraisals/endpoints/getAppraisalRecordScore.endpoint.ts +58 -0
  52. package/src/sample/domains/appraisals/endpoints/listAppraisalCyclesSimple.endpoint.ts +52 -0
  53. package/src/sample/domains/appraisals/endpoints/listAppraisalRecords.endpoint.ts +245 -0
  54. package/src/sample/domains/appraisals/endpoints/listAppraisalTemplatesSimple.endpoint.ts +52 -0
  55. package/src/sample/domains/appraisals/index.ts +40 -0
  56. package/src/sample/domains/appraisals/rules/appraisalRecordScoping.rule.ts +7 -0
  57. package/src/sample/domains/attendance/concepts/attendancePermission.concept.ts +17 -0
  58. package/src/sample/domains/attendance/concepts/attendanceTransaction.concept.ts +17 -0
  59. package/src/sample/domains/attendance/concepts/publicHoliday.concept.ts +10 -0
  60. package/src/sample/domains/attendance/concepts/punch.concept.ts +19 -0
  61. package/src/sample/domains/attendance/endpoints/getAttendanceTransactionById.endpoint.ts +444 -0
  62. package/src/sample/domains/attendance/endpoints/getCurrentAttendanceProfile.endpoint.ts +886 -0
  63. package/src/sample/domains/attendance/endpoints/getCurrentAttendanceStatistics.endpoint.ts +49 -0
  64. package/src/sample/domains/attendance/endpoints/listAttendancePermissions.endpoint.ts +176 -0
  65. package/src/sample/domains/attendance/endpoints/listAttendanceTransactionStates.endpoint.ts +26 -0
  66. package/src/sample/domains/attendance/endpoints/listAttendanceTransactions.endpoint.ts +373 -0
  67. package/src/sample/domains/attendance/endpoints/listPublicHolidaysSimple.endpoint.ts +52 -0
  68. package/src/sample/domains/attendance/endpoints/listPunchTypes.endpoint.ts +25 -0
  69. package/src/sample/domains/attendance/endpoints/listPunches.endpoint.ts +178 -0
  70. package/src/sample/domains/attendance/index.ts +41 -0
  71. package/src/sample/domains/attendance/services/attendancePermissions.service.ts +15 -0
  72. package/src/sample/domains/employees/concepts/employee.concept.ts +20 -0
  73. package/src/sample/domains/employees/concepts/employeeBankAccount.concept.ts +19 -0
  74. package/src/sample/domains/employees/concepts/employeeChild.concept.ts +19 -0
  75. package/src/sample/domains/employees/concepts/employeeDocument.concept.ts +21 -0
  76. package/src/sample/domains/employees/concepts/employeeEvent.concept.ts +21 -0
  77. package/src/sample/domains/employees/concepts/employeeExperience.concept.ts +18 -0
  78. package/src/sample/domains/employees/concepts/employeeJobLevelChange.concept.ts +21 -0
  79. package/src/sample/domains/employees/concepts/employeeMedal.concept.ts +20 -0
  80. package/src/sample/domains/employees/concepts/employeeQualification.concept.ts +20 -0
  81. package/src/sample/domains/employees/concepts/employeeSpouse.concept.ts +21 -0
  82. package/src/sample/domains/employees/concepts/employeeViolation.concept.ts +19 -0
  83. package/src/sample/domains/employees/endpoints/getCurrentEmployee.endpoint.ts +1651 -0
  84. package/src/sample/domains/employees/endpoints/getCurrentIdentity.endpoint.ts +197 -0
  85. package/src/sample/domains/employees/endpoints/getCurrentManagers.endpoint.ts +142 -0
  86. package/src/sample/domains/employees/endpoints/getEmployeeById.endpoint.ts +1659 -0
  87. package/src/sample/domains/employees/endpoints/getEmployeeStatistics.endpoint.ts +43 -0
  88. package/src/sample/domains/employees/endpoints/listBankAccounts.endpoint.ts +223 -0
  89. package/src/sample/domains/employees/endpoints/listChildren.endpoint.ts +211 -0
  90. package/src/sample/domains/employees/endpoints/listDocuments.endpoint.ts +222 -0
  91. package/src/sample/domains/employees/endpoints/listEmployeesSimple.endpoint.ts +156 -0
  92. package/src/sample/domains/employees/endpoints/listEvents.endpoint.ts +120 -0
  93. package/src/sample/domains/employees/endpoints/listExperiences.endpoint.ts +188 -0
  94. package/src/sample/domains/employees/endpoints/listJobLevelChanges.endpoint.ts +240 -0
  95. package/src/sample/domains/employees/endpoints/listMedals.endpoint.ts +266 -0
  96. package/src/sample/domains/employees/endpoints/listQualifications.endpoint.ts +265 -0
  97. package/src/sample/domains/employees/endpoints/listSpouses.endpoint.ts +278 -0
  98. package/src/sample/domains/employees/endpoints/listViolations.endpoint.ts +245 -0
  99. package/src/sample/domains/employees/index.ts +75 -0
  100. package/src/sample/domains/employees/services/employees.service.ts +181 -0
  101. package/src/sample/domains/index.ts +10 -0
  102. package/src/sample/domains/leaves/concepts/leave.concept.ts +21 -0
  103. package/src/sample/domains/leaves/concepts/leaveBalance.concept.ts +17 -0
  104. package/src/sample/domains/leaves/concepts/leaveBalanceTransaction.concept.ts +16 -0
  105. package/src/sample/domains/leaves/concepts/leaveType.concept.ts +13 -0
  106. package/src/sample/domains/leaves/concepts/leaveTypes.concept.ts +205 -0
  107. package/src/sample/domains/leaves/endpoints/getBalance.endpoint.ts +53 -0
  108. package/src/sample/domains/leaves/endpoints/getLeaveById.endpoint.ts +53 -0
  109. package/src/sample/domains/leaves/endpoints/listBalanceTransactions.endpoint.ts +196 -0
  110. package/src/sample/domains/leaves/endpoints/listBalanceTypes.endpoint.ts +26 -0
  111. package/src/sample/domains/leaves/endpoints/listBalances.endpoint.ts +201 -0
  112. package/src/sample/domains/leaves/endpoints/listLeaveTypes.endpoint.ts +28 -0
  113. package/src/sample/domains/leaves/endpoints/listLeaves.endpoint.ts +234 -0
  114. package/src/sample/domains/leaves/index.ts +38 -0
  115. package/src/sample/domains/leaves/services/leaveRequests.service.ts +232 -0
  116. package/src/sample/domains/notifications/concepts/notification.concept.ts +19 -0
  117. package/src/sample/domains/notifications/endpoints/countMyNotifications.endpoint.ts +21 -0
  118. package/src/sample/domains/notifications/endpoints/getMyNotification.endpoint.ts +57 -0
  119. package/src/sample/domains/notifications/endpoints/listMyNotifications.endpoint.ts +59 -0
  120. package/src/sample/domains/notifications/endpoints/markMyNotificationAsRead.endpoint.ts +32 -0
  121. package/src/sample/domains/notifications/index.ts +20 -0
  122. package/src/sample/domains/payroll/concepts/payslip.concept.ts +18 -0
  123. package/src/sample/domains/payroll/concepts/salaryCertificate.concept.ts +17 -0
  124. package/src/sample/domains/payroll/concepts/salaryCertificateRequestingEntity.concept.ts +8 -0
  125. package/src/sample/domains/payroll/endpoints/getPayslipById.endpoint.ts +238 -0
  126. package/src/sample/domains/payroll/endpoints/listPayslips.endpoint.ts +216 -0
  127. package/src/sample/domains/payroll/endpoints/listSalaryCertificateLanguages.endpoint.ts +25 -0
  128. package/src/sample/domains/payroll/endpoints/listSalaryCertificateRequestingEntities.endpoint.ts +62 -0
  129. package/src/sample/domains/payroll/endpoints/listSalaryCertificateTypes.endpoint.ts +24 -0
  130. package/src/sample/domains/payroll/endpoints/listSalaryCertificates.endpoint.ts +122 -0
  131. package/src/sample/domains/payroll/endpoints/previewSalaryCertificate.endpoint.ts +45 -0
  132. package/src/sample/domains/payroll/index.ts +32 -0
  133. package/src/sample/domains/payroll/rules/payrollEmployeeContext.rule.ts +7 -0
  134. package/src/sample/domains/payroll/services/salaryCertificates.service.ts +15 -0
  135. package/src/sample/domains/servicing/concepts/service.concept.ts +6 -0
  136. package/src/sample/domains/servicing/concepts/serviceRequest.concept.ts +12 -0
  137. package/src/sample/domains/servicing/concepts/serviceRequestApproval.concept.ts +9 -0
  138. package/src/sample/domains/servicing/endpoints/cancelServiceRequest.endpoint.ts +21 -0
  139. package/src/sample/domains/servicing/endpoints/createServiceRequest.endpoint.ts +511 -0
  140. package/src/sample/domains/servicing/endpoints/getServiceRequest.endpoint.ts +352 -0
  141. package/src/sample/domains/servicing/endpoints/getServiceRequestFormItems.endpoint.ts +219 -0
  142. package/src/sample/domains/servicing/endpoints/getServiceRequestTransactionFormItems.endpoint.ts +216 -0
  143. package/src/sample/domains/servicing/endpoints/getServiceStates.endpoint.ts +47 -0
  144. package/src/sample/domains/servicing/endpoints/invokeServiceRequestAction.endpoint.ts +139 -0
  145. package/src/sample/domains/servicing/endpoints/listServiceRequests.endpoint.ts +292 -0
  146. package/src/sample/domains/servicing/endpoints/listServices.endpoint.ts +108 -0
  147. package/src/sample/domains/servicing/endpoints/updateServiceRequest.endpoint.ts +355 -0
  148. package/src/sample/domains/servicing/index.ts +44 -0
  149. package/src/sample/domains/servicing/rules/checkValidActions.rule.ts +7 -0
  150. package/src/sample/domains/servicing/rules/createServiceRequest.rule.ts +7 -0
  151. package/src/sample/domains/servicing/rules/filterServiceRequestsByState.rule.ts +7 -0
  152. package/src/sample/domains/servicing/rules/passingOptionFields.rule.ts +7 -0
  153. package/src/sample/domains/shared/rules/pagination.rule.ts +7 -0
  154. package/src/sample/domains/suggestions/concepts/suggestion.concept.ts +19 -0
  155. package/src/sample/domains/suggestions/concepts/suggestionCategory.concept.ts +7 -0
  156. package/src/sample/domains/suggestions/concepts/suggestionImpactLevel.concept.ts +7 -0
  157. package/src/sample/domains/suggestions/endpoints/createSuggestion.endpoint.ts +705 -0
  158. package/src/sample/domains/suggestions/endpoints/deleteSuggestion.endpoint.ts +32 -0
  159. package/src/sample/domains/suggestions/endpoints/getSuggestionById.endpoint.ts +635 -0
  160. package/src/sample/domains/suggestions/endpoints/listSuggestionCategories.endpoint.ts +62 -0
  161. package/src/sample/domains/suggestions/endpoints/listSuggestionImpactLevels.endpoint.ts +62 -0
  162. package/src/sample/domains/suggestions/endpoints/listSuggestionStates.endpoint.ts +24 -0
  163. package/src/sample/domains/suggestions/endpoints/listSuggestions.endpoint.ts +132 -0
  164. package/src/sample/domains/suggestions/endpoints/updateSuggestion.endpoint.ts +690 -0
  165. package/src/sample/domains/suggestions/endpoints/updateSuggestionState.endpoint.ts +39 -0
  166. package/src/sample/domains/suggestions/index.ts +34 -0
  167. package/src/sample/domains/suggestions/rules/suggestionScope.rule.ts +7 -0
  168. package/src/sample/domains/surveys/concepts/survey.concept.ts +10 -0
  169. package/src/sample/domains/surveys/concepts/surveyResponse.concept.ts +14 -0
  170. package/src/sample/domains/surveys/endpoints/getSurveyResponseById.endpoint.ts +131 -0
  171. package/src/sample/domains/surveys/endpoints/getTargetedSurvey.endpoint.ts +129 -0
  172. package/src/sample/domains/surveys/endpoints/listTargetedSurveys.endpoint.ts +160 -0
  173. package/src/sample/domains/surveys/endpoints/respondToSurvey.endpoint.ts +144 -0
  174. package/src/sample/domains/surveys/index.ts +21 -0
  175. package/src/sample/drizzle.config.ts +11 -0
  176. package/src/sample/index.bak.ts +341 -0
  177. package/src/sample/index.ts +318 -0
  178. package/src/sample/official-statements/defaults.ts +57 -0
  179. package/src/sample/official-statements/routes.ts +137 -0
  180. package/src/sample/official-statements/service.ts +148 -0
  181. package/src/sample/official-statements/types.ts +23 -0
  182. package/dist/src/ai/context/compressor.d.ts +0 -7
  183. package/dist/src/ai/tools/call-endpoint.tool.d.ts +0 -7
  184. package/dist/src/config.d.ts +0 -159
  185. package/src/ai/context/compressor.ts +0 -47
  186. package/src/ai/prompt.ts +0 -126
  187. package/src/ai/tools/call-endpoint.tool.ts +0 -89
  188. package/src/config.ts +0 -164
  189. package/src/db/migrations/20260315000000_add_context_meta/migration.sql +0 -1
  190. package/dist/src/{adapters → lib/adapters}/minio.d.ts +0 -0
  191. package/dist/src/{adapters → lib/adapters}/mssql.d.ts +0 -0
  192. package/dist/src/{adapters → lib/adapters}/storage.d.ts +0 -0
  193. package/dist/src/{ai → lib/ai}/active-streams.d.ts +0 -0
  194. package/dist/src/{ai → lib/ai}/context/builder.d.ts +0 -0
  195. package/dist/src/{ai → lib/ai}/context/summarizer.d.ts +0 -0
  196. package/dist/src/{ai → lib/ai}/context/token-estimator.d.ts +0 -0
  197. package/dist/src/{ai → lib/ai}/fetch.d.ts +0 -0
  198. package/dist/src/{ai → lib/ai}/helpers.d.ts +0 -0
  199. package/dist/src/{ai → lib/ai}/index.d.ts +0 -0
  200. package/dist/src/{ai → lib/ai}/interceptors/request-interceptor.d.ts +0 -0
  201. package/dist/src/{ai → lib/ai}/prompt.d.ts +0 -0
  202. package/dist/src/{ai → lib/ai}/tools/capture-files.tool.d.ts +0 -0
  203. package/dist/src/{ai → lib/ai}/tools/execute-code.tool.d.ts +0 -0
  204. package/dist/src/{ai → lib/ai}/tools/query-graph.tool.d.ts +0 -0
  205. package/dist/src/{auth → lib/auth}/middleware.d.ts +0 -0
  206. package/dist/src/{cli → lib/cli}/extract-endpoints.d.ts +0 -0
  207. package/dist/src/{db → lib/db}/migrate.d.ts +0 -0
  208. package/dist/src/{factory.d.ts → lib/factory.d.ts} +0 -0
  209. package/dist/src/{graph → lib/graph}/expand-domains.d.ts +0 -0
  210. package/dist/src/{graph → lib/graph}/generate-cypher.d.ts +0 -0
  211. package/dist/src/{graph → lib/graph}/helpers.d.ts +2 -2
  212. /package/dist/src/{graph → lib/graph}/index.d.ts +0 -0
  213. /package/dist/src/{graph → lib/graph}/neo4j.d.ts +0 -0
  214. /package/dist/src/{graph → lib/graph}/resolver.d.ts +0 -0
  215. /package/dist/src/{graph → lib/graph}/seed.d.ts +0 -0
  216. /package/dist/src/{graph → lib/graph}/types.d.ts +0 -0
  217. /package/dist/src/{graph → lib/graph}/validate.d.ts +0 -0
  218. /package/dist/src/{routes → lib/routes}/chat.d.ts +0 -0
  219. /package/dist/src/{routes → lib/routes}/files.d.ts +0 -0
  220. /package/dist/src/{routes → lib/routes}/index.d.ts +0 -0
  221. /package/dist/src/{routes → lib/routes}/threads.d.ts +0 -0
  222. /package/dist/src/{routes → lib/routes}/ws.d.ts +0 -0
  223. /package/dist/src/{ws → lib/ws}/connections.d.ts +0 -0
  224. /package/dist/src/{ws → lib/ws}/events.d.ts +0 -0
  225. /package/dist/src/{ws → lib/ws}/index.d.ts +0 -0
  226. /package/dist/src/{ws → lib/ws}/notify.d.ts +0 -0
  227. /package/src/{adapters → lib/adapters}/storage.ts +0 -0
  228. /package/src/{ai → lib/ai}/active-streams.ts +0 -0
  229. /package/src/{ai → lib/ai}/context/builder.ts +0 -0
  230. /package/src/{ai → lib/ai}/context/summarizer.ts +0 -0
  231. /package/src/{ai → lib/ai}/context/token-estimator.ts +0 -0
  232. /package/src/{ai → lib/ai}/fetch.ts +0 -0
  233. /package/src/{ai → lib/ai}/helpers.ts +0 -0
  234. /package/src/{ai → lib/ai}/interceptors/request-interceptor.ts +0 -0
  235. /package/src/{ai → lib/ai}/tools/capture-files.tool.ts +0 -0
  236. /package/src/{ai → lib/ai}/tools/query-graph.tool.ts +0 -0
  237. /package/src/{cli → lib/cli}/extract-endpoints.ts +0 -0
  238. /package/src/{db → lib/db}/migrate.ts +0 -0
  239. /package/src/{graph → lib/graph}/expand-domains.ts +0 -0
  240. /package/src/{graph → lib/graph}/generate-cypher.ts +0 -0
  241. /package/src/{graph → lib/graph}/helpers.ts +0 -0
  242. /package/src/{graph → lib/graph}/index.ts +0 -0
  243. /package/src/{graph → lib/graph}/neo4j.ts +0 -0
  244. /package/src/{graph → lib/graph}/resolver.ts +0 -0
  245. /package/src/{graph → lib/graph}/seed.ts +0 -0
  246. /package/src/{graph → lib/graph}/types.ts +0 -0
  247. /package/src/{graph → lib/graph}/validate.ts +0 -0
  248. /package/src/{routes → lib/routes}/chat.ts +0 -0
  249. /package/src/{routes → lib/routes}/index.ts +0 -0
  250. /package/src/{routes → lib/routes}/ws.ts +0 -0
  251. /package/src/{ws → lib/ws}/connections.ts +0 -0
  252. /package/src/{ws → lib/ws}/events.ts +0 -0
  253. /package/src/{ws → lib/ws}/index.ts +0 -0
  254. /package/src/{ws → lib/ws}/notify.ts +0 -0
@@ -0,0 +1,181 @@
1
+ import type { Tool, ToolSet, UIMessage } from "ai";
2
+ import type { DatabaseAdapter } from "./adapters/database";
3
+ import type { StorageAdapter } from "./adapters/storage";
4
+ import type { DomainDef } from "./graph/types.ts";
5
+ import type { RequestInterceptorOptions } from "./ai/interceptors/request-interceptor.ts";
6
+ import type { ContextConfig } from "./ai/context/types.ts";
7
+ import type { Thread } from "./types.ts";
8
+
9
+ type ModelConfig = {
10
+ baseURL: string;
11
+ apiKey: string;
12
+ modelName: string;
13
+ providerName?: string;
14
+ };
15
+
16
+ type EmbeddingConfig = {
17
+ baseURL: string;
18
+ apiKey: string;
19
+ modelName: string;
20
+ dimension: number;
21
+ };
22
+
23
+ type Neo4jConfig = {
24
+ url: string;
25
+ user: string;
26
+ password: string;
27
+ };
28
+
29
+ type RerankerConfig = {
30
+ url: string;
31
+ apiKey: string;
32
+ };
33
+
34
+ export type KnowledgeConfig = {
35
+ swagger?: { url: string };
36
+ domains?: Record<string, DomainDef>;
37
+ };
38
+
39
+ export type PromptContext<
40
+ TSession extends Record<string, unknown> = Record<string, unknown>,
41
+ TRequestContext extends Record<string, unknown> = Record<string, unknown>,
42
+ > = {
43
+ session: TSession | null;
44
+ requestContext: TRequestContext;
45
+ };
46
+
47
+ /**
48
+ * Per-request context handed to a tools factory. Allows tool implementations to
49
+ * close over the active thread, user, session, and request-level context without
50
+ * reaching for globals or AsyncLocalStorage.
51
+ */
52
+ export type ToolContext<
53
+ TSession extends Record<string, unknown> = Record<string, unknown>,
54
+ TRequestContext extends Record<string, unknown> = Record<string, unknown>,
55
+ > = {
56
+ thread: Thread;
57
+ userId: string;
58
+ token: string;
59
+ session: TSession | null;
60
+ requestContext: TRequestContext;
61
+ };
62
+
63
+ export type ToolSetFactory<
64
+ TSession extends Record<string, unknown> = Record<string, unknown>,
65
+ TRequestContext extends Record<string, unknown> = Record<string, unknown>,
66
+ > = (context: ToolContext<TSession, TRequestContext>) => ToolSet;
67
+
68
+ export type DatabaseConfig = {
69
+ type: "mssql";
70
+ connectionString: string;
71
+ };
72
+
73
+ export type StorageConfig = {
74
+ endPoint: string;
75
+ port: number;
76
+ useSSL: boolean;
77
+ accessKey: string;
78
+ secretKey: string;
79
+ bucketName?: string;
80
+ };
81
+
82
+ export type CortexAgentDefinition<
83
+ TSession extends Record<string, unknown> = Record<string, unknown>,
84
+ TRequestContext extends Record<string, unknown> = Record<string, unknown>,
85
+ > = {
86
+ systemPrompt:
87
+ | string
88
+ | ((context: PromptContext<TSession, TRequestContext>) => string | Promise<string>);
89
+ tools?: ToolSet | ToolSetFactory<TSession, TRequestContext>;
90
+ backendFetch?: {
91
+ baseUrl: string;
92
+ apiKey: string;
93
+ headers?: Record<string, string>;
94
+ transformRequestBody?: (
95
+ body: Record<string, unknown>,
96
+ context: { token: string },
97
+ ) => Promise<Record<string, unknown>>;
98
+ interceptor?: RequestInterceptorOptions;
99
+ };
100
+ loadSessionData?: (token: string) => Promise<TSession>;
101
+ resolveRequestContext?: (request: Request) => TRequestContext | Promise<TRequestContext>;
102
+ onToolCall?: (toolCall: {
103
+ toolName: string;
104
+ toolCallId: string;
105
+ args: Record<string, unknown>;
106
+ }) => void;
107
+ onStreamFinish?: (result: { messages: UIMessage[]; isAborted: boolean }) => void;
108
+ model?: ModelConfig;
109
+ fastModel?: ModelConfig;
110
+ embedding?: EmbeddingConfig;
111
+ neo4j?: Neo4jConfig;
112
+ reranker?: RerankerConfig;
113
+ context?: Partial<ContextConfig>;
114
+ knowledge?: KnowledgeConfig | null;
115
+ };
116
+
117
+ export type ResolvedCortexAgentConfig = {
118
+ db: DatabaseAdapter;
119
+ storage: StorageAdapter;
120
+ model: ModelConfig;
121
+ fastModel?: ModelConfig;
122
+ embedding: EmbeddingConfig;
123
+ neo4j?: Neo4jConfig;
124
+ reranker?: RerankerConfig;
125
+ systemPrompt: string | ((context: PromptContext) => string | Promise<string>);
126
+ tools?: ToolSet | ToolSetFactory;
127
+ backendFetch?: {
128
+ baseUrl: string;
129
+ apiKey: string;
130
+ headers?: Record<string, string>;
131
+ transformRequestBody?: (
132
+ body: Record<string, unknown>,
133
+ context: { token: string },
134
+ ) => Promise<Record<string, unknown>>;
135
+ interceptor?: RequestInterceptorOptions;
136
+ };
137
+ loadSessionData?: (token: string) => Promise<Record<string, unknown>>;
138
+ resolveRequestContext?: (
139
+ request: Request,
140
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>;
141
+ onToolCall?: (toolCall: {
142
+ toolName: string;
143
+ toolCallId: string;
144
+ args: Record<string, unknown>;
145
+ }) => void;
146
+ onStreamFinish?: (result: { messages: UIMessage[]; isAborted: boolean }) => void;
147
+ context: ContextConfig;
148
+ knowledge?: KnowledgeConfig;
149
+ };
150
+
151
+ export type CortexConfig = {
152
+ port?: number;
153
+ database: DatabaseConfig;
154
+ storage: StorageConfig;
155
+ auth?: {
156
+ jwksUri: string;
157
+ issuer: string;
158
+ tokenExtractor?: (req: Request) => string | null;
159
+ cookieName?: string;
160
+ };
161
+ model: ModelConfig;
162
+ fastModel?: ModelConfig;
163
+ embedding: EmbeddingConfig;
164
+ neo4j?: Neo4jConfig;
165
+ reranker?: RerankerConfig;
166
+ context?: Partial<ContextConfig>;
167
+ knowledge?: KnowledgeConfig;
168
+ agents: Record<string, CortexAgentDefinition>;
169
+ };
170
+
171
+ /**
172
+ * Helper to define an agent with full type inference for `systemPrompt` context.
173
+ * The `context.session` type is inferred from `loadSessionData`'s return type,
174
+ * and `context.requestContext` is inferred from `resolveRequestContext`'s return type.
175
+ */
176
+ export function defineAgent<
177
+ TSession extends Record<string, unknown> = Record<string, unknown>,
178
+ TRequestContext extends Record<string, unknown> = Record<string, unknown>,
179
+ >(config: CortexAgentDefinition<TSession, TRequestContext>): CortexAgentDefinition {
180
+ return config as CortexAgentDefinition;
181
+ }
@@ -10,6 +10,16 @@ CREATE TABLE [ai].[captured_files] (
10
10
  CONSTRAINT [captured_files_pkey] PRIMARY KEY([id])
11
11
  );
12
12
  --> statement-breakpoint
13
+ CREATE TABLE [ai].[llm_requests] (
14
+ [id] UNIQUEIDENTIFIER CONSTRAINT [llm_requests_id_default] DEFAULT (NEWID()),
15
+ [message_id] nvarchar(128) NOT NULL,
16
+ [step_number] int NOT NULL,
17
+ [prompt] nvarchar(max) NOT NULL,
18
+ [output] nvarchar(max),
19
+ [token_usage] nvarchar(max),
20
+ CONSTRAINT [llm_requests_pkey] PRIMARY KEY([id])
21
+ );
22
+ --> statement-breakpoint
13
23
  CREATE TABLE [ai].[messages] (
14
24
  [id] nvarchar(128),
15
25
  [thread_id] UNIQUEIDENTIFIER NOT NULL,
@@ -27,10 +37,12 @@ CREATE TABLE [ai].[threads] (
27
37
  [agent_id] nvarchar(128) NOT NULL CONSTRAINT [threads_agent_id_default] DEFAULT ('default'),
28
38
  [title] nvarchar(256),
29
39
  [session] nvarchar(max),
40
+ [context_meta] nvarchar(max),
30
41
  [created_at] datetime2 NOT NULL,
31
42
  [updated_at] datetime2 NOT NULL,
32
43
  CONSTRAINT [threads_pkey] PRIMARY KEY([id])
33
44
  );
34
45
  --> statement-breakpoint
35
46
  ALTER TABLE [ai].[captured_files] ADD CONSTRAINT [captured_files_message_id_messages_id_fk] FOREIGN KEY ([message_id]) REFERENCES [ai].[messages]([id]) ON DELETE CASCADE;--> statement-breakpoint
47
+ ALTER TABLE [ai].[llm_requests] ADD CONSTRAINT [llm_requests_message_id_messages_id_fk] FOREIGN KEY ([message_id]) REFERENCES [ai].[messages]([id]) ON DELETE CASCADE;--> statement-breakpoint
36
48
  ALTER TABLE [ai].[messages] ADD CONSTRAINT [messages_thread_id_threads_id_fk] FOREIGN KEY ([thread_id]) REFERENCES [ai].[threads]([id]) ON DELETE CASCADE;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": "2",
3
3
  "dialect": "mssql",
4
- "id": "d92d3e1a-9613-4d7e-a224-de2dd01b2718",
4
+ "id": "407c2a91-87ca-412e-92c4-1c4d0d3c71b0",
5
5
  "prevIds": ["00000000-0000-0000-0000-000000000000"],
6
6
  "ddl": [
7
7
  {
@@ -13,6 +13,11 @@
13
13
  "entityType": "tables",
14
14
  "schema": "ai"
15
15
  },
16
+ {
17
+ "name": "llm_requests",
18
+ "entityType": "tables",
19
+ "schema": "ai"
20
+ },
16
21
  {
17
22
  "name": "messages",
18
23
  "entityType": "tables",
@@ -83,6 +88,66 @@
83
88
  "entityType": "columns",
84
89
  "table": "captured_files"
85
90
  },
91
+ {
92
+ "type": "UNIQUEIDENTIFIER",
93
+ "notNull": true,
94
+ "generated": null,
95
+ "identity": null,
96
+ "name": "id",
97
+ "schema": "ai",
98
+ "entityType": "columns",
99
+ "table": "llm_requests"
100
+ },
101
+ {
102
+ "type": "nvarchar(128)",
103
+ "notNull": true,
104
+ "generated": null,
105
+ "identity": null,
106
+ "name": "message_id",
107
+ "schema": "ai",
108
+ "entityType": "columns",
109
+ "table": "llm_requests"
110
+ },
111
+ {
112
+ "type": "int",
113
+ "notNull": true,
114
+ "generated": null,
115
+ "identity": null,
116
+ "name": "step_number",
117
+ "schema": "ai",
118
+ "entityType": "columns",
119
+ "table": "llm_requests"
120
+ },
121
+ {
122
+ "type": "nvarchar(max)",
123
+ "notNull": true,
124
+ "generated": null,
125
+ "identity": null,
126
+ "name": "prompt",
127
+ "schema": "ai",
128
+ "entityType": "columns",
129
+ "table": "llm_requests"
130
+ },
131
+ {
132
+ "type": "nvarchar(max)",
133
+ "notNull": false,
134
+ "generated": null,
135
+ "identity": null,
136
+ "name": "output",
137
+ "schema": "ai",
138
+ "entityType": "columns",
139
+ "table": "llm_requests"
140
+ },
141
+ {
142
+ "type": "nvarchar(max)",
143
+ "notNull": false,
144
+ "generated": null,
145
+ "identity": null,
146
+ "name": "token_usage",
147
+ "schema": "ai",
148
+ "entityType": "columns",
149
+ "table": "llm_requests"
150
+ },
86
151
  {
87
152
  "type": "nvarchar(128)",
88
153
  "notNull": true,
@@ -203,6 +268,16 @@
203
268
  "entityType": "columns",
204
269
  "table": "threads"
205
270
  },
271
+ {
272
+ "type": "nvarchar(max)",
273
+ "notNull": false,
274
+ "generated": null,
275
+ "identity": null,
276
+ "name": "context_meta",
277
+ "schema": "ai",
278
+ "entityType": "columns",
279
+ "table": "threads"
280
+ },
206
281
  {
207
282
  "type": "datetime2",
208
283
  "notNull": true,
@@ -236,6 +311,19 @@
236
311
  "table": "captured_files",
237
312
  "schema": "ai"
238
313
  },
314
+ {
315
+ "columns": ["message_id"],
316
+ "nameExplicit": false,
317
+ "schemaTo": "ai",
318
+ "tableTo": "messages",
319
+ "columnsTo": ["id"],
320
+ "onUpdate": "NO ACTION",
321
+ "onDelete": "CASCADE",
322
+ "name": "llm_requests_message_id_messages_id_fk",
323
+ "entityType": "fks",
324
+ "table": "llm_requests",
325
+ "schema": "ai"
326
+ },
239
327
  {
240
328
  "columns": ["thread_id"],
241
329
  "nameExplicit": false,
@@ -257,6 +345,14 @@
257
345
  "schema": "ai",
258
346
  "entityType": "pks"
259
347
  },
348
+ {
349
+ "nameExplicit": false,
350
+ "columns": ["id"],
351
+ "name": "llm_requests_pkey",
352
+ "table": "llm_requests",
353
+ "schema": "ai",
354
+ "entityType": "pks"
355
+ },
260
356
  {
261
357
  "nameExplicit": false,
262
358
  "columns": ["id"],
@@ -282,6 +378,15 @@
282
378
  "schema": "ai",
283
379
  "table": "captured_files"
284
380
  },
381
+ {
382
+ "column": "id",
383
+ "nameExplicit": false,
384
+ "default": "(NEWID())",
385
+ "name": "llm_requests_id_default",
386
+ "entityType": "defaults",
387
+ "schema": "ai",
388
+ "table": "llm_requests"
389
+ },
285
390
  {
286
391
  "column": "id",
287
392
  "nameExplicit": false,
@@ -1,7 +1,7 @@
1
1
  import type { ToolUIPart, UIMessage } from "ai";
2
2
  import { sql } from "drizzle-orm";
3
- import { customType, datetime2, index, mssqlSchema, nvarchar } from "drizzle-orm/mssql-core";
4
- import type { MessageMetadata } from "src/types";
3
+ import { customType, datetime2, index, int, mssqlSchema, nvarchar } from "drizzle-orm/mssql-core";
4
+ import type { MessageMetadata, TokenUsage } from "../types.ts";
5
5
  import type { ThreadContextMeta } from "../ai/context/types.ts";
6
6
 
7
7
  const uniqueIdentifier = customType<{ data: string }>({
@@ -50,6 +50,19 @@ export const messages = aiSchema.table("messages", {
50
50
  ...auditColumns,
51
51
  });
52
52
 
53
+ export const llmRequests = aiSchema.table("llm_requests", {
54
+ id: uniqueIdentifier()
55
+ .default(sql`NEWID()`)
56
+ .primaryKey(),
57
+ messageId: nvarchar({ length: 128 })
58
+ .references(() => messages.id, { onDelete: "cascade" })
59
+ .notNull(),
60
+ stepNumber: int().notNull(),
61
+ prompt: nvarchar({ length: "max" }).notNull(),
62
+ output: nvarchar({ length: "max" }),
63
+ tokenUsage: nvarchar({ length: "max", mode: "json" }).$type<TokenUsage>(),
64
+ });
65
+
53
66
  export const capturedFiles = aiSchema.table(
54
67
  "captured_files",
55
68
  {
@@ -84,6 +84,7 @@ export function createCortex(config: CortexConfig) {
84
84
  db,
85
85
  storage,
86
86
  model: agentDef.model ?? config.model,
87
+ fastModel: agentDef.fastModel ?? config.fastModel,
87
88
  embedding: agentDef.embedding ?? config.embedding,
88
89
  neo4j: agentDef.neo4j ?? config.neo4j,
89
90
  reranker: agentDef.reranker ?? config.reranker,
@@ -6,7 +6,10 @@ export type {
6
6
  DatabaseConfig,
7
7
  StorageConfig,
8
8
  PromptContext,
9
+ ToolContext,
10
+ ToolSetFactory,
9
11
  } from "./config";
12
+ export { defineAgent } from "./config";
10
13
 
11
14
  export type { ContextConfig, ThreadContextMeta } from "./ai/context/types";
12
15
 
@@ -27,7 +30,6 @@ export { createRequestInterceptor } from "./ai/interceptors/request-interceptor"
27
30
  // Tools (consumers may register custom tools or use built-in ones)
28
31
  export { captureFilesTool } from "./ai/tools/capture-files.tool";
29
32
  export { createQueryGraphTool } from "./ai/tools/query-graph.tool";
30
- export { createCallEndpointTool } from "./ai/tools/call-endpoint.tool";
31
33
  export { createExecuteCodeTool } from "./ai/tools/execute-code.tool";
32
34
 
33
35
  // Graph (consumers may use independently)
@@ -86,12 +86,19 @@ export function createFileRoutes() {
86
86
  );
87
87
 
88
88
  // Store file bytes
89
- await Promise.all(
89
+ const uploadResults = await Promise.all(
90
90
  result.map(async (r, i) => {
91
- await config.storage.put(`captured_files/${r.uploadId}`, files[i]!.file.bytes);
91
+ return await config.storage.put(
92
+ `captured_files/${r.uploadId}`,
93
+ files[i]!.file.bytes,
94
+ );
92
95
  }),
93
96
  );
94
97
 
98
+ if (uploadResults.some((x) => !x)) {
99
+ throw new HTTPException(400, { message: "Some or all files failed to upload" });
100
+ }
101
+
95
102
  return c.json(result);
96
103
  },
97
104
  );
@@ -80,10 +80,17 @@ export function createThreadRoutes() {
80
80
  return c.json(messages);
81
81
  });
82
82
 
83
+ app.get("/messages/:messageId/llm-requests", requireAuth, async function (c) {
84
+ const config = c.get("agentConfig");
85
+ const messageId = c.req.param("messageId");
86
+ const requests = await config.db.llmRequests.listByMessageId(messageId);
87
+ return c.json(requests);
88
+ });
89
+
83
90
  app.post(
84
91
  "/threads/:threadId/session",
85
92
  requireAuth,
86
- zValidator("json", z.object({ session: z.record(z.unknown()) })),
93
+ zValidator("json", z.object({ session: z.record(z.string(), z.unknown()) })),
87
94
  async function (c) {
88
95
  const config = c.get("agentConfig");
89
96
  const agentId = c.get("agentId");
@@ -1,4 +1,3 @@
1
- import type { ToolUIPart, UIMessage } from "ai";
2
1
  import type { ResolvedCortexAgentConfig } from "./config";
3
2
  import type { InferSelectModel } from "drizzle-orm";
4
3
  import type { messages, threads } from "./db/schema";
@@ -15,24 +14,26 @@ export type ThreadSummary = {
15
14
  isRunning: boolean;
16
15
  };
17
16
 
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
+ };
31
+
18
32
  export type MessageMetadata = {
19
33
  modelId: string;
20
34
  providerMetadata: unknown;
21
35
  isAborted?: boolean;
22
- tokenUsage?: {
23
- input: {
24
- noCache: number;
25
- cacheRead: number;
26
- cacheWrite: number;
27
- total: number;
28
- };
29
- output: {
30
- reasoning: number;
31
- text: number;
32
- total: number;
33
- };
34
- total: number;
35
- };
36
+ tokenUsage?: TokenUsage;
36
37
  };
37
38
 
38
39
  export type CapturedFileInput = {
@@ -0,0 +1,9 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { drizzle } from "drizzle-orm/bun-sqlite";
3
+ import { resolve } from "path";
4
+ import * as schema from "./schema.ts";
5
+
6
+ const url = process.env["SAMPLE_DB_URL"] ?? resolve(import.meta.dir, "sample.db");
7
+ const client = new Database(url);
8
+
9
+ export const db = drizzle({ client, schema, casing: "snake_case" });
@@ -0,0 +1,5 @@
1
+ CREATE TABLE `official_statements` (
2
+ `id` text PRIMARY KEY,
3
+ `thread_id` text NOT NULL,
4
+ `data` text NOT NULL
5
+ );
@@ -0,0 +1,50 @@
1
+ {
2
+ "version": "7",
3
+ "dialect": "sqlite",
4
+ "id": "d8da372b-c2d6-4299-a062-58550458a12d",
5
+ "prevIds": ["00000000-0000-0000-0000-000000000000"],
6
+ "ddl": [
7
+ {
8
+ "name": "official_statements",
9
+ "entityType": "tables"
10
+ },
11
+ {
12
+ "type": "text",
13
+ "notNull": false,
14
+ "autoincrement": false,
15
+ "default": null,
16
+ "generated": null,
17
+ "name": "id",
18
+ "entityType": "columns",
19
+ "table": "official_statements"
20
+ },
21
+ {
22
+ "type": "text",
23
+ "notNull": true,
24
+ "autoincrement": false,
25
+ "default": null,
26
+ "generated": null,
27
+ "name": "thread_id",
28
+ "entityType": "columns",
29
+ "table": "official_statements"
30
+ },
31
+ {
32
+ "type": "text",
33
+ "notNull": true,
34
+ "autoincrement": false,
35
+ "default": null,
36
+ "generated": null,
37
+ "name": "data",
38
+ "entityType": "columns",
39
+ "table": "official_statements"
40
+ },
41
+ {
42
+ "columns": ["id"],
43
+ "nameExplicit": false,
44
+ "name": "official_statements_pk",
45
+ "table": "official_statements",
46
+ "entityType": "pks"
47
+ }
48
+ ],
49
+ "renames": []
50
+ }
@@ -0,0 +1,10 @@
1
+ import { sqliteTable, text } from "drizzle-orm/sqlite-core";
2
+ import type { OfficialStatementData } from "../official-statements/types.ts";
3
+
4
+ export const officialStatements = sqliteTable("official_statements", {
5
+ id: text()
6
+ .primaryKey()
7
+ .$defaultFn(() => crypto.randomUUID()),
8
+ threadId: text().notNull(),
9
+ data: text({ mode: "json" }).$type<OfficialStatementData>().notNull(),
10
+ });
@@ -0,0 +1,17 @@
1
+ import { defineConcept } from "@m6d/cortex-server";
2
+
3
+ export const sessionConcept = defineConcept({
4
+ name: "Session",
5
+ description:
6
+ "An authenticated login session for the current user, including device, IP address, last activity, and whether it is the active session on the current device.",
7
+ aliases: [
8
+ "session",
9
+ "login session",
10
+ "active sessions",
11
+ "my sessions",
12
+ "devices signed in",
13
+ "الجلسات",
14
+ "جلساتي",
15
+ "الأجهزة المسجل عليها الدخول",
16
+ ],
17
+ });
@@ -0,0 +1,31 @@
1
+ import { defineEndpoint } from "@m6d/cortex-server";
2
+ import { sessionConcept } from "../concepts/session.concept";
3
+
4
+ export const listCurrentSessionsEndpoint = defineEndpoint({
5
+ name: "List current user sessions",
6
+ path: "/auth/users/current/sessions",
7
+ method: "GET",
8
+ description:
9
+ "Returns all active sessions for the currently authenticated user. Useful for reviewing signed-in devices and recent session activity.",
10
+ queries: [sessionConcept],
11
+ returns: [{ concept: sessionConcept }],
12
+
13
+ // @auto-generated-start
14
+ autoGenerated: {
15
+ params: [] as const,
16
+ body: [] as const,
17
+ response: [
18
+ { name: "sessionId", required: false, type: "uuid" },
19
+ { name: "ipAddress", required: false, type: "string" },
20
+ { name: "deviceType", required: false, type: "string" },
21
+ { name: "userAgent", required: false, type: "string" },
22
+ { name: "createdTime", required: false, type: "datetime" },
23
+ { name: "lastUsedTime", required: false, type: "datetime" },
24
+ { name: "isCurrent", required: false, type: "boolean" },
25
+ ] as const,
26
+ successStatus: 200,
27
+ errorStatuses: [],
28
+ responseKind: "array",
29
+ } as const,
30
+ // @auto-generated-end
31
+ });
@@ -0,0 +1,22 @@
1
+ import { defineEndpoint } from "@m6d/cortex-server";
2
+ import { sessionConcept } from "../concepts/session.concept";
3
+
4
+ export const revokeAllOtherSessionsEndpoint = defineEndpoint({
5
+ name: "Revoke all other current user sessions",
6
+ path: "/auth/users/current/sessions",
7
+ method: "DELETE",
8
+ description:
9
+ "Revokes every active session for the current user except the current session. Useful for signing out from all other devices at once.",
10
+ mutates: [sessionConcept],
11
+
12
+ // @auto-generated-start
13
+ autoGenerated: {
14
+ params: [] as const,
15
+ body: [] as const,
16
+ response: [] as const,
17
+ successStatus: 204,
18
+ errorStatuses: [],
19
+ responseKind: "none",
20
+ } as const,
21
+ // @auto-generated-end
22
+ });