@m6d/cortex-server 1.7.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 (252) 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/{config.d.ts → lib/config.d.ts} +54 -66
  8. package/dist/src/{db → lib/db}/schema.d.ts +104 -1
  9. package/dist/src/{index.d.ts → lib/index.d.ts} +1 -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/{config.ts → lib/config.ts} +65 -66
  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} +2 -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/src/ai/context/compressor.ts +0 -47
  185. package/src/ai/prompt.ts +0 -126
  186. package/src/ai/tools/call-endpoint.tool.ts +0 -89
  187. package/src/db/migrations/20260315000000_add_context_meta/migration.sql +0 -1
  188. package/dist/src/{adapters → lib/adapters}/minio.d.ts +0 -0
  189. package/dist/src/{adapters → lib/adapters}/mssql.d.ts +0 -0
  190. package/dist/src/{adapters → lib/adapters}/storage.d.ts +0 -0
  191. package/dist/src/{ai → lib/ai}/active-streams.d.ts +0 -0
  192. package/dist/src/{ai → lib/ai}/context/builder.d.ts +0 -0
  193. package/dist/src/{ai → lib/ai}/context/summarizer.d.ts +0 -0
  194. package/dist/src/{ai → lib/ai}/context/token-estimator.d.ts +0 -0
  195. package/dist/src/{ai → lib/ai}/fetch.d.ts +0 -0
  196. package/dist/src/{ai → lib/ai}/helpers.d.ts +0 -0
  197. package/dist/src/{ai → lib/ai}/index.d.ts +0 -0
  198. package/dist/src/{ai → lib/ai}/interceptors/request-interceptor.d.ts +0 -0
  199. package/dist/src/{ai → lib/ai}/prompt.d.ts +0 -0
  200. package/dist/src/{ai → lib/ai}/tools/capture-files.tool.d.ts +0 -0
  201. package/dist/src/{ai → lib/ai}/tools/execute-code.tool.d.ts +0 -0
  202. package/dist/src/{ai → lib/ai}/tools/query-graph.tool.d.ts +0 -0
  203. package/dist/src/{auth → lib/auth}/middleware.d.ts +0 -0
  204. package/dist/src/{cli → lib/cli}/extract-endpoints.d.ts +0 -0
  205. package/dist/src/{db → lib/db}/migrate.d.ts +0 -0
  206. package/dist/src/{factory.d.ts → lib/factory.d.ts} +0 -0
  207. package/dist/src/{graph → lib/graph}/expand-domains.d.ts +0 -0
  208. package/dist/src/{graph → lib/graph}/generate-cypher.d.ts +0 -0
  209. package/dist/src/{graph → lib/graph}/helpers.d.ts +2 -2
  210. /package/dist/src/{graph → lib/graph}/index.d.ts +0 -0
  211. /package/dist/src/{graph → lib/graph}/neo4j.d.ts +0 -0
  212. /package/dist/src/{graph → lib/graph}/resolver.d.ts +0 -0
  213. /package/dist/src/{graph → lib/graph}/seed.d.ts +0 -0
  214. /package/dist/src/{graph → lib/graph}/types.d.ts +0 -0
  215. /package/dist/src/{graph → lib/graph}/validate.d.ts +0 -0
  216. /package/dist/src/{routes → lib/routes}/chat.d.ts +0 -0
  217. /package/dist/src/{routes → lib/routes}/files.d.ts +0 -0
  218. /package/dist/src/{routes → lib/routes}/index.d.ts +0 -0
  219. /package/dist/src/{routes → lib/routes}/threads.d.ts +0 -0
  220. /package/dist/src/{routes → lib/routes}/ws.d.ts +0 -0
  221. /package/dist/src/{ws → lib/ws}/connections.d.ts +0 -0
  222. /package/dist/src/{ws → lib/ws}/events.d.ts +0 -0
  223. /package/dist/src/{ws → lib/ws}/index.d.ts +0 -0
  224. /package/dist/src/{ws → lib/ws}/notify.d.ts +0 -0
  225. /package/src/{adapters → lib/adapters}/storage.ts +0 -0
  226. /package/src/{ai → lib/ai}/active-streams.ts +0 -0
  227. /package/src/{ai → lib/ai}/context/builder.ts +0 -0
  228. /package/src/{ai → lib/ai}/context/summarizer.ts +0 -0
  229. /package/src/{ai → lib/ai}/context/token-estimator.ts +0 -0
  230. /package/src/{ai → lib/ai}/fetch.ts +0 -0
  231. /package/src/{ai → lib/ai}/helpers.ts +0 -0
  232. /package/src/{ai → lib/ai}/interceptors/request-interceptor.ts +0 -0
  233. /package/src/{ai → lib/ai}/tools/capture-files.tool.ts +0 -0
  234. /package/src/{ai → lib/ai}/tools/query-graph.tool.ts +0 -0
  235. /package/src/{cli → lib/cli}/extract-endpoints.ts +0 -0
  236. /package/src/{db → lib/db}/migrate.ts +0 -0
  237. /package/src/{graph → lib/graph}/expand-domains.ts +0 -0
  238. /package/src/{graph → lib/graph}/generate-cypher.ts +0 -0
  239. /package/src/{graph → lib/graph}/helpers.ts +0 -0
  240. /package/src/{graph → lib/graph}/index.ts +0 -0
  241. /package/src/{graph → lib/graph}/neo4j.ts +0 -0
  242. /package/src/{graph → lib/graph}/resolver.ts +0 -0
  243. /package/src/{graph → lib/graph}/seed.ts +0 -0
  244. /package/src/{graph → lib/graph}/types.ts +0 -0
  245. /package/src/{graph → lib/graph}/validate.ts +0 -0
  246. /package/src/{routes → lib/routes}/chat.ts +0 -0
  247. /package/src/{routes → lib/routes}/index.ts +0 -0
  248. /package/src/{routes → lib/routes}/ws.ts +0 -0
  249. /package/src/{ws → lib/ws}/connections.ts +0 -0
  250. /package/src/{ws → lib/ws}/events.ts +0 -0
  251. /package/src/{ws → lib/ws}/index.ts +0 -0
  252. /package/src/{ws → lib/ws}/notify.ts +0 -0
package/dist/index.d.ts CHANGED
@@ -1 +1 @@
1
- export * from "./src/index";
1
+ export * from "./src/lib/index";
@@ -1,5 +1,5 @@
1
1
  import type { ToolUIPart, UIMessage } from "ai";
2
- import type { Thread, StoredMessage, CapturedFileInput } from "../types";
2
+ import type { Thread, StoredMessage, CapturedFileInput, TokenUsage } from "../types";
3
3
  import type { ThreadContextMeta } from "../ai/context/types.ts";
4
4
  export type DatabaseAdapter = {
5
5
  threads: {
@@ -18,6 +18,21 @@ export type DatabaseAdapter = {
18
18
  }): Promise<StoredMessage[]>;
19
19
  upsert(threadId: string, messages: UIMessage[]): Promise<void>;
20
20
  };
21
+ llmRequests: {
22
+ insert(requests: {
23
+ messageId: string;
24
+ stepNumber: number;
25
+ prompt: string;
26
+ output: string | null;
27
+ tokenUsage: TokenUsage | null;
28
+ }[]): Promise<void>;
29
+ listByMessageId(messageId: string): Promise<{
30
+ id: string;
31
+ prompt: string;
32
+ output: string | null;
33
+ tokenUsage: TokenUsage | null;
34
+ }[]>;
35
+ };
21
36
  capturedFiles: {
22
37
  create(userId: string, messageId: string, toolPart: ToolUIPart, files: CapturedFileInput[]): Promise<{
23
38
  id: string;
@@ -0,0 +1,18 @@
1
+ import type { UIMessage } from "ai";
2
+ import type { MessageMetadata } from "../../types.ts";
3
+ /**
4
+ * Returns a new array of messages with large tool outputs truncated
5
+ * to `maxTokensPerResult`. Does not mutate the input messages.
6
+ */
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
+ */
18
+ export declare function summarizeValue(val: unknown): string;
@@ -1,9 +1,10 @@
1
1
  export type { ContextConfig, ThreadContextMeta } from "./types.ts";
2
2
  export { DEFAULT_CONTEXT_CONFIG } from "./types.ts";
3
3
  export { CHARS_PER_TOKEN, estimateTokens, estimateMessageTokens, estimateMessagesTokens, } from "./token-estimator.ts";
4
- export { compressToolResults } from "./compressor.ts";
4
+ export { compressToolResults, smartStructuralCompress, summarizeValue } from "./compressor.ts";
5
5
  export { summarizeMessages } from "./summarizer.ts";
6
6
  export { buildContextMessages, trimMessagesToFit } from "./builder.ts";
7
+ export { compressIntraTurnToolResults, estimateToolResultTokens, summarizeOldStepResults, } from "./intra-turn-compressor.ts";
7
8
  import type { UIMessage } from "ai";
8
9
  import type { ResolvedCortexAgentConfig } from "../../config.ts";
9
10
  import type { Thread } from "../../types.ts";
@@ -0,0 +1,24 @@
1
+ import type { LanguageModelV3Prompt } from "@ai-sdk/provider";
2
+ import type { ContextConfig } from "./types.ts";
3
+ type SummarizationModelConfig = NonNullable<ContextConfig["summarizationModel"]>;
4
+ /**
5
+ * Compresses tool results from older steps in the prompt.
6
+ *
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.
10
+ */
11
+ export declare function compressIntraTurnToolResults(prompt: LanguageModelV3Prompt, toolResultMaxTokens: number): LanguageModelV3Prompt;
12
+ /**
13
+ * Estimates the total token count of tool results in the prompt.
14
+ */
15
+ export declare function estimateToolResultTokens(prompt: LanguageModelV3Prompt): number;
16
+ /**
17
+ * When accumulated tool result tokens exceed the threshold, summarizes
18
+ * older step results using a lightweight LLM call.
19
+ *
20
+ * Replaces all tool results except the last two with a single synthetic
21
+ * summary in the oldest tool message.
22
+ */
23
+ export declare function summarizeOldStepResults(prompt: LanguageModelV3Prompt, thresholdTokens: number, modelConfig: SummarizationModelConfig): Promise<LanguageModelV3Prompt>;
24
+ export {};
@@ -10,6 +10,8 @@ export type ContextConfig = {
10
10
  };
11
11
  toolResultMaxTokens: number;
12
12
  recentMessagesToKeep: number;
13
+ /** Token threshold for triggering intra-turn summarization of older tool results */
14
+ intraTurnSummarizationThresholdTokens: number;
13
15
  };
14
16
  export type ThreadContextMeta = {
15
17
  summary: string | null;
@@ -4,6 +4,28 @@ import type { StorageAdapter } from "./adapters/storage";
4
4
  import type { DomainDef } from "./graph/types.ts";
5
5
  import type { RequestInterceptorOptions } from "./ai/interceptors/request-interceptor.ts";
6
6
  import type { ContextConfig } from "./ai/context/types.ts";
7
+ import type { Thread } from "./types.ts";
8
+ type ModelConfig = {
9
+ baseURL: string;
10
+ apiKey: string;
11
+ modelName: string;
12
+ providerName?: string;
13
+ };
14
+ type EmbeddingConfig = {
15
+ baseURL: string;
16
+ apiKey: string;
17
+ modelName: string;
18
+ dimension: number;
19
+ };
20
+ type Neo4jConfig = {
21
+ url: string;
22
+ user: string;
23
+ password: string;
24
+ };
25
+ type RerankerConfig = {
26
+ url: string;
27
+ apiKey: string;
28
+ };
7
29
  export type KnowledgeConfig = {
8
30
  swagger?: {
9
31
  url: string;
@@ -14,6 +36,19 @@ export type PromptContext<TSession extends Record<string, unknown> = Record<stri
14
36
  session: TSession | null;
15
37
  requestContext: TRequestContext;
16
38
  };
39
+ /**
40
+ * Per-request context handed to a tools factory. Allows tool implementations to
41
+ * close over the active thread, user, session, and request-level context without
42
+ * reaching for globals or AsyncLocalStorage.
43
+ */
44
+ export type ToolContext<TSession extends Record<string, unknown> = Record<string, unknown>, TRequestContext extends Record<string, unknown> = Record<string, unknown>> = {
45
+ thread: Thread;
46
+ userId: string;
47
+ token: string;
48
+ session: TSession | null;
49
+ requestContext: TRequestContext;
50
+ };
51
+ export type ToolSetFactory<TSession extends Record<string, unknown> = Record<string, unknown>, TRequestContext extends Record<string, unknown> = Record<string, unknown>> = (context: ToolContext<TSession, TRequestContext>) => ToolSet;
17
52
  export type DatabaseConfig = {
18
53
  type: "mssql";
19
54
  connectionString: string;
@@ -28,7 +63,7 @@ export type StorageConfig = {
28
63
  };
29
64
  export type CortexAgentDefinition<TSession extends Record<string, unknown> = Record<string, unknown>, TRequestContext extends Record<string, unknown> = Record<string, unknown>> = {
30
65
  systemPrompt: string | ((context: PromptContext<TSession, TRequestContext>) => string | Promise<string>);
31
- tools?: ToolSet;
66
+ tools?: ToolSet | ToolSetFactory<TSession, TRequestContext>;
32
67
  backendFetch?: {
33
68
  baseUrl: string;
34
69
  apiKey: string;
@@ -49,56 +84,24 @@ export type CortexAgentDefinition<TSession extends Record<string, unknown> = Rec
49
84
  messages: UIMessage[];
50
85
  isAborted: boolean;
51
86
  }) => void;
52
- model?: {
53
- baseURL: string;
54
- apiKey: string;
55
- modelName: string;
56
- providerName?: string;
57
- };
58
- embedding?: {
59
- baseURL: string;
60
- apiKey: string;
61
- modelName: string;
62
- dimension: number;
63
- };
64
- neo4j?: {
65
- url: string;
66
- user: string;
67
- password: string;
68
- };
69
- reranker?: {
70
- url: string;
71
- apiKey: string;
72
- };
87
+ model?: ModelConfig;
88
+ fastModel?: ModelConfig;
89
+ embedding?: EmbeddingConfig;
90
+ neo4j?: Neo4jConfig;
91
+ reranker?: RerankerConfig;
73
92
  context?: Partial<ContextConfig>;
74
93
  knowledge?: KnowledgeConfig | null;
75
94
  };
76
95
  export type ResolvedCortexAgentConfig = {
77
96
  db: DatabaseAdapter;
78
97
  storage: StorageAdapter;
79
- model: {
80
- baseURL: string;
81
- apiKey: string;
82
- modelName: string;
83
- providerName?: string;
84
- };
85
- embedding: {
86
- baseURL: string;
87
- apiKey: string;
88
- modelName: string;
89
- dimension: number;
90
- };
91
- neo4j: {
92
- url: string;
93
- user: string;
94
- password: string;
95
- };
96
- reranker?: {
97
- url: string;
98
- apiKey: string;
99
- };
98
+ model: ModelConfig;
99
+ fastModel?: ModelConfig;
100
+ embedding: EmbeddingConfig;
101
+ neo4j?: Neo4jConfig;
102
+ reranker?: RerankerConfig;
100
103
  systemPrompt: string | ((context: PromptContext) => string | Promise<string>);
101
- tools?: ToolSet;
104
+ tools?: ToolSet | ToolSetFactory;
102
105
  backendFetch?: {
103
106
  baseUrl: string;
104
107
  apiKey: string;
@@ -126,33 +129,17 @@ export type CortexConfig = {
126
129
  port?: number;
127
130
  database: DatabaseConfig;
128
131
  storage: StorageConfig;
129
- auth: {
132
+ auth?: {
130
133
  jwksUri: string;
131
134
  issuer: string;
132
135
  tokenExtractor?: (req: Request) => string | null;
133
136
  cookieName?: string;
134
137
  };
135
- model: {
136
- baseURL: string;
137
- apiKey: string;
138
- modelName: string;
139
- providerName?: string;
140
- };
141
- embedding: {
142
- baseURL: string;
143
- apiKey: string;
144
- modelName: string;
145
- dimension: number;
146
- };
147
- neo4j: {
148
- url: string;
149
- user: string;
150
- password: string;
151
- };
152
- reranker?: {
153
- url: string;
154
- apiKey: string;
155
- };
138
+ model: ModelConfig;
139
+ fastModel?: ModelConfig;
140
+ embedding: EmbeddingConfig;
141
+ neo4j?: Neo4jConfig;
142
+ reranker?: RerankerConfig;
156
143
  context?: Partial<ContextConfig>;
157
144
  knowledge?: KnowledgeConfig;
158
145
  agents: Record<string, CortexAgentDefinition>;
@@ -163,3 +150,4 @@ export type CortexConfig = {
163
150
  * and `context.requestContext` is inferred from `resolveRequestContext`'s return type.
164
151
  */
165
152
  export declare function defineAgent<TSession extends Record<string, unknown> = Record<string, unknown>, TRequestContext extends Record<string, unknown> = Record<string, unknown>>(config: CortexAgentDefinition<TSession, TRequestContext>): CortexAgentDefinition;
153
+ export {};
@@ -1,5 +1,5 @@
1
1
  import type { UIMessage } from "ai";
2
- import type { MessageMetadata } from "src/types";
2
+ import type { MessageMetadata, TokenUsage } from "../types.ts";
3
3
  import type { ThreadContextMeta } from "../ai/context/types.ts";
4
4
  export declare const aiSchema: import("drizzle-orm/mssql-core").MsSqlSchema<"ai">;
5
5
  export declare const threads: import("drizzle-orm/mssql-core").MsSqlTableWithColumns<{
@@ -256,6 +256,109 @@ export declare const messages: import("drizzle-orm/mssql-core").MsSqlTableWithCo
256
256
  };
257
257
  dialect: "mssql";
258
258
  }>;
259
+ export declare const llmRequests: import("drizzle-orm/mssql-core").MsSqlTableWithColumns<{
260
+ name: "llm_requests";
261
+ schema: "ai";
262
+ columns: {
263
+ id: import("drizzle-orm/mssql-core").MsSqlColumn<{
264
+ name: string;
265
+ tableName: "llm_requests";
266
+ dataType: "custom";
267
+ data: string;
268
+ driverParam: unknown;
269
+ notNull: true;
270
+ hasDefault: true;
271
+ isPrimaryKey: true;
272
+ isAutoincrement: false;
273
+ hasRuntimeDefault: false;
274
+ enumValues: undefined;
275
+ baseColumn: never;
276
+ identity: undefined;
277
+ generated: undefined;
278
+ }, {}>;
279
+ messageId: import("drizzle-orm/mssql-core").MsSqlColumn<{
280
+ name: string;
281
+ tableName: "llm_requests";
282
+ dataType: "string";
283
+ data: string;
284
+ driverParam: string | number;
285
+ notNull: true;
286
+ hasDefault: false;
287
+ isPrimaryKey: false;
288
+ isAutoincrement: false;
289
+ hasRuntimeDefault: false;
290
+ enumValues: [string, ...string[]];
291
+ baseColumn: never;
292
+ identity: undefined;
293
+ generated: undefined;
294
+ }, {}>;
295
+ stepNumber: import("drizzle-orm/mssql-core").MsSqlColumn<{
296
+ name: string;
297
+ tableName: "llm_requests";
298
+ dataType: "number int32";
299
+ data: number;
300
+ driverParam: number;
301
+ notNull: true;
302
+ hasDefault: false;
303
+ isPrimaryKey: false;
304
+ isAutoincrement: false;
305
+ hasRuntimeDefault: false;
306
+ enumValues: undefined;
307
+ baseColumn: never;
308
+ identity: undefined;
309
+ generated: undefined;
310
+ }, {}>;
311
+ prompt: import("drizzle-orm/mssql-core").MsSqlColumn<{
312
+ name: string;
313
+ tableName: "llm_requests";
314
+ dataType: "string";
315
+ data: string;
316
+ driverParam: string | number;
317
+ notNull: true;
318
+ hasDefault: false;
319
+ isPrimaryKey: false;
320
+ isAutoincrement: false;
321
+ hasRuntimeDefault: false;
322
+ enumValues: [string, ...string[]];
323
+ baseColumn: never;
324
+ identity: undefined;
325
+ generated: undefined;
326
+ }, {}>;
327
+ output: import("drizzle-orm/mssql-core").MsSqlColumn<{
328
+ name: string;
329
+ tableName: "llm_requests";
330
+ dataType: "string";
331
+ data: string;
332
+ driverParam: string | number;
333
+ notNull: false;
334
+ hasDefault: false;
335
+ isPrimaryKey: false;
336
+ isAutoincrement: false;
337
+ hasRuntimeDefault: false;
338
+ enumValues: [string, ...string[]];
339
+ baseColumn: never;
340
+ identity: undefined;
341
+ generated: undefined;
342
+ }, {}>;
343
+ tokenUsage: import("drizzle-orm/mssql-core").MsSqlColumn<{
344
+ name: string;
345
+ tableName: "llm_requests";
346
+ dataType: "object json";
347
+ data: TokenUsage;
348
+ driverParam: string;
349
+ notNull: false;
350
+ hasDefault: false;
351
+ isPrimaryKey: false;
352
+ isAutoincrement: false;
353
+ hasRuntimeDefault: false;
354
+ enumValues: undefined;
355
+ baseColumn: never;
356
+ identity: undefined;
357
+ generated: undefined;
358
+ }, {}>;
359
+ };
360
+ dialect: "mssql";
361
+ }>;
259
362
  export declare const capturedFiles: import("drizzle-orm/mssql-core").MsSqlTableWithColumns<{
260
363
  name: "captured_files";
261
364
  schema: "ai";
@@ -1,4 +1,4 @@
1
- export type { CortexConfig, CortexAgentDefinition, KnowledgeConfig, DatabaseConfig, StorageConfig, PromptContext, } from "./config";
1
+ export type { CortexConfig, CortexAgentDefinition, KnowledgeConfig, DatabaseConfig, StorageConfig, PromptContext, ToolContext, ToolSetFactory, } from "./config";
2
2
  export { defineAgent } from "./config";
3
3
  export type { ContextConfig, ThreadContextMeta } from "./ai/context/types";
4
4
  export type { Thread, AppEnv } from "./types";
@@ -8,7 +8,6 @@ export type { ResolvedFile, RequestInterceptorOptions, } from "./ai/interceptors
8
8
  export { createRequestInterceptor } from "./ai/interceptors/request-interceptor";
9
9
  export { captureFilesTool } from "./ai/tools/capture-files.tool";
10
10
  export { createQueryGraphTool } from "./ai/tools/query-graph.tool";
11
- export { createCallEndpointTool } from "./ai/tools/call-endpoint.tool";
12
11
  export { createExecuteCodeTool } from "./ai/tools/execute-code.tool";
13
12
  export * from "./graph/index";
14
13
  export type { WsEvent, ThreadTitleUpdatedEvent } from "./ws/index";
@@ -10,24 +10,25 @@ export type ThreadSummary = {
10
10
  updatedAt: Date;
11
11
  isRunning: boolean;
12
12
  };
13
+ export type TokenUsage = {
14
+ input: {
15
+ noCache: number;
16
+ cacheRead: number;
17
+ cacheWrite: number;
18
+ total: number;
19
+ };
20
+ output: {
21
+ reasoning: number;
22
+ text: number;
23
+ total: number;
24
+ };
25
+ total: number;
26
+ };
13
27
  export type MessageMetadata = {
14
28
  modelId: string;
15
29
  providerMetadata: unknown;
16
30
  isAborted?: boolean;
17
- 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
+ tokenUsage?: TokenUsage;
31
32
  };
32
33
  export type CapturedFileInput = {
33
34
  id: string;
package/index.ts CHANGED
@@ -1 +1 @@
1
- export * from "./src/index";
1
+ export * from "./src/lib/index";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@m6d/cortex-server",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "description": "Reusable AI agent chat server library for Hono + Bun",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -22,7 +22,10 @@
22
22
  "scripts": {
23
23
  "build": "tsc -p tsconfig.build.json",
24
24
  "db:generate": "drizzle-kit generate",
25
- "db:migrate": "drizzle-kit migrate"
25
+ "db:migrate": "drizzle-kit migrate",
26
+ "db:sample:generate": "drizzle-kit generate --config ./src/sample/drizzle.config.ts",
27
+ "db:sample:migrate": "drizzle-kit migrate --config ./src/sample/drizzle.config.ts",
28
+ "dev": "bun run --hot src/sample/index.ts"
26
29
  },
27
30
  "dependencies": {
28
31
  "@ai-sdk/provider": "^3.0.0",
@@ -40,7 +43,9 @@
40
43
  "ai": "^6.0.104",
41
44
  "drizzle-kit": "^1.0.0-beta.15-859cf75",
42
45
  "hono": "^4.12.3",
43
- "typescript": "^5"
46
+ "jose": "^6.1.3",
47
+ "typescript": "^5",
48
+ "zod": "^4.3.6"
44
49
  },
45
50
  "peerDependencies": {
46
51
  "@ai-sdk/openai-compatible": "^2.0.0",
@@ -1,5 +1,5 @@
1
1
  import type { ToolUIPart, UIMessage } from "ai";
2
- import type { Thread, StoredMessage, CapturedFileInput } from "../types";
2
+ import type { Thread, StoredMessage, CapturedFileInput, TokenUsage } from "../types";
3
3
  import type { ThreadContextMeta } from "../ai/context/types.ts";
4
4
 
5
5
  export type DatabaseAdapter = {
@@ -17,6 +17,25 @@ export type DatabaseAdapter = {
17
17
  list(userId: string, threadId: string, opts?: { limit?: number }): Promise<StoredMessage[]>;
18
18
  upsert(threadId: string, messages: UIMessage[]): Promise<void>;
19
19
  };
20
+ llmRequests: {
21
+ insert(
22
+ requests: {
23
+ messageId: string;
24
+ stepNumber: number;
25
+ prompt: string;
26
+ output: string | null;
27
+ tokenUsage: TokenUsage | null;
28
+ }[],
29
+ ): Promise<void>;
30
+ listByMessageId(messageId: string): Promise<
31
+ {
32
+ id: string;
33
+ prompt: string;
34
+ output: string | null;
35
+ tokenUsage: TokenUsage | null;
36
+ }[]
37
+ >;
38
+ };
20
39
  capturedFiles: {
21
40
  create(
22
41
  userId: string,
@@ -41,7 +41,8 @@ export function createMinioAdapter(config: MinioConfig) {
41
41
  await ensureBucket();
42
42
  await client.putObject(bucketName, path, Buffer.from(data, "base64"));
43
43
  return true;
44
- } catch {
44
+ } catch (e) {
45
+ console.log(e);
45
46
  return false;
46
47
  }
47
48
  },
@@ -1,7 +1,7 @@
1
1
  import type { ToolUIPart, UIMessage } from "ai";
2
- import { and, desc, eq, getColumns, inArray, type InferInsertModel } from "drizzle-orm";
2
+ import { and, asc, desc, eq, getColumns, inArray, type InferInsertModel } from "drizzle-orm";
3
3
  import { drizzle } from "drizzle-orm/node-mssql";
4
- import { threads, messages, capturedFiles } from "../db/schema";
4
+ import { threads, messages, capturedFiles, llmRequests } from "../db/schema";
5
5
  import type { DatabaseAdapter } from "./database";
6
6
  import type { StorageAdapter } from "./storage";
7
7
  import type { Thread, CapturedFileInput, MessageMetadata } from "../types";
@@ -142,6 +142,42 @@ export function createMssqlAdapter(connectionString: string, storage: StorageAda
142
142
  },
143
143
  },
144
144
 
145
+ llmRequests: {
146
+ async insert(requests) {
147
+ if (!requests.length) return;
148
+
149
+ await db
150
+ .insert(llmRequests)
151
+ .values(
152
+ requests.map(
153
+ (r) =>
154
+ ({
155
+ messageId: r.messageId,
156
+ stepNumber: r.stepNumber,
157
+ prompt: r.prompt,
158
+ output: r.output,
159
+ tokenUsage: r.tokenUsage,
160
+ }) satisfies InferInsertModel<typeof llmRequests>,
161
+ ),
162
+ )
163
+ .execute();
164
+ },
165
+
166
+ async listByMessageId(messageId) {
167
+ return await db
168
+ .select({
169
+ id: llmRequests.id,
170
+ prompt: llmRequests.prompt,
171
+ output: llmRequests.output,
172
+ tokenUsage: llmRequests.tokenUsage,
173
+ })
174
+ .from(llmRequests)
175
+ .where(eq(llmRequests.messageId, messageId))
176
+ .orderBy(asc(llmRequests.stepNumber))
177
+ .execute();
178
+ },
179
+ },
180
+
145
181
  capturedFiles: {
146
182
  async create(
147
183
  userId: string,