@m6d/cortex-server 1.7.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) 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 → contracts}/graph/helpers.ts +4 -10
  5. package/{src → contracts}/graph/neo4j.ts +14 -27
  6. package/contracts/graph/schema.ts +65 -0
  7. package/{src → contracts}/graph/types.ts +2 -29
  8. package/contracts/graph.ts +36 -0
  9. package/contracts/runtime.ts +208 -0
  10. package/contracts/wire.ts +143 -0
  11. package/dist/contracts/graph/embed.d.ts +22 -0
  12. package/dist/{src → contracts}/graph/helpers.d.ts +14 -12
  13. package/dist/{src → contracts}/graph/neo4j.d.ts +5 -5
  14. package/dist/contracts/graph/schema.d.ts +62 -0
  15. package/dist/{src → contracts}/graph/types.d.ts +1 -1
  16. package/dist/contracts/graph.d.ts +14 -0
  17. package/dist/contracts/runtime.d.ts +278 -0
  18. package/dist/contracts/wire.d.ts +120 -0
  19. package/dist/index.d.ts +1 -1
  20. package/dist/src/lib/adapters/database/index.d.ts +61 -0
  21. package/dist/src/lib/adapters/database/message-content.d.ts +30 -0
  22. package/dist/src/lib/adapters/database/mssql/attachments.d.ts +100 -0
  23. package/dist/src/lib/adapters/database/mssql/client.d.ts +8 -0
  24. package/dist/src/lib/adapters/database/mssql/index.d.ts +194 -0
  25. package/dist/src/lib/adapters/database/mssql/llm-requests.d.ts +17 -0
  26. package/dist/src/lib/adapters/database/mssql/messages.d.ts +37 -0
  27. package/dist/src/lib/adapters/database/mssql/threads.d.ts +50 -0
  28. package/dist/src/lib/adapters/database/postgres/attachments.d.ts +113 -0
  29. package/dist/src/lib/adapters/database/postgres/client.d.ts +8 -0
  30. package/dist/src/lib/adapters/database/postgres/index.d.ts +207 -0
  31. package/dist/src/lib/adapters/database/postgres/llm-requests.d.ts +17 -0
  32. package/dist/src/lib/adapters/database/postgres/messages.d.ts +37 -0
  33. package/dist/src/lib/adapters/database/postgres/threads.d.ts +50 -0
  34. package/{src/adapters/storage.ts → dist/src/lib/adapters/storage/index.d.ts} +1 -1
  35. package/dist/src/{adapters → lib/adapters/storage}/minio.d.ts +1 -1
  36. package/dist/src/lib/ai/active-runs.d.ts +63 -0
  37. package/dist/src/lib/ai/attachments.d.ts +30 -0
  38. package/dist/src/lib/ai/backend-url.d.ts +16 -0
  39. package/dist/src/lib/ai/cc-runtime.d.ts +61 -0
  40. package/dist/src/lib/ai/commit-gate.d.ts +21 -0
  41. package/dist/src/{ai → lib/ai}/context/builder.d.ts +6 -7
  42. package/dist/src/lib/ai/context/compression-middleware.d.ts +15 -0
  43. package/dist/src/lib/ai/context/compressor.d.ts +7 -0
  44. package/dist/src/lib/ai/context/intra-turn-compressor.d.ts +24 -0
  45. package/dist/src/lib/ai/context/optimize-thread-context.d.ts +9 -0
  46. package/dist/src/lib/ai/context/summarizer.d.ts +5 -0
  47. package/dist/src/{ai → lib/ai}/context/token-estimator.d.ts +5 -8
  48. package/dist/src/{ai → lib/ai}/context/types.d.ts +2 -0
  49. package/dist/src/{ai → 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 +38 -0
  52. package/dist/src/lib/ai/index.d.ts +7 -0
  53. package/dist/src/lib/ai/inspector.d.ts +41 -0
  54. package/dist/src/lib/ai/interceptors/request-interceptor.d.ts +13 -0
  55. package/dist/src/{ai → 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 -0
  59. package/dist/src/lib/ai/tools/query-graph.tool.d.ts +13 -0
  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 +170 -0
  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 -0
  78. package/dist/src/{db/schema.d.ts → lib/db/schema.mssql.d.ts} +236 -24
  79. package/dist/src/lib/db/schema.pg.d.ts +546 -0
  80. package/dist/src/{factory.d.ts → lib/factory.d.ts} +2 -12
  81. package/dist/src/lib/graph/index.d.ts +10 -0
  82. package/dist/src/{graph → lib/graph}/resolver.d.ts +2 -3
  83. package/dist/src/{index.d.ts → lib/index.d.ts} +3 -4
  84. package/dist/src/lib/redis.d.ts +19 -0
  85. package/dist/src/{routes → lib/routes}/chat.d.ts +1 -1
  86. package/dist/src/{routes → lib/routes}/files.d.ts +1 -1
  87. package/dist/src/lib/routes/owned-thread.d.ts +17 -0
  88. package/dist/src/{routes → lib/routes}/threads.d.ts +1 -1
  89. package/dist/src/{routes → lib/routes}/ws.d.ts +1 -1
  90. package/dist/src/lib/types.d.ts +58 -0
  91. package/dist/src/{ws → lib/ws}/connections.d.ts +2 -1
  92. package/index.ts +1 -1
  93. package/package.json +35 -15
  94. package/src/lib/adapters/database/index.ts +78 -0
  95. package/src/lib/adapters/database/message-content.ts +39 -0
  96. package/src/lib/adapters/database/mssql/attachments.ts +90 -0
  97. package/src/lib/adapters/database/mssql/client.ts +11 -0
  98. package/src/lib/adapters/database/mssql/index.ts +23 -0
  99. package/src/lib/adapters/database/mssql/llm-requests.ts +43 -0
  100. package/src/lib/adapters/database/mssql/messages.ts +92 -0
  101. package/src/lib/adapters/database/mssql/threads.ts +83 -0
  102. package/src/lib/adapters/database/postgres/attachments.ts +88 -0
  103. package/src/lib/adapters/database/postgres/client.ts +11 -0
  104. package/src/lib/adapters/database/postgres/index.ts +23 -0
  105. package/src/lib/adapters/database/postgres/llm-requests.ts +45 -0
  106. package/src/lib/adapters/database/postgres/messages.ts +92 -0
  107. package/src/lib/adapters/database/postgres/threads.ts +84 -0
  108. package/{dist/src/adapters/storage.d.ts → src/lib/adapters/storage/index.ts} +1 -1
  109. package/src/{adapters → lib/adapters/storage}/minio.ts +7 -6
  110. package/src/lib/ai/active-runs.ts +157 -0
  111. package/src/lib/ai/attachments.ts +144 -0
  112. package/src/lib/ai/backend-url.ts +27 -0
  113. package/src/lib/ai/cc-runtime.ts +63 -0
  114. package/src/lib/ai/commit-gate.ts +116 -0
  115. package/src/{ai → lib/ai}/context/builder.ts +12 -14
  116. package/src/lib/ai/context/compression-middleware.ts +44 -0
  117. package/src/lib/ai/context/compressor.ts +267 -0
  118. package/src/lib/ai/context/intra-turn-compressor.ts +181 -0
  119. package/src/lib/ai/context/optimize-thread-context.ts +50 -0
  120. package/src/lib/ai/context/summarizer.ts +48 -0
  121. package/src/lib/ai/context/token-estimator.ts +65 -0
  122. package/src/{ai → lib/ai}/context/types.ts +4 -1
  123. package/src/{ai → lib/ai}/fetch.ts +10 -5
  124. package/src/lib/ai/finish-turn.ts +75 -0
  125. package/src/lib/ai/helpers.ts +100 -0
  126. package/src/lib/ai/index.ts +408 -0
  127. package/src/lib/ai/inspector.ts +112 -0
  128. package/src/lib/ai/interceptors/request-interceptor.ts +89 -0
  129. package/src/lib/ai/prompt.ts +355 -0
  130. package/src/lib/ai/redis-runs.ts +167 -0
  131. package/src/lib/ai/redis-stream-log.ts +219 -0
  132. package/src/lib/ai/tools/execute-code.tool.ts +267 -0
  133. package/src/{ai → lib/ai}/tools/query-graph.tool.ts +7 -8
  134. package/src/lib/ai/tools/read-attachment.tool.ts +59 -0
  135. package/src/lib/ai/tools/search-common.ts +15 -0
  136. package/src/lib/ai/tools/search-knowledge.tool.ts +33 -0
  137. package/src/lib/ai/tools/search-services.tool.ts +31 -0
  138. package/src/lib/ai/tools/search-tools.tool.ts +29 -0
  139. package/src/lib/ai/turn-tools.ts +154 -0
  140. package/src/lib/ai/vision/rasterize-pdf.ts +69 -0
  141. package/src/lib/ai/vision/rasterize-pdf.worker.ts +81 -0
  142. package/src/lib/ai/vision/vision-reader.ts +130 -0
  143. package/src/{auth → lib/auth}/middleware.ts +12 -3
  144. package/src/lib/cc/client.ts +273 -0
  145. package/src/lib/cc/config-cache.ts +32 -0
  146. package/src/lib/cc/format.ts +96 -0
  147. package/src/lib/cc/registry.ts +62 -0
  148. package/src/lib/cc/types.ts +44 -0
  149. package/src/lib/config.ts +212 -0
  150. package/src/lib/db/drizzle.config.mssql.ts +9 -0
  151. package/src/lib/db/drizzle.config.pg.ts +9 -0
  152. package/src/lib/db/migrate.ts +56 -0
  153. package/src/{db/migrations/20260309012148_cloudy_maria_hill → lib/db/migrations/mssql/20260326231647_nice_speedball}/migration.sql +12 -0
  154. package/src/{db/migrations/20260309012148_cloudy_maria_hill → lib/db/migrations/mssql/20260326231647_nice_speedball}/snapshot.json +106 -1
  155. package/src/lib/db/migrations/mssql/20260729092726_talented_wilson_fisk/migration.sql +20 -0
  156. package/src/lib/db/migrations/mssql/20260729092726_talented_wilson_fisk/snapshot.json +497 -0
  157. package/src/lib/db/migrations/mssql/20260801003652_perpetual_blue_shield/migration.sql +1 -0
  158. package/src/lib/db/migrations/mssql/20260801003652_perpetual_blue_shield/snapshot.json +516 -0
  159. package/src/lib/db/migrations/mssql/20260812174642_user_id_text/migration.sql +2 -0
  160. package/src/lib/db/migrations/mssql/20260812174642_user_id_text/snapshot.json +516 -0
  161. package/src/lib/db/migrations/pg/20260801084117_thick_ben_grimm/migration.sql +53 -0
  162. package/src/lib/db/migrations/pg/20260801084117_thick_ben_grimm/snapshot.json +584 -0
  163. package/src/lib/db/migrations/pg/20260812174622_user_id_text/migration.sql +2 -0
  164. package/src/lib/db/migrations/pg/20260812174622_user_id_text/snapshot.json +584 -0
  165. package/src/lib/db/schema.mssql.ts +94 -0
  166. package/src/lib/db/schema.pg.ts +95 -0
  167. package/src/lib/factory.ts +127 -0
  168. package/src/lib/graph/index.ts +19 -0
  169. package/src/lib/graph/resolver.ts +387 -0
  170. package/src/{index.ts → lib/index.ts} +13 -5
  171. package/src/lib/redis.ts +44 -0
  172. package/src/lib/routes/chat.ts +115 -0
  173. package/src/lib/routes/files.ts +129 -0
  174. package/src/lib/routes/owned-thread.ts +17 -0
  175. package/src/{routes → lib/routes}/threads.ts +22 -31
  176. package/src/{routes → lib/routes}/ws.ts +9 -3
  177. package/src/lib/types.ts +76 -0
  178. package/src/{ws → lib/ws}/connections.ts +9 -1
  179. package/tsconfig.json +48 -0
  180. package/dist/src/adapters/database.d.ts +0 -30
  181. package/dist/src/adapters/mssql.d.ts +0 -3
  182. package/dist/src/ai/active-streams.d.ts +0 -14
  183. package/dist/src/ai/context/compressor.d.ts +0 -7
  184. package/dist/src/ai/context/index.d.ts +0 -15
  185. package/dist/src/ai/context/summarizer.d.ts +0 -5
  186. package/dist/src/ai/helpers.d.ts +0 -5
  187. package/dist/src/ai/index.d.ts +0 -4
  188. package/dist/src/ai/interceptors/request-interceptor.d.ts +0 -12
  189. package/dist/src/ai/tools/call-endpoint.tool.d.ts +0 -7
  190. package/dist/src/ai/tools/capture-files.tool.d.ts +0 -6
  191. package/dist/src/ai/tools/execute-code.tool.d.ts +0 -4
  192. package/dist/src/ai/tools/query-graph.tool.d.ts +0 -5
  193. package/dist/src/cli/extract-endpoints.d.ts +0 -6
  194. package/dist/src/config.d.ts +0 -165
  195. package/dist/src/db/migrate.d.ts +0 -1
  196. package/dist/src/graph/expand-domains.d.ts +0 -2
  197. package/dist/src/graph/generate-cypher.d.ts +0 -22
  198. package/dist/src/graph/index.d.ts +0 -11
  199. package/dist/src/graph/seed.d.ts +0 -19
  200. package/dist/src/graph/validate.d.ts +0 -2
  201. package/dist/src/routes/index.d.ts +0 -4
  202. package/dist/src/types.d.ts +0 -74
  203. package/dist/src/ws/events.d.ts +0 -39
  204. package/dist/src/ws/index.d.ts +0 -3
  205. package/dist/src/ws/notify.d.ts +0 -2
  206. package/src/adapters/database.ts +0 -29
  207. package/src/adapters/mssql.ts +0 -195
  208. package/src/ai/active-streams.ts +0 -123
  209. package/src/ai/context/compressor.ts +0 -47
  210. package/src/ai/context/index.ts +0 -75
  211. package/src/ai/context/summarizer.ts +0 -50
  212. package/src/ai/context/token-estimator.ts +0 -60
  213. package/src/ai/helpers.ts +0 -32
  214. package/src/ai/index.ts +0 -277
  215. package/src/ai/interceptors/request-interceptor.ts +0 -61
  216. package/src/ai/prompt.ts +0 -126
  217. package/src/ai/tools/call-endpoint.tool.ts +0 -89
  218. package/src/ai/tools/capture-files.tool.ts +0 -20
  219. package/src/ai/tools/execute-code.tool.ts +0 -153
  220. package/src/cli/extract-endpoints.ts +0 -550
  221. package/src/config.ts +0 -182
  222. package/src/db/migrate.ts +0 -21
  223. package/src/db/migrations/20260315000000_add_context_meta/migration.sql +0 -1
  224. package/src/db/schema.ts +0 -70
  225. package/src/factory.ts +0 -171
  226. package/src/graph/expand-domains.ts +0 -276
  227. package/src/graph/generate-cypher.ts +0 -192
  228. package/src/graph/index.ts +0 -47
  229. package/src/graph/resolver.ts +0 -357
  230. package/src/graph/seed.ts +0 -162
  231. package/src/graph/validate.ts +0 -78
  232. package/src/routes/chat.ts +0 -86
  233. package/src/routes/files.ts +0 -100
  234. package/src/routes/index.ts +0 -4
  235. package/src/types.ts +0 -74
  236. package/src/ws/events.ts +0 -39
  237. package/src/ws/index.ts +0 -11
  238. package/src/ws/notify.ts +0 -9
  239. /package/dist/src/{auth → lib/auth}/middleware.d.ts +0 -0
@@ -1,15 +0,0 @@
1
- export type { ContextConfig, ThreadContextMeta } from "./types.ts";
2
- export { DEFAULT_CONTEXT_CONFIG } from "./types.ts";
3
- export { CHARS_PER_TOKEN, estimateTokens, estimateMessageTokens, estimateMessagesTokens, } from "./token-estimator.ts";
4
- export { compressToolResults } from "./compressor.ts";
5
- export { summarizeMessages } from "./summarizer.ts";
6
- export { buildContextMessages, trimMessagesToFit } from "./builder.ts";
7
- import type { UIMessage } from "ai";
8
- import type { ResolvedCortexAgentConfig } from "../../config.ts";
9
- import type { Thread } from "../../types.ts";
10
- /**
11
- * Post-response context optimization.
12
- * Called fire-and-forget from onFinish — summarizes older messages
13
- * when token usage exceeds the configured threshold.
14
- */
15
- export declare function optimizeThreadContext(thread: Thread, messages: UIMessage[], config: ResolvedCortexAgentConfig): Promise<void>;
@@ -1,5 +0,0 @@
1
- import type { UIMessage } from "ai";
2
- import type { ContextConfig } from "./types.ts";
3
- type SummarizationModelConfig = NonNullable<ContextConfig["summarizationModel"]>;
4
- export declare function summarizeMessages(messages: UIMessage[], existingSummary: string | null, modelConfig: SummarizationModelConfig): Promise<string>;
5
- export {};
@@ -1,5 +0,0 @@
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;
4
- export declare function streamToBase64(stream: ReadableStream<Uint8Array>): Promise<string>;
5
- export declare function tokenToUserId(token: string): string;
@@ -1,4 +0,0 @@
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>;
4
- export declare function generateTitle(threadId: string, prompt: string, userId: string, config: ResolvedCortexAgentConfig): Promise<void>;
@@ -1,12 +0,0 @@
1
- import type { DatabaseAdapter } from "../../adapters/database.ts";
2
- import type { StorageAdapter } from "../../adapters/storage.ts";
3
- export type ResolvedFile = {
4
- name: string;
5
- bytes: string;
6
- };
7
- export type RequestInterceptorOptions = {
8
- transformFile?: (file: ResolvedFile) => unknown;
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>>;
@@ -1,7 +0,0 @@
1
- import type { ResolvedCortexAgentConfig } from "../../config.ts";
2
- export declare function createCallEndpointTool(backendFetch: NonNullable<ResolvedCortexAgentConfig["backendFetch"]>, token: string): import("ai").Tool<{
3
- method: "GET" | "POST" | "PUT" | "DELETE";
4
- path: string;
5
- body?: string | undefined;
6
- queryParams?: string | undefined;
7
- }, string>;
@@ -1,6 +0,0 @@
1
- export declare const captureFilesTool: import("ai").Tool<{
2
- files: {
3
- id: string;
4
- label: string;
5
- }[];
6
- }, never>;
@@ -1,4 +0,0 @@
1
- import type { ResolvedCortexAgentConfig } from "../../config.ts";
2
- export declare function createExecuteCodeTool(backendFetch: NonNullable<ResolvedCortexAgentConfig["backendFetch"]>, token: string): import("ai").Tool<{
3
- code: string;
4
- }, string>;
@@ -1,5 +0,0 @@
1
- import type { Neo4jClient } from "../../graph/neo4j.ts";
2
- export declare function createQueryGraphTool(neo4j: Neo4jClient): import("ai").Tool<{
3
- query: string;
4
- parameters?: string | undefined;
5
- }, string>;
@@ -1,6 +0,0 @@
1
- export type ExtractEndpointsOptions = {
2
- swaggerUrl: string;
3
- domainsDir: string;
4
- write?: boolean;
5
- };
6
- export declare function extractEndpoints(options: ExtractEndpointsOptions): Promise<void>;
@@ -1,165 +0,0 @@
1
- import type { 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
- export type KnowledgeConfig = {
8
- swagger?: {
9
- url: string;
10
- };
11
- domains?: Record<string, DomainDef>;
12
- };
13
- export type PromptContext<TSession extends Record<string, unknown> = Record<string, unknown>, TRequestContext extends Record<string, unknown> = Record<string, unknown>> = {
14
- session: TSession | null;
15
- requestContext: TRequestContext;
16
- };
17
- export type DatabaseConfig = {
18
- type: "mssql";
19
- connectionString: string;
20
- };
21
- export type StorageConfig = {
22
- endPoint: string;
23
- port: number;
24
- useSSL: boolean;
25
- accessKey: string;
26
- secretKey: string;
27
- bucketName?: string;
28
- };
29
- export type CortexAgentDefinition<TSession extends Record<string, unknown> = Record<string, unknown>, TRequestContext extends Record<string, unknown> = Record<string, unknown>> = {
30
- systemPrompt: string | ((context: PromptContext<TSession, TRequestContext>) => string | Promise<string>);
31
- tools?: ToolSet;
32
- backendFetch?: {
33
- baseUrl: string;
34
- apiKey: string;
35
- headers?: Record<string, string>;
36
- transformRequestBody?: (body: Record<string, unknown>, context: {
37
- token: string;
38
- }) => Promise<Record<string, unknown>>;
39
- interceptor?: RequestInterceptorOptions;
40
- };
41
- loadSessionData?: (token: string) => Promise<TSession>;
42
- resolveRequestContext?: (request: Request) => TRequestContext | Promise<TRequestContext>;
43
- onToolCall?: (toolCall: {
44
- toolName: string;
45
- toolCallId: string;
46
- args: Record<string, unknown>;
47
- }) => void;
48
- onStreamFinish?: (result: {
49
- messages: UIMessage[];
50
- isAborted: boolean;
51
- }) => 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
- };
73
- context?: Partial<ContextConfig>;
74
- knowledge?: KnowledgeConfig | null;
75
- };
76
- export type ResolvedCortexAgentConfig = {
77
- db: DatabaseAdapter;
78
- 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
- };
100
- systemPrompt: string | ((context: PromptContext) => string | Promise<string>);
101
- tools?: ToolSet;
102
- backendFetch?: {
103
- baseUrl: string;
104
- apiKey: string;
105
- headers?: Record<string, string>;
106
- transformRequestBody?: (body: Record<string, unknown>, context: {
107
- token: string;
108
- }) => Promise<Record<string, unknown>>;
109
- interceptor?: RequestInterceptorOptions;
110
- };
111
- loadSessionData?: (token: string) => Promise<Record<string, unknown>>;
112
- resolveRequestContext?: (request: Request) => Record<string, unknown> | Promise<Record<string, unknown>>;
113
- onToolCall?: (toolCall: {
114
- toolName: string;
115
- toolCallId: string;
116
- args: Record<string, unknown>;
117
- }) => void;
118
- onStreamFinish?: (result: {
119
- messages: UIMessage[];
120
- isAborted: boolean;
121
- }) => void;
122
- context: ContextConfig;
123
- knowledge?: KnowledgeConfig;
124
- };
125
- export type CortexConfig = {
126
- port?: number;
127
- database: DatabaseConfig;
128
- storage: StorageConfig;
129
- auth: {
130
- jwksUri: string;
131
- issuer: string;
132
- tokenExtractor?: (req: Request) => string | null;
133
- cookieName?: string;
134
- };
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
- };
156
- context?: Partial<ContextConfig>;
157
- knowledge?: KnowledgeConfig;
158
- agents: Record<string, CortexAgentDefinition>;
159
- };
160
- /**
161
- * Helper to define an agent with full type inference for `systemPrompt` context.
162
- * The `context.session` type is inferred from `loadSessionData`'s return type,
163
- * and `context.requestContext` is inferred from `resolveRequestContext`'s return type.
164
- */
165
- 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;
@@ -1 +0,0 @@
1
- export declare function runMigrations(connectionString: string): Promise<void>;
@@ -1,2 +0,0 @@
1
- import type { DomainDef } from "./types.ts";
2
- export declare function expandDomains(domains: Record<string, DomainDef>): Record<string, DomainDef>;
@@ -1,22 +0,0 @@
1
- /**
2
- * Transforms declarative DomainDef into idempotent MERGE-based Cypher.
3
- *
4
- * Returns two phases:
5
- * - `nodes` -- MERGE statements that create/update Domain, Concept, Endpoint,
6
- * Service, and Rule nodes.
7
- * - `edges` -- MATCH+MERGE statements that wire up relationships between nodes.
8
- *
9
- * The caller MUST run all `nodes` from every module before running any `edges`,
10
- * because edges may reference nodes defined in a different module (e.g. a Rule
11
- * in the leaves module that GOVERNS a Concept created by the servicing module).
12
- */
13
- import type { DomainDef } from "./types.ts";
14
- export type GeneratedCypher = {
15
- nodes: string[];
16
- edges: string[];
17
- };
18
- export declare function generateCypher(data: DomainDef): {
19
- nodes: string[];
20
- edges: string[];
21
- };
22
- export declare function toCypherScript(data: DomainDef): string;
@@ -1,11 +0,0 @@
1
- export type { EndpointScalarType, EndpointProperty, ResponseKind, AutoGenerated, ConceptDef, EndpointDef, EndpointInput, ServiceDef, RuleDef, DomainDef, } from "./types.ts";
2
- export { defineConcept, defineRule, defineService, defineDomain, defineEndpoint, } from "./helpers.ts";
3
- export type { GeneratedCypher } from "./generate-cypher.ts";
4
- export { generateCypher, toCypherScript } from "./generate-cypher.ts";
5
- export { validateDomain } from "./validate.ts";
6
- export type { Neo4jConfig, Neo4jClient } from "./neo4j.ts";
7
- export { createNeo4jClient } from "./neo4j.ts";
8
- export type { EmbeddingConfig, SeedGraphConfig } from "./seed.ts";
9
- export { seedGraph } from "./seed.ts";
10
- export type { RerankerConfig, ResolverConfig, ResolvedEndpoint, ResolvedService, ResolvedContext, } from "./resolver.ts";
11
- export { resolveFromGraph } from "./resolver.ts";
@@ -1,19 +0,0 @@
1
- /**
2
- * Seed orchestrator for the knowledge graph.
3
- *
4
- * Validates domains, generates Cypher, executes against Neo4j,
5
- * and generates concept embeddings. All configuration is passed
6
- * explicitly — no environment variables or Convex dependencies.
7
- */
8
- import type { EmbeddingModel } from "ai";
9
- import type { Neo4jConfig } from "./neo4j.ts";
10
- import type { DomainDef } from "./types.ts";
11
- export type EmbeddingConfig = {
12
- model: EmbeddingModel;
13
- dimension: number;
14
- };
15
- export type SeedGraphConfig = {
16
- neo4j: Neo4jConfig;
17
- embedding: EmbeddingConfig;
18
- };
19
- export declare function seedGraph(config: SeedGraphConfig, domains: Record<string, DomainDef>): Promise<void>;
@@ -1,2 +0,0 @@
1
- import type { DomainDef } from "./types.ts";
2
- export declare function validateDomain(data: DomainDef): string[];
@@ -1,4 +0,0 @@
1
- export { createThreadRoutes } from "./threads.ts";
2
- export { createChatRoutes } from "./chat.ts";
3
- export { createFileRoutes } from "./files.ts";
4
- export { createWsRoute } from "./ws.ts";
@@ -1,74 +0,0 @@
1
- import type { ResolvedCortexAgentConfig } from "./config";
2
- import type { InferSelectModel } from "drizzle-orm";
3
- import type { messages, threads } from "./db/schema";
4
- export type Thread = InferSelectModel<typeof threads>;
5
- export type StoredMessage = InferSelectModel<typeof messages>;
6
- export type ThreadSummary = {
7
- id: string;
8
- title?: string;
9
- createdAt: Date;
10
- updatedAt: Date;
11
- isRunning: boolean;
12
- };
13
- export type MessageMetadata = {
14
- modelId: string;
15
- providerMetadata: unknown;
16
- 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
- };
32
- export type CapturedFileInput = {
33
- id: string;
34
- file: {
35
- name: string;
36
- bytes: string;
37
- };
38
- };
39
- export type AppEnv = {
40
- Bindings: {};
41
- Variables: {
42
- user: {
43
- id: string;
44
- token: string;
45
- } | undefined;
46
- };
47
- };
48
- export type AuthedAppEnv = {
49
- Bindings: {};
50
- Variables: {
51
- user: {
52
- id: string;
53
- token: string;
54
- };
55
- };
56
- };
57
- export type CortexAppEnv = {
58
- Bindings: {};
59
- Variables: {
60
- user: {
61
- id: string;
62
- token: string;
63
- };
64
- agentConfig: ResolvedCortexAgentConfig;
65
- agentId: string;
66
- };
67
- };
68
- export declare function toThreadSummary(thread: Thread, isRunning: boolean): {
69
- id: string;
70
- title: string | undefined;
71
- createdAt: Date;
72
- updatedAt: Date;
73
- isRunning: boolean;
74
- };
@@ -1,39 +0,0 @@
1
- import type { ThreadSummary } from "../types.ts";
2
- export type ThreadCreatedEvent = {
3
- type: "thread:created";
4
- payload: {
5
- thread: ThreadSummary;
6
- };
7
- };
8
- export type ThreadDeletedEvent = {
9
- type: "thread:deleted";
10
- payload: {
11
- threadId: string;
12
- };
13
- };
14
- export type ThreadTitleUpdatedEvent = {
15
- type: "thread:title-updated";
16
- payload: {
17
- thread: ThreadSummary;
18
- };
19
- };
20
- export type ThreadRunStartedEvent = {
21
- type: "thread:run-started";
22
- payload: {
23
- thread: ThreadSummary;
24
- };
25
- };
26
- export type ThreadRunFinishedEvent = {
27
- type: "thread:run-finished";
28
- payload: {
29
- thread: ThreadSummary;
30
- };
31
- };
32
- export type ThreadMessagesUpdatedEvent = {
33
- type: "thread:messages-updated";
34
- payload: {
35
- threadId: string;
36
- thread: ThreadSummary;
37
- };
38
- };
39
- export type WsEvent = ThreadCreatedEvent | ThreadDeletedEvent | ThreadTitleUpdatedEvent | ThreadRunStartedEvent | ThreadRunFinishedEvent | ThreadMessagesUpdatedEvent;
@@ -1,3 +0,0 @@
1
- export { addConnection, removeConnection, getConnections } from "./connections.ts";
2
- export { notify } from "./notify.ts";
3
- export type { WsEvent, ThreadCreatedEvent, ThreadDeletedEvent, ThreadTitleUpdatedEvent, ThreadRunStartedEvent, ThreadRunFinishedEvent, ThreadMessagesUpdatedEvent, } from "./events.ts";
@@ -1,2 +0,0 @@
1
- import type { WsEvent } from "./events.ts";
2
- export declare function notify(userId: string, agentId: string, event: WsEvent): void;
@@ -1,29 +0,0 @@
1
- import type { ToolUIPart, UIMessage } from "ai";
2
- import type { Thread, StoredMessage, CapturedFileInput } from "../types";
3
- import type { ThreadContextMeta } from "../ai/context/types.ts";
4
-
5
- export type DatabaseAdapter = {
6
- threads: {
7
- list(userId: string, agentId: string): Promise<Thread[]>;
8
- getById(userId: string, threadId: string): Promise<Thread | null>;
9
- create(userId: string, agentId: string): Promise<Thread>;
10
- delete(userId: string, threadId: string): Promise<void>;
11
- touch(threadId: string): Promise<Thread>;
12
- updateTitle(threadId: string, title: string): Promise<void>;
13
- updateSession(threadId: string, session: Record<string, unknown>): Promise<void>;
14
- updateContextMeta(threadId: string, meta: ThreadContextMeta): Promise<void>;
15
- };
16
- messages: {
17
- list(userId: string, threadId: string, opts?: { limit?: number }): Promise<StoredMessage[]>;
18
- upsert(threadId: string, messages: UIMessage[]): Promise<void>;
19
- };
20
- capturedFiles: {
21
- create(
22
- userId: string,
23
- messageId: string,
24
- toolPart: ToolUIPart,
25
- files: CapturedFileInput[],
26
- ): Promise<{ id: string; uploadId: string }[]>;
27
- getById(id: string, userId: string): Promise<{ name: string } | null>;
28
- };
29
- };
@@ -1,195 +0,0 @@
1
- import type { ToolUIPart, UIMessage } from "ai";
2
- import { and, desc, eq, getColumns, inArray, type InferInsertModel } from "drizzle-orm";
3
- import { drizzle } from "drizzle-orm/node-mssql";
4
- import { threads, messages, capturedFiles } from "../db/schema";
5
- import type { DatabaseAdapter } from "./database";
6
- import type { StorageAdapter } from "./storage";
7
- import type { Thread, CapturedFileInput, MessageMetadata } from "../types";
8
- import type { ThreadContextMeta } from "../ai/context/types.ts";
9
-
10
- export function createMssqlAdapter(connectionString: string, storage: StorageAdapter) {
11
- const db = drizzle(connectionString, { casing: "snake_case" });
12
-
13
- const adapter: DatabaseAdapter = {
14
- threads: {
15
- async list(userId: string, agentId: string) {
16
- return (await db
17
- .select()
18
- .from(threads)
19
- .where(and(eq(threads.userId, userId), eq(threads.agentId, agentId)))
20
- .orderBy(desc(threads.updatedAt), desc(threads.createdAt))) as Thread[];
21
- },
22
-
23
- async getById(userId: string, threadId: string) {
24
- const result = await db
25
- .select()
26
- .top(1)
27
- .from(threads)
28
- .where(and(eq(threads.id, threadId), eq(threads.userId, userId)))
29
- .execute();
30
- return result.length ? (result[0] as Thread) : null;
31
- },
32
-
33
- async create(userId: string, agentId: string) {
34
- const result = await db
35
- .insert(threads)
36
- .output()
37
- .values({ userId, agentId })
38
- .execute();
39
- return result[0] as Thread;
40
- },
41
-
42
- async delete(userId: string, threadId: string) {
43
- const capturedFilePaths = await db
44
- .select({ id: capturedFiles.id })
45
- .from(capturedFiles)
46
- .innerJoin(messages, eq(messages.id, capturedFiles.messageId))
47
- .innerJoin(threads, eq(threads.id, messages.threadId))
48
- .where(and(eq(threads.id, threadId), eq(threads.userId, userId)))
49
- .execute()
50
- .then((x) => x.map((y) => `captured_files/${y.id}`));
51
-
52
- await storage.delete(capturedFilePaths);
53
-
54
- await db
55
- .delete(threads)
56
- .where(and(eq(threads.id, threadId), eq(threads.userId, userId)))
57
- .execute();
58
- },
59
-
60
- async touch(threadId: string) {
61
- const result = await db
62
- .update(threads)
63
- .set({ updatedAt: new Date() })
64
- .where(eq(threads.id, threadId))
65
- .output()
66
- .execute();
67
-
68
- return result[0] as Thread;
69
- },
70
-
71
- async updateTitle(threadId: string, title: string) {
72
- await db.update(threads).set({ title }).where(eq(threads.id, threadId)).execute();
73
- },
74
-
75
- async updateSession(threadId: string, session: Record<string, unknown>) {
76
- await db.update(threads).set({ session }).where(eq(threads.id, threadId)).execute();
77
- },
78
-
79
- async updateContextMeta(threadId: string, meta: ThreadContextMeta) {
80
- await db
81
- .update(threads)
82
- .set({ contextMeta: meta })
83
- .where(eq(threads.id, threadId))
84
- .execute();
85
- },
86
- },
87
-
88
- messages: {
89
- async list(userId: string, threadId: string, opts?: { limit?: number }) {
90
- return await db
91
- .select(getColumns(messages))
92
- .from(messages)
93
- .innerJoin(threads, eq(threads.id, messages.threadId))
94
- .where(and(eq(threads.userId, userId), eq(threads.id, threadId)))
95
- .orderBy(desc(messages.createdAt))
96
- .offset(0)
97
- .fetch(opts?.limit ?? 100)
98
- .then((x) => x.reverse());
99
- },
100
-
101
- async upsert(threadId: string, messagesToUpsert: UIMessage<MessageMetadata>[]) {
102
- const ids = messagesToUpsert.map((x) => x.id);
103
-
104
- const existingIds = await db
105
- .select({ id: messages.id })
106
- .from(messages)
107
- .where(inArray(messages.id, ids))
108
- .execute()
109
- .then((x) => x.map((y) => y.id));
110
-
111
- const newMessages = messagesToUpsert.filter((x) => !existingIds.includes(x.id));
112
-
113
- if (newMessages.length) {
114
- await db
115
- .insert(messages)
116
- .values(
117
- newMessages.map(
118
- (x) =>
119
- ({
120
- id: x.id,
121
- role: x.role,
122
- threadId,
123
- content: x,
124
- text: x.parts.find((y) => y.type === "text")?.text,
125
- }) satisfies InferInsertModel<typeof messages>,
126
- ),
127
- )
128
- .execute();
129
- }
130
-
131
- const existingMessages = messagesToUpsert.filter((x) => existingIds.includes(x.id));
132
- for (const message of existingMessages) {
133
- await db
134
- .update(messages)
135
- .set({
136
- content: message,
137
- text: message.parts.find((x) => x.type === "text")?.text,
138
- })
139
- .where(eq(messages.id, message.id))
140
- .execute();
141
- }
142
- },
143
- },
144
-
145
- capturedFiles: {
146
- async create(
147
- userId: string,
148
- messageId: string,
149
- toolPart: ToolUIPart,
150
- files: CapturedFileInput[],
151
- ) {
152
- const result = await db
153
- .insert(capturedFiles)
154
- .output({ id: capturedFiles.id })
155
- .values(
156
- files.map(
157
- (file) =>
158
- ({
159
- userId,
160
- messageId,
161
- toolPart,
162
- name: file.file.name,
163
- agentGeneratedId: file.id,
164
- }) satisfies InferInsertModel<typeof capturedFiles>,
165
- ),
166
- )
167
- .execute()
168
- .then((x) => x.map((y) => y.id));
169
-
170
- await Promise.all(
171
- result.map(
172
- async (id, idx) =>
173
- await storage.put(`captured_files/${id}`, files[idx]!.file.bytes),
174
- ),
175
- );
176
-
177
- return result.map((r, i) => ({ id: files[i]!.id, uploadId: r }));
178
- },
179
-
180
- async getById(id: string, userId: string) {
181
- const file = await db
182
- .select()
183
- .top(1)
184
- .from(capturedFiles)
185
- .where(and(eq(capturedFiles.id, id), eq(capturedFiles.userId, userId)))
186
- .execute()
187
- .then((x) => (x.length ? x[0] : null));
188
-
189
- return file ? { name: file.name } : null;
190
- },
191
- },
192
- };
193
-
194
- return adapter;
195
- }