@terreno/ai 0.3.2
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.
- package/.claude/CLAUDE.local.md +208 -0
- package/.cursor/rules/00-root.mdc +342 -0
- package/.cursorrules +221 -0
- package/.github/copilot-instructions.md +337 -0
- package/AGENTS.md +337 -0
- package/biome.jsonc +20 -0
- package/bunfig.toml +3 -0
- package/dist/aiApp.d.ts +59 -0
- package/dist/aiApp.js +67 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +23 -0
- package/dist/models/aiRequest.d.ts +2 -0
- package/dist/models/aiRequest.js +76 -0
- package/dist/models/aiRequest.test.d.ts +1 -0
- package/dist/models/aiRequest.test.js +187 -0
- package/dist/models/fileAttachment.d.ts +2 -0
- package/dist/models/fileAttachment.js +25 -0
- package/dist/models/fileAttachment.test.d.ts +1 -0
- package/dist/models/fileAttachment.test.js +217 -0
- package/dist/models/gptHistory.d.ts +2 -0
- package/dist/models/gptHistory.js +56 -0
- package/dist/models/gptHistory.test.d.ts +1 -0
- package/dist/models/gptHistory.test.js +336 -0
- package/dist/models/index.d.ts +3 -0
- package/dist/models/index.js +9 -0
- package/dist/routes/aiRequestsExplorer.d.ts +2 -0
- package/dist/routes/aiRequestsExplorer.js +153 -0
- package/dist/routes/files.d.ts +5 -0
- package/dist/routes/files.js +168 -0
- package/dist/routes/gpt.d.ts +2 -0
- package/dist/routes/gpt.js +593 -0
- package/dist/routes/gptHistories.d.ts +3 -0
- package/dist/routes/gptHistories.js +29 -0
- package/dist/routes/index.d.ts +5 -0
- package/dist/routes/index.js +13 -0
- package/dist/routes/mcp.d.ts +2 -0
- package/dist/routes/mcp.js +133 -0
- package/dist/routes/routes.test.d.ts +1 -0
- package/dist/routes/routes.test.js +303 -0
- package/dist/service/aiService.d.ts +24 -0
- package/dist/service/aiService.js +453 -0
- package/dist/service/aiService.test.d.ts +1 -0
- package/dist/service/aiService.test.js +367 -0
- package/dist/service/fileStorage.d.ts +24 -0
- package/dist/service/fileStorage.js +143 -0
- package/dist/service/index.d.ts +4 -0
- package/dist/service/index.js +15 -0
- package/dist/service/mcpService.d.ts +14 -0
- package/dist/service/mcpService.js +271 -0
- package/dist/service/prompts.d.ts +4 -0
- package/dist/service/prompts.js +14 -0
- package/dist/tests/bunSetup.d.ts +1 -0
- package/dist/tests/bunSetup.js +227 -0
- package/dist/types/index.d.ts +170 -0
- package/dist/types/index.js +7 -0
- package/package.json +55 -0
- package/src/aiApp.ts +110 -0
- package/src/index.ts +6 -0
- package/src/models/aiRequest.test.ts +101 -0
- package/src/models/aiRequest.ts +45 -0
- package/src/models/fileAttachment.test.ts +119 -0
- package/src/models/fileAttachment.ts +31 -0
- package/src/models/gptHistory.test.ts +209 -0
- package/src/models/gptHistory.ts +71 -0
- package/src/models/index.ts +3 -0
- package/src/routes/aiRequestsExplorer.ts +107 -0
- package/src/routes/files.ts +128 -0
- package/src/routes/gpt.ts +503 -0
- package/src/routes/gptHistories.ts +31 -0
- package/src/routes/index.ts +5 -0
- package/src/routes/mcp.ts +76 -0
- package/src/routes/routes.test.ts +168 -0
- package/src/service/aiService.test.ts +242 -0
- package/src/service/aiService.ts +269 -0
- package/src/service/fileStorage.ts +74 -0
- package/src/service/index.ts +9 -0
- package/src/service/mcpService.ts +120 -0
- package/src/service/prompts.ts +18 -0
- package/src/tests/bunSetup.ts +163 -0
- package/src/types/index.ts +224 -0
- package/tsconfig.json +31 -0
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import {Storage} from "@google-cloud/storage";
|
|
2
|
+
|
|
3
|
+
import {FileAttachment} from "../models/fileAttachment";
|
|
4
|
+
|
|
5
|
+
export interface UploadFileParams {
|
|
6
|
+
buffer: Buffer;
|
|
7
|
+
filename: string;
|
|
8
|
+
mimeType: string;
|
|
9
|
+
userId: import("mongoose").Types.ObjectId;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface UploadFileResult {
|
|
13
|
+
filename: string;
|
|
14
|
+
gcsKey: string;
|
|
15
|
+
mimeType: string;
|
|
16
|
+
size: number;
|
|
17
|
+
url: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export class FileStorageService {
|
|
21
|
+
private storage: Storage;
|
|
22
|
+
private bucketName: string;
|
|
23
|
+
|
|
24
|
+
constructor({bucketName}: {bucketName: string}) {
|
|
25
|
+
this.storage = new Storage();
|
|
26
|
+
this.bucketName = bucketName;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
private get bucket() {
|
|
30
|
+
return this.storage.bucket(this.bucketName);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async upload({buffer, filename, mimeType, userId}: UploadFileParams): Promise<UploadFileResult> {
|
|
34
|
+
const timestamp = Date.now();
|
|
35
|
+
const sanitizedFilename = filename.replace(/[^a-zA-Z0-9._-]/g, "_");
|
|
36
|
+
const gcsKey = `uploads/${userId.toString()}/${timestamp}-${sanitizedFilename}`;
|
|
37
|
+
|
|
38
|
+
const file = this.bucket.file(gcsKey);
|
|
39
|
+
await file.save(buffer, {
|
|
40
|
+
contentType: mimeType,
|
|
41
|
+
metadata: {userId: userId.toString()},
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const url = `https://storage.googleapis.com/${this.bucketName}/${gcsKey}`;
|
|
45
|
+
|
|
46
|
+
await FileAttachment.create({
|
|
47
|
+
filename,
|
|
48
|
+
gcsKey,
|
|
49
|
+
mimeType,
|
|
50
|
+
size: buffer.length,
|
|
51
|
+
url,
|
|
52
|
+
userId,
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
return {filename, gcsKey, mimeType, size: buffer.length, url};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
async getSignedUrl(gcsKey: string): Promise<string> {
|
|
59
|
+
const file = this.bucket.file(gcsKey);
|
|
60
|
+
const [url] = await file.getSignedUrl({
|
|
61
|
+
action: "read",
|
|
62
|
+
expires: Date.now() + 60 * 60 * 1000, // 1 hour
|
|
63
|
+
version: "v4",
|
|
64
|
+
});
|
|
65
|
+
return url;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
async delete(gcsKey: string): Promise<void> {
|
|
69
|
+
const file = this.bucket.file(gcsKey);
|
|
70
|
+
await file.delete({ignoreNotFound: true});
|
|
71
|
+
|
|
72
|
+
await FileAttachment.findOneAndUpdate({gcsKey}, {deleted: true});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export {AIService, TemperaturePresets} from "./aiService";
|
|
2
|
+
export {FileStorageService} from "./fileStorage";
|
|
3
|
+
export {MCPService} from "./mcpService";
|
|
4
|
+
export {
|
|
5
|
+
CONTENT_SUMMARY_PROMPT,
|
|
6
|
+
DEFAULT_GPT_MEMORY,
|
|
7
|
+
REMIX_PROMPT,
|
|
8
|
+
TRANSLATION_PROMPT,
|
|
9
|
+
} from "./prompts";
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import {createMCPClient} from "@ai-sdk/mcp";
|
|
2
|
+
import type {Tool} from "ai";
|
|
3
|
+
|
|
4
|
+
import type {MCPServerConfig} from "../types";
|
|
5
|
+
|
|
6
|
+
interface MCPClientInstance {
|
|
7
|
+
close: () => Promise<void>;
|
|
8
|
+
tools: () => Promise<Record<string, Tool>>;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
interface MCPConnection {
|
|
12
|
+
client: MCPClientInstance | null;
|
|
13
|
+
config: MCPServerConfig;
|
|
14
|
+
connected: boolean;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export class MCPService {
|
|
18
|
+
private connections: Map<string, MCPConnection> = new Map();
|
|
19
|
+
|
|
20
|
+
constructor(servers: MCPServerConfig[]) {
|
|
21
|
+
for (const config of servers) {
|
|
22
|
+
this.connections.set(config.name, {client: null, config, connected: false});
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async connect(): Promise<void> {
|
|
27
|
+
const connectPromises = Array.from(this.connections.entries()).map(
|
|
28
|
+
async ([_name, connection]) => {
|
|
29
|
+
try {
|
|
30
|
+
const client = await createMCPClient({
|
|
31
|
+
transport: {
|
|
32
|
+
headers: connection.config.transport.headers,
|
|
33
|
+
type: "sse",
|
|
34
|
+
url: connection.config.transport.url,
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
connection.client = client as unknown as MCPClientInstance;
|
|
38
|
+
connection.connected = true;
|
|
39
|
+
} catch {
|
|
40
|
+
connection.connected = false;
|
|
41
|
+
connection.client = null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
);
|
|
45
|
+
|
|
46
|
+
await Promise.allSettled(connectPromises);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async disconnect(): Promise<void> {
|
|
50
|
+
const disconnectPromises = Array.from(this.connections.values()).map(async (connection) => {
|
|
51
|
+
if (connection.client) {
|
|
52
|
+
try {
|
|
53
|
+
await connection.client.close();
|
|
54
|
+
} catch {
|
|
55
|
+
// Ignore disconnect errors
|
|
56
|
+
}
|
|
57
|
+
connection.client = null;
|
|
58
|
+
connection.connected = false;
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
await Promise.allSettled(disconnectPromises);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async reconnectServer(name: string): Promise<boolean> {
|
|
66
|
+
const connection = this.connections.get(name);
|
|
67
|
+
if (!connection) {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
if (connection.client) {
|
|
72
|
+
try {
|
|
73
|
+
await connection.client.close();
|
|
74
|
+
} catch {
|
|
75
|
+
// Ignore
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
try {
|
|
80
|
+
const client = await createMCPClient({
|
|
81
|
+
transport: {
|
|
82
|
+
headers: connection.config.transport.headers,
|
|
83
|
+
type: "sse",
|
|
84
|
+
url: connection.config.transport.url,
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
connection.client = client as unknown as MCPClientInstance;
|
|
88
|
+
connection.connected = true;
|
|
89
|
+
return true;
|
|
90
|
+
} catch {
|
|
91
|
+
connection.connected = false;
|
|
92
|
+
connection.client = null;
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async getTools(): Promise<Record<string, Tool>> {
|
|
98
|
+
const allTools: Record<string, Tool> = {};
|
|
99
|
+
|
|
100
|
+
for (const [, connection] of this.connections) {
|
|
101
|
+
if (connection.connected && connection.client) {
|
|
102
|
+
try {
|
|
103
|
+
const tools = await connection.client.tools();
|
|
104
|
+
Object.assign(allTools, tools);
|
|
105
|
+
} catch {
|
|
106
|
+
// Skip tools from failed servers
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
return allTools;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
getServerStatus(): Array<{name: string; connected: boolean}> {
|
|
115
|
+
return Array.from(this.connections.entries()).map(([name, connection]) => ({
|
|
116
|
+
connected: connection.connected,
|
|
117
|
+
name,
|
|
118
|
+
}));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export const DEFAULT_GPT_MEMORY =
|
|
2
|
+
"You are a helpful, friendly AI assistant. Provide clear, accurate, and concise responses. " +
|
|
3
|
+
"When you don't know something, say so honestly rather than guessing.";
|
|
4
|
+
|
|
5
|
+
export const REMIX_PROMPT =
|
|
6
|
+
"Reword the following text to sound more natural and polished while preserving the original " +
|
|
7
|
+
"meaning and tone. Do not add any new information or change the intent. Return only the " +
|
|
8
|
+
"reworded text with no additional commentary.";
|
|
9
|
+
|
|
10
|
+
export const CONTENT_SUMMARY_PROMPT =
|
|
11
|
+
"Provide a concise two-paragraph summary of the following text. The first paragraph should " +
|
|
12
|
+
"cover the main points and key findings. The second paragraph should highlight any important " +
|
|
13
|
+
"details, implications, or action items.";
|
|
14
|
+
|
|
15
|
+
export const TRANSLATION_PROMPT =
|
|
16
|
+
"Translate the following text from {sourceLanguage} to {targetLanguage}. " +
|
|
17
|
+
"Maintain the original tone and meaning as closely as possible. " +
|
|
18
|
+
"Return only the translated text with no additional commentary.";
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import {afterAll, afterEach, beforeAll, beforeEach, mock} from "bun:test";
|
|
2
|
+
import {Writable} from "node:stream";
|
|
3
|
+
import {setupEnvironment, winstonLogger} from "@terreno/api";
|
|
4
|
+
import mongoose from "mongoose";
|
|
5
|
+
import winston from "winston";
|
|
6
|
+
|
|
7
|
+
// Connect to MongoDB once for all tests
|
|
8
|
+
beforeAll(async () => {
|
|
9
|
+
await mongoose
|
|
10
|
+
.connect("mongodb://127.0.0.1/terreno-ai-test?&connectTimeoutMS=360000")
|
|
11
|
+
.catch((err) => {
|
|
12
|
+
console.error("Failed to connect to MongoDB:", err);
|
|
13
|
+
});
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
// Close MongoDB connection after all tests
|
|
17
|
+
afterAll(async () => {
|
|
18
|
+
await mongoose.connection.close();
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
let logs: string[] = [];
|
|
22
|
+
|
|
23
|
+
const SHOW_ALL_LOGS = process.env.SHOW_ALL_TEST_LOGS === "true";
|
|
24
|
+
|
|
25
|
+
// Create a custom stream that captures logs
|
|
26
|
+
const logStream = new Writable({
|
|
27
|
+
write(chunk: unknown, _encoding: unknown, callback: () => void) {
|
|
28
|
+
logs.push(String(chunk));
|
|
29
|
+
if (SHOW_ALL_LOGS) {
|
|
30
|
+
process.stdout.write(String(chunk));
|
|
31
|
+
}
|
|
32
|
+
callback();
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
// Silence both winston loggers by replacing all transports with our capturing stream
|
|
37
|
+
const silentTransport = new winston.transports.Stream({
|
|
38
|
+
format: winston.format.simple(),
|
|
39
|
+
stream: logStream,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
// Clear and silence the default winston logger
|
|
43
|
+
winston.clear();
|
|
44
|
+
winston.add(silentTransport);
|
|
45
|
+
|
|
46
|
+
// Clear and silence the custom winstonLogger
|
|
47
|
+
winstonLogger.clear();
|
|
48
|
+
winstonLogger.add(silentTransport);
|
|
49
|
+
|
|
50
|
+
// Capture and silence console methods
|
|
51
|
+
const originalConsole = {
|
|
52
|
+
debug: console.debug,
|
|
53
|
+
error: console.error,
|
|
54
|
+
info: console.info,
|
|
55
|
+
// biome-ignore lint/suspicious/noConsole: We keep the original reference.
|
|
56
|
+
log: console.log,
|
|
57
|
+
warn: console.warn,
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
const captureConsoleMethod = (method: keyof typeof originalConsole): void => {
|
|
61
|
+
(console as any)[method] = (...args: any[]) => {
|
|
62
|
+
const logMessage = `[console.${method}] ${args.map((arg) => (typeof arg === "object" ? JSON.stringify(arg) : String(arg))).join(" ")}`;
|
|
63
|
+
logs.push(logMessage);
|
|
64
|
+
if (SHOW_ALL_LOGS) {
|
|
65
|
+
originalConsole[method](...args);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
captureConsoleMethod("log");
|
|
71
|
+
captureConsoleMethod("info");
|
|
72
|
+
captureConsoleMethod("warn");
|
|
73
|
+
captureConsoleMethod("error");
|
|
74
|
+
captureConsoleMethod("debug");
|
|
75
|
+
|
|
76
|
+
// Setup before each test
|
|
77
|
+
beforeEach(() => {
|
|
78
|
+
process.env.TOKEN_SECRET = "secret";
|
|
79
|
+
process.env.TOKEN_ISSUER = "terreno-ai.test";
|
|
80
|
+
process.env.SESSION_SECRET = "sessionSecret";
|
|
81
|
+
process.env.REFRESH_TOKEN_SECRET = "refreshTokenSecret";
|
|
82
|
+
setupEnvironment();
|
|
83
|
+
// Re-silence loggers after setupEnvironment which may reconfigure them
|
|
84
|
+
winston.clear();
|
|
85
|
+
winston.add(silentTransport);
|
|
86
|
+
winstonLogger.clear();
|
|
87
|
+
winstonLogger.add(silentTransport);
|
|
88
|
+
logs = [];
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
// Clear logs after each test
|
|
92
|
+
afterEach(() => {
|
|
93
|
+
logs = [];
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
// Mock @sentry/bun module
|
|
97
|
+
mock.module("@sentry/bun", () => {
|
|
98
|
+
const mockFn = (): ReturnType<typeof mock> => mock(() => {});
|
|
99
|
+
|
|
100
|
+
const mockScope = {
|
|
101
|
+
addBreadcrumb: mockFn(),
|
|
102
|
+
clear: mockFn(),
|
|
103
|
+
getSpan: mockFn(),
|
|
104
|
+
setContext: mockFn(),
|
|
105
|
+
setFingerprint: mockFn(),
|
|
106
|
+
setLevel: mockFn(),
|
|
107
|
+
setSpan: mockFn(),
|
|
108
|
+
setTag: mockFn(),
|
|
109
|
+
setTags: mockFn(),
|
|
110
|
+
setTransactionName: mockFn(),
|
|
111
|
+
setUser: mockFn(),
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
const mockClient = {
|
|
115
|
+
captureException: mockFn(),
|
|
116
|
+
captureMessage: mockFn(),
|
|
117
|
+
close: mock(() => Promise.resolve(true)),
|
|
118
|
+
flush: mock(() => Promise.resolve(true)),
|
|
119
|
+
getOptions: mock(() => ({})),
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
return {
|
|
123
|
+
addBreadcrumb: mockFn(),
|
|
124
|
+
captureException: mockFn(),
|
|
125
|
+
captureMessage: mockFn(),
|
|
126
|
+
clearScope: mockFn(),
|
|
127
|
+
close: mock(() => Promise.resolve(true)),
|
|
128
|
+
configureScope: mockFn(),
|
|
129
|
+
default: {
|
|
130
|
+
captureException: mockFn(),
|
|
131
|
+
captureMessage: mockFn(),
|
|
132
|
+
Handlers: {
|
|
133
|
+
errorHandler: mock(
|
|
134
|
+
() => (err: unknown, _req: unknown, _res: unknown, next: (e?: unknown) => void) =>
|
|
135
|
+
next(err)
|
|
136
|
+
),
|
|
137
|
+
requestHandler: mock(() => (_req: unknown, _res: unknown, next: () => void) => next()),
|
|
138
|
+
tracingHandler: mock(() => (_req: unknown, _res: unknown, next: () => void) => next()),
|
|
139
|
+
},
|
|
140
|
+
init: mockFn(),
|
|
141
|
+
isInitialized: mock(() => true),
|
|
142
|
+
setupExpressErrorHandler: mockFn(),
|
|
143
|
+
},
|
|
144
|
+
flush: mock(() => Promise.resolve(true)),
|
|
145
|
+
getClient: mock(() => mockClient),
|
|
146
|
+
getCurrentScope: mock(() => mockScope),
|
|
147
|
+
Handlers: {
|
|
148
|
+
errorHandler: mock(
|
|
149
|
+
() => (err: unknown, _req: unknown, _res: unknown, next: (e?: unknown) => void) => next(err)
|
|
150
|
+
),
|
|
151
|
+
requestHandler: mock(() => (_req: unknown, _res: unknown, next: () => void) => next()),
|
|
152
|
+
tracingHandler: mock(() => (_req: unknown, _res: unknown, next: () => void) => next()),
|
|
153
|
+
},
|
|
154
|
+
init: mockFn(),
|
|
155
|
+
isInitialized: mock(() => true),
|
|
156
|
+
setContext: mockFn(),
|
|
157
|
+
setTag: mockFn(),
|
|
158
|
+
setTags: mockFn(),
|
|
159
|
+
setUser: mockFn(),
|
|
160
|
+
setupExpressErrorHandler: mockFn(),
|
|
161
|
+
withScope: mock((callback: (scope: typeof mockScope) => void) => callback(mockScope)),
|
|
162
|
+
};
|
|
163
|
+
});
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import type {FindExactlyOnePlugin, FindOneOrNonePlugin} from "@terreno/api";
|
|
2
|
+
import type {LanguageModel} from "ai";
|
|
3
|
+
import type mongoose from "mongoose";
|
|
4
|
+
|
|
5
|
+
// ============================================================
|
|
6
|
+
// AIRequest Types
|
|
7
|
+
// ============================================================
|
|
8
|
+
|
|
9
|
+
export const AI_REQUEST_TYPES = ["general", "remix", "summarization", "translation"] as const;
|
|
10
|
+
export type AIRequestType = (typeof AI_REQUEST_TYPES)[number];
|
|
11
|
+
|
|
12
|
+
export type AIRequestDocument = mongoose.Document<mongoose.Types.ObjectId> & {
|
|
13
|
+
created: Date;
|
|
14
|
+
deleted: boolean;
|
|
15
|
+
error?: string;
|
|
16
|
+
metadata?: Record<string, unknown>;
|
|
17
|
+
aiModel: string;
|
|
18
|
+
prompt: string;
|
|
19
|
+
requestType: AIRequestType;
|
|
20
|
+
response?: string;
|
|
21
|
+
responseTime?: number;
|
|
22
|
+
tokensUsed?: number;
|
|
23
|
+
updated: Date;
|
|
24
|
+
userId?: mongoose.Types.ObjectId;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export interface AIRequestStatics
|
|
28
|
+
extends FindExactlyOnePlugin<AIRequestDocument>,
|
|
29
|
+
FindOneOrNonePlugin<AIRequestDocument> {
|
|
30
|
+
logRequest(params: LogRequestParams): Promise<AIRequestDocument>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type AIRequestModel = mongoose.Model<AIRequestDocument> & AIRequestStatics;
|
|
34
|
+
|
|
35
|
+
export interface LogRequestParams {
|
|
36
|
+
error?: string;
|
|
37
|
+
metadata?: Record<string, unknown>;
|
|
38
|
+
aiModel: string;
|
|
39
|
+
prompt: string;
|
|
40
|
+
requestType: AIRequestType;
|
|
41
|
+
response?: string;
|
|
42
|
+
responseTime?: number;
|
|
43
|
+
tokensUsed?: number;
|
|
44
|
+
userId?: mongoose.Types.ObjectId;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// ============================================================
|
|
48
|
+
// Content Part Types (Multi-modal)
|
|
49
|
+
// ============================================================
|
|
50
|
+
|
|
51
|
+
export interface TextContentPart {
|
|
52
|
+
type: "text";
|
|
53
|
+
text: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface ImageContentPart {
|
|
57
|
+
type: "image";
|
|
58
|
+
url: string;
|
|
59
|
+
mimeType?: string;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export interface FileContentPart {
|
|
63
|
+
type: "file";
|
|
64
|
+
url: string;
|
|
65
|
+
filename?: string;
|
|
66
|
+
mimeType: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export type MessageContentPart = TextContentPart | ImageContentPart | FileContentPart;
|
|
70
|
+
|
|
71
|
+
// ============================================================
|
|
72
|
+
// GptHistory Types
|
|
73
|
+
// ============================================================
|
|
74
|
+
|
|
75
|
+
export interface GptHistoryPrompt {
|
|
76
|
+
model?: string;
|
|
77
|
+
rating?: "up" | "down";
|
|
78
|
+
text: string;
|
|
79
|
+
type: "user" | "assistant" | "system" | "tool-call" | "tool-result";
|
|
80
|
+
content?: MessageContentPart[];
|
|
81
|
+
toolCallId?: string;
|
|
82
|
+
toolName?: string;
|
|
83
|
+
args?: Record<string, unknown>;
|
|
84
|
+
result?: unknown;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export type GptHistoryDocument = mongoose.Document<mongoose.Types.ObjectId> & {
|
|
88
|
+
created: Date;
|
|
89
|
+
deleted: boolean;
|
|
90
|
+
prompts: GptHistoryPrompt[];
|
|
91
|
+
title?: string;
|
|
92
|
+
updated: Date;
|
|
93
|
+
userId: mongoose.Types.ObjectId;
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
export interface GptHistoryStatics
|
|
97
|
+
extends FindExactlyOnePlugin<GptHistoryDocument>,
|
|
98
|
+
FindOneOrNonePlugin<GptHistoryDocument> {}
|
|
99
|
+
|
|
100
|
+
export type GptHistoryModel = mongoose.Model<GptHistoryDocument> & GptHistoryStatics;
|
|
101
|
+
|
|
102
|
+
// ============================================================
|
|
103
|
+
// AI Service Types
|
|
104
|
+
// ============================================================
|
|
105
|
+
|
|
106
|
+
export interface AIServiceOptions {
|
|
107
|
+
defaultTemperature?: number;
|
|
108
|
+
model: LanguageModel;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export interface GenerateTextOptions {
|
|
112
|
+
maxOutputTokens?: number;
|
|
113
|
+
prompt: string;
|
|
114
|
+
stopWhen?: import("ai").StopCondition<any>;
|
|
115
|
+
systemPrompt?: string;
|
|
116
|
+
temperature?: number;
|
|
117
|
+
toolChoice?: "auto" | "none" | "required";
|
|
118
|
+
tools?: Record<string, import("ai").Tool>;
|
|
119
|
+
userId?: mongoose.Types.ObjectId;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export interface GenerateStreamOptions {
|
|
123
|
+
maxOutputTokens?: number;
|
|
124
|
+
prompt: string;
|
|
125
|
+
systemPrompt?: string;
|
|
126
|
+
temperature?: number;
|
|
127
|
+
userId?: mongoose.Types.ObjectId;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export interface GenerateChatStreamOptions {
|
|
131
|
+
messages: Array<{content: string; role: "user" | "assistant" | "system"}>;
|
|
132
|
+
stopWhen?: import("ai").StopCondition<any>;
|
|
133
|
+
systemPrompt?: string;
|
|
134
|
+
toolChoice?: "auto" | "none" | "required";
|
|
135
|
+
tools?: Record<string, import("ai").Tool>;
|
|
136
|
+
userId?: mongoose.Types.ObjectId;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export interface RemixOptions {
|
|
140
|
+
text: string;
|
|
141
|
+
userId?: mongoose.Types.ObjectId;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export interface SummaryOptions {
|
|
145
|
+
text: string;
|
|
146
|
+
userId?: mongoose.Types.ObjectId;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export interface TranslateOptions {
|
|
150
|
+
sourceLanguage?: string;
|
|
151
|
+
targetLanguage: string;
|
|
152
|
+
text: string;
|
|
153
|
+
userId?: mongoose.Types.ObjectId;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// ============================================================
|
|
157
|
+
// Route Option Types
|
|
158
|
+
// ============================================================
|
|
159
|
+
|
|
160
|
+
export interface GptRouteOptions {
|
|
161
|
+
/** Pre-configured AIService. Optional when using per-request keys or demo mode. */
|
|
162
|
+
aiService?: import("../service/aiService").AIService;
|
|
163
|
+
/** Factory to create a LanguageModel from a per-request API key (x-ai-api-key header). */
|
|
164
|
+
createModelFn?: (apiKey: string, modelId?: string) => import("ai").LanguageModel;
|
|
165
|
+
/** Factory to create per-request tools (e.g. tools that need the request's API key). Merged with static tools. */
|
|
166
|
+
createRequestTools?: (req: import("express").Request) => Record<string, import("ai").Tool>;
|
|
167
|
+
/** Return canned responses when no AI service is available. */
|
|
168
|
+
demoMode?: boolean;
|
|
169
|
+
mcpService?: import("../service/mcpService").MCPService;
|
|
170
|
+
openApiOptions?: Record<string, unknown>;
|
|
171
|
+
tools?: Record<string, import("ai").Tool>;
|
|
172
|
+
toolChoice?: "auto" | "none" | "required";
|
|
173
|
+
maxSteps?: number;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export interface GptHistoryRouteOptions {
|
|
177
|
+
openApiOptions?: Record<string, unknown>;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export interface AiRequestsExplorerRouteOptions {
|
|
181
|
+
openApiOptions?: Record<string, unknown>;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export interface FileRouteOptions {
|
|
185
|
+
gcsBucket: string;
|
|
186
|
+
maxFileSize?: number;
|
|
187
|
+
openApiOptions?: Record<string, unknown>;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
export interface McpRouteOptions {
|
|
191
|
+
mcpService: import("../service/mcpService").MCPService;
|
|
192
|
+
openApiOptions?: Record<string, unknown>;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ============================================================
|
|
196
|
+
// File Attachment Types
|
|
197
|
+
// ============================================================
|
|
198
|
+
|
|
199
|
+
export interface FileAttachmentDocument extends mongoose.Document<mongoose.Types.ObjectId> {
|
|
200
|
+
created: Date;
|
|
201
|
+
deleted: boolean;
|
|
202
|
+
filename: string;
|
|
203
|
+
gcsKey: string;
|
|
204
|
+
mimeType: string;
|
|
205
|
+
size: number;
|
|
206
|
+
updated: Date;
|
|
207
|
+
url: string;
|
|
208
|
+
userId: mongoose.Types.ObjectId;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export interface FileAttachmentStatics
|
|
212
|
+
extends FindExactlyOnePlugin<FileAttachmentDocument>,
|
|
213
|
+
FindOneOrNonePlugin<FileAttachmentDocument> {}
|
|
214
|
+
|
|
215
|
+
export type FileAttachmentModel = mongoose.Model<FileAttachmentDocument> & FileAttachmentStatics;
|
|
216
|
+
|
|
217
|
+
// ============================================================
|
|
218
|
+
// MCP Types
|
|
219
|
+
// ============================================================
|
|
220
|
+
|
|
221
|
+
export interface MCPServerConfig {
|
|
222
|
+
name: string;
|
|
223
|
+
transport: {type: "sse"; url: string; headers?: Record<string, string>};
|
|
224
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"allowJs": true,
|
|
4
|
+
"allowSyntheticDefaultImports": true,
|
|
5
|
+
"baseUrl": "./",
|
|
6
|
+
"declaration": true,
|
|
7
|
+
"downlevelIteration": true,
|
|
8
|
+
"esModuleInterop": true,
|
|
9
|
+
"forceConsistentCasingInFileNames": true,
|
|
10
|
+
"jsx": "react",
|
|
11
|
+
"lib": ["es2017", "dom", "es2017.object"],
|
|
12
|
+
"module": "commonjs",
|
|
13
|
+
"moduleResolution": "node",
|
|
14
|
+
"noEmit": false,
|
|
15
|
+
"noImplicitAny": false,
|
|
16
|
+
"noImplicitReturns": true,
|
|
17
|
+
"noImplicitThis": true,
|
|
18
|
+
"noUnusedLocals": false,
|
|
19
|
+
"noUnusedParameters": false,
|
|
20
|
+
"outDir": "./dist",
|
|
21
|
+
"preserveConstEnums": true,
|
|
22
|
+
"removeComments": false,
|
|
23
|
+
"skipLibCheck": true,
|
|
24
|
+
"strict": true,
|
|
25
|
+
"strictFunctionTypes": true,
|
|
26
|
+
"strictNullChecks": true,
|
|
27
|
+
"target": "es5"
|
|
28
|
+
},
|
|
29
|
+
"exclude": ["node_modules"],
|
|
30
|
+
"include": ["src/**/*.ts*", "src/*.ts", "types.d.ts"]
|
|
31
|
+
}
|