@terreno/ai 0.3.2 → 0.5.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 (49) hide show
  1. package/README.md +5 -0
  2. package/dist/aiApp.d.ts +2 -0
  3. package/dist/aiApp.js +4 -1
  4. package/dist/models/aiRequest.js +68 -9
  5. package/dist/models/aiRequest.test.js +7 -5
  6. package/dist/models/gptHistory.js +6 -8
  7. package/dist/models/gptHistory.test.js +4 -22
  8. package/dist/models/index.d.ts +1 -0
  9. package/dist/models/index.js +3 -1
  10. package/dist/models/project.d.ts +2 -0
  11. package/dist/models/project.js +47 -0
  12. package/dist/routes/files.js +2 -2
  13. package/dist/routes/gpt.js +368 -128
  14. package/dist/routes/gptHistories.js +1 -1
  15. package/dist/routes/index.d.ts +1 -0
  16. package/dist/routes/index.js +3 -1
  17. package/dist/routes/projects.d.ts +3 -0
  18. package/dist/routes/projects.js +147 -0
  19. package/dist/service/aiService.js +21 -5
  20. package/dist/service/fileStorage.d.ts +3 -1
  21. package/dist/service/fileStorage.js +2 -2
  22. package/dist/service/index.d.ts +2 -1
  23. package/dist/service/index.js +2 -1
  24. package/dist/service/prompts.d.ts +1 -0
  25. package/dist/service/prompts.js +3 -1
  26. package/dist/service/webSearchTool.d.ts +39 -0
  27. package/dist/service/webSearchTool.js +2 -0
  28. package/dist/types/index.d.ts +39 -2
  29. package/dist/types/index.js +7 -2
  30. package/package.json +5 -5
  31. package/src/aiApp.ts +6 -0
  32. package/src/models/aiRequest.test.ts +8 -8
  33. package/src/models/aiRequest.ts +68 -10
  34. package/src/models/gptHistory.test.ts +4 -16
  35. package/src/models/gptHistory.ts +6 -9
  36. package/src/models/index.ts +1 -0
  37. package/src/models/project.ts +54 -0
  38. package/src/routes/files.ts +4 -4
  39. package/src/routes/gpt.ts +493 -295
  40. package/src/routes/gptHistories.ts +1 -1
  41. package/src/routes/index.ts +1 -0
  42. package/src/routes/mcp.ts +1 -1
  43. package/src/routes/projects.ts +115 -0
  44. package/src/service/aiService.ts +22 -6
  45. package/src/service/fileStorage.ts +3 -3
  46. package/src/service/index.ts +2 -0
  47. package/src/service/prompts.ts +4 -0
  48. package/src/service/webSearchTool.ts +40 -0
  49. package/src/types/index.ts +54 -2
@@ -24,6 +24,6 @@ var addGptHistoryRoutes = function (router, options) {
24
24
  }, preCreate: function (body, req) {
25
25
  var _a;
26
26
  return __assign(__assign({}, body), { userId: (_a = req.user) === null || _a === void 0 ? void 0 : _a._id });
27
- }, queryFields: ["userId"], queryFilter: function (user) { return ({ userId: user === null || user === void 0 ? void 0 : user.id }); }, sort: "-updated" })));
27
+ }, queryFields: ["userId", "projectId"], queryFilter: function (user) { return ({ userId: user === null || user === void 0 ? void 0 : user.id }); }, sort: "-updated" })));
28
28
  };
29
29
  exports.addGptHistoryRoutes = addGptHistoryRoutes;
@@ -3,3 +3,4 @@ export { addFileRoutes } from "./files";
3
3
  export { addGptRoutes } from "./gpt";
4
4
  export { addGptHistoryRoutes } from "./gptHistories";
5
5
  export { addMcpRoutes } from "./mcp";
6
+ export { addProjectRoutes } from "./projects";
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.addMcpRoutes = exports.addGptHistoryRoutes = exports.addGptRoutes = exports.addFileRoutes = exports.addAiRequestsExplorerRoutes = void 0;
3
+ exports.addProjectRoutes = exports.addMcpRoutes = exports.addGptHistoryRoutes = exports.addGptRoutes = exports.addFileRoutes = exports.addAiRequestsExplorerRoutes = void 0;
4
4
  var aiRequestsExplorer_1 = require("./aiRequestsExplorer");
5
5
  Object.defineProperty(exports, "addAiRequestsExplorerRoutes", { enumerable: true, get: function () { return aiRequestsExplorer_1.addAiRequestsExplorerRoutes; } });
6
6
  var files_1 = require("./files");
@@ -11,3 +11,5 @@ var gptHistories_1 = require("./gptHistories");
11
11
  Object.defineProperty(exports, "addGptHistoryRoutes", { enumerable: true, get: function () { return gptHistories_1.addGptHistoryRoutes; } });
12
12
  var mcp_1 = require("./mcp");
13
13
  Object.defineProperty(exports, "addMcpRoutes", { enumerable: true, get: function () { return mcp_1.addMcpRoutes; } });
14
+ var projects_1 = require("./projects");
15
+ Object.defineProperty(exports, "addProjectRoutes", { enumerable: true, get: function () { return projects_1.addProjectRoutes; } });
@@ -0,0 +1,3 @@
1
+ export declare const addProjectRoutes: (router: any, options?: {
2
+ openApiOptions?: Record<string, unknown>;
3
+ }) => void;
@@ -0,0 +1,147 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.addProjectRoutes = void 0;
51
+ var api_1 = require("@terreno/api");
52
+ var project_1 = require("../models/project");
53
+ var addProjectRoutes = function (router, options) {
54
+ var _a, _b;
55
+ router.use("/gpt/projects", (0, api_1.modelRouter)(project_1.Project, __assign(__assign({}, options === null || options === void 0 ? void 0 : options.openApiOptions), { permissions: {
56
+ create: [api_1.Permissions.IsAuthenticated],
57
+ delete: [api_1.Permissions.IsOwner],
58
+ list: [api_1.Permissions.IsAuthenticated],
59
+ read: [api_1.Permissions.IsOwner],
60
+ update: [api_1.Permissions.IsOwner],
61
+ }, preCreate: function (body, req) {
62
+ var _a;
63
+ return (__assign(__assign({}, body), { userId: (_a = req.user) === null || _a === void 0 ? void 0 : _a._id }));
64
+ }, queryFields: ["userId"], queryFilter: function (user) { return ({ userId: user === null || user === void 0 ? void 0 : user.id }); }, sort: "-updated" })));
65
+ // Add memory to a project
66
+ router.post("/gpt/projects/:id/memories", [
67
+ (0, api_1.authenticateMiddleware)(),
68
+ (0, api_1.createOpenApiBuilder)((_a = options === null || options === void 0 ? void 0 : options.openApiOptions) !== null && _a !== void 0 ? _a : {})
69
+ .withTags(["gpt"])
70
+ .withSummary("Add a memory to a project")
71
+ .withPathParameter("id", { type: "string" })
72
+ .withRequestBody({
73
+ category: { type: "string" },
74
+ text: { type: "string" },
75
+ })
76
+ .withResponse(200, { data: { type: "object" } })
77
+ .build(),
78
+ ], (0, api_1.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
79
+ var id, _a, text, category, userId, project;
80
+ var _b;
81
+ return __generator(this, function (_c) {
82
+ switch (_c.label) {
83
+ case 0:
84
+ id = req.params.id;
85
+ _a = req.body, text = _a.text, category = _a.category;
86
+ userId = (_b = req.user) === null || _b === void 0 ? void 0 : _b._id;
87
+ if (!text || typeof text !== "string") {
88
+ throw new api_1.APIError({ status: 400, title: "text is required" });
89
+ }
90
+ return [4 /*yield*/, project_1.Project.findById(id)];
91
+ case 1:
92
+ project = _c.sent();
93
+ if (!project) {
94
+ throw new api_1.APIError({ status: 404, title: "Project not found" });
95
+ }
96
+ if (project.userId.toString() !== (userId === null || userId === void 0 ? void 0 : userId.toString())) {
97
+ throw new api_1.APIError({ status: 403, title: "Not authorized" });
98
+ }
99
+ project.memories.push({ category: category, source: "user", text: text });
100
+ return [4 /*yield*/, project.save()];
101
+ case 2:
102
+ _c.sent();
103
+ return [2 /*return*/, res.json({ data: project.memories[project.memories.length - 1] })];
104
+ }
105
+ });
106
+ }); }));
107
+ // Remove memory from a project
108
+ router.delete("/gpt/projects/:id/memories/:memoryId", [
109
+ (0, api_1.authenticateMiddleware)(),
110
+ (0, api_1.createOpenApiBuilder)((_b = options === null || options === void 0 ? void 0 : options.openApiOptions) !== null && _b !== void 0 ? _b : {})
111
+ .withTags(["gpt"])
112
+ .withSummary("Remove a memory from a project")
113
+ .withPathParameter("id", { type: "string" })
114
+ .withPathParameter("memoryId", { type: "string" })
115
+ .withResponse(200, { data: { type: "object" } })
116
+ .build(),
117
+ ], (0, api_1.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
118
+ var _a, id, memoryId, userId, project, memoryIndex;
119
+ var _b;
120
+ return __generator(this, function (_c) {
121
+ switch (_c.label) {
122
+ case 0:
123
+ _a = req.params, id = _a.id, memoryId = _a.memoryId;
124
+ userId = (_b = req.user) === null || _b === void 0 ? void 0 : _b._id;
125
+ return [4 /*yield*/, project_1.Project.findById(id)];
126
+ case 1:
127
+ project = _c.sent();
128
+ if (!project) {
129
+ throw new api_1.APIError({ status: 404, title: "Project not found" });
130
+ }
131
+ if (project.userId.toString() !== (userId === null || userId === void 0 ? void 0 : userId.toString())) {
132
+ throw new api_1.APIError({ status: 403, title: "Not authorized" });
133
+ }
134
+ memoryIndex = project.memories.findIndex(function (m) { var _a; return ((_a = m._id) === null || _a === void 0 ? void 0 : _a.toString()) === memoryId; });
135
+ if (memoryIndex === -1) {
136
+ throw new api_1.APIError({ status: 404, title: "Memory not found" });
137
+ }
138
+ project.memories.splice(memoryIndex, 1);
139
+ return [4 /*yield*/, project.save()];
140
+ case 2:
141
+ _c.sent();
142
+ return [2 /*return*/, res.json({ data: { deleted: true } })];
143
+ }
144
+ });
145
+ }); }));
146
+ };
147
+ exports.addProjectRoutes = addProjectRoutes;
@@ -68,6 +68,7 @@ var __values = (this && this.__values) || function(o) {
68
68
  };
69
69
  Object.defineProperty(exports, "__esModule", { value: true });
70
70
  exports.AIService = exports.TemperaturePresets = void 0;
71
+ var api_1 = require("@terreno/api");
71
72
  var ai_1 = require("ai");
72
73
  var aiRequest_1 = require("../models/aiRequest");
73
74
  var prompts_1 = require("./prompts");
@@ -305,6 +306,7 @@ var AIService = /** @class */ (function () {
305
306
  };
306
307
  AIService.prototype.buildMessages = function (prompts) {
307
308
  var e_2, _a, e_3, _b;
309
+ var _c, _d;
308
310
  var messages = [];
309
311
  try {
310
312
  for (var prompts_2 = __values(prompts), prompts_2_1 = prompts_2.next(); !prompts_2_1.done; prompts_2_1 = prompts_2.next()) {
@@ -316,23 +318,37 @@ var AIService = /** @class */ (function () {
316
318
  if (prompt_1.content && prompt_1.content.length > 0 && role === "user") {
317
319
  var parts = [];
318
320
  try {
319
- for (var _c = (e_3 = void 0, __values(prompt_1.content)), _d = _c.next(); !_d.done; _d = _c.next()) {
320
- var part = _d.value;
321
+ for (var _e = (e_3 = void 0, __values(prompt_1.content)), _f = _e.next(); !_f.done; _f = _e.next()) {
322
+ var part = _f.value;
321
323
  if (part.type === "text") {
322
324
  parts.push({ text: part.text, type: "text" });
323
325
  }
324
326
  else if (part.type === "image") {
325
- parts.push({ image: new URL(part.url), mimeType: part.mimeType, type: "image" });
327
+ api_1.logger.debug("Building image message part", {
328
+ mediaType: part.mimeType,
329
+ urlPrefix: (_c = part.url) === null || _c === void 0 ? void 0 : _c.substring(0, 50),
330
+ });
331
+ parts.push({ image: new URL(part.url), mediaType: part.mimeType, type: "image" });
326
332
  }
327
333
  else if (part.type === "file") {
328
- parts.push({ data: new URL(part.url), mimeType: part.mimeType, type: "file" });
334
+ api_1.logger.debug("Building file message part", {
335
+ filename: part.filename,
336
+ mediaType: part.mimeType,
337
+ urlPrefix: (_d = part.url) === null || _d === void 0 ? void 0 : _d.substring(0, 50),
338
+ });
339
+ parts.push({
340
+ data: new URL(part.url),
341
+ filename: part.filename,
342
+ mediaType: part.mimeType,
343
+ type: "file",
344
+ });
329
345
  }
330
346
  }
331
347
  }
332
348
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
333
349
  finally {
334
350
  try {
335
- if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
351
+ if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
336
352
  }
337
353
  finally { if (e_3) throw e_3.error; }
338
354
  }
@@ -1,3 +1,4 @@
1
+ import { type StorageOptions } from "@google-cloud/storage";
1
2
  export interface UploadFileParams {
2
3
  buffer: Buffer;
3
4
  filename: string;
@@ -14,8 +15,9 @@ export interface UploadFileResult {
14
15
  export declare class FileStorageService {
15
16
  private storage;
16
17
  private bucketName;
17
- constructor({ bucketName }: {
18
+ constructor({ bucketName, storageOptions }: {
18
19
  bucketName: string;
20
+ storageOptions?: StorageOptions;
19
21
  });
20
22
  private get bucket();
21
23
  upload({ buffer, filename, mimeType, userId }: UploadFileParams): Promise<UploadFileResult>;
@@ -57,8 +57,8 @@ var storage_1 = require("@google-cloud/storage");
57
57
  var fileAttachment_1 = require("../models/fileAttachment");
58
58
  var FileStorageService = /** @class */ (function () {
59
59
  function FileStorageService(_a) {
60
- var bucketName = _a.bucketName;
61
- this.storage = new storage_1.Storage();
60
+ var bucketName = _a.bucketName, storageOptions = _a.storageOptions;
61
+ this.storage = new storage_1.Storage(storageOptions);
62
62
  this.bucketName = bucketName;
63
63
  }
64
64
  Object.defineProperty(FileStorageService.prototype, "bucket", {
@@ -1,4 +1,5 @@
1
1
  export { AIService, TemperaturePresets } from "./aiService";
2
2
  export { FileStorageService } from "./fileStorage";
3
3
  export { MCPService } from "./mcpService";
4
- export { CONTENT_SUMMARY_PROMPT, DEFAULT_GPT_MEMORY, REMIX_PROMPT, TRANSLATION_PROMPT, } from "./prompts";
4
+ export { CONTENT_SUMMARY_PROMPT, DEFAULT_GPT_MEMORY, REMIX_PROMPT, TITLE_GENERATION_PROMPT, TRANSLATION_PROMPT, } from "./prompts";
5
+ export type { WebSearchProvider, WebSearchResult } from "./webSearchTool";
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TRANSLATION_PROMPT = exports.REMIX_PROMPT = exports.DEFAULT_GPT_MEMORY = exports.CONTENT_SUMMARY_PROMPT = exports.MCPService = exports.FileStorageService = exports.TemperaturePresets = exports.AIService = void 0;
3
+ exports.TRANSLATION_PROMPT = exports.TITLE_GENERATION_PROMPT = exports.REMIX_PROMPT = exports.DEFAULT_GPT_MEMORY = exports.CONTENT_SUMMARY_PROMPT = exports.MCPService = exports.FileStorageService = exports.TemperaturePresets = exports.AIService = void 0;
4
4
  var aiService_1 = require("./aiService");
5
5
  Object.defineProperty(exports, "AIService", { enumerable: true, get: function () { return aiService_1.AIService; } });
6
6
  Object.defineProperty(exports, "TemperaturePresets", { enumerable: true, get: function () { return aiService_1.TemperaturePresets; } });
@@ -12,4 +12,5 @@ var prompts_1 = require("./prompts");
12
12
  Object.defineProperty(exports, "CONTENT_SUMMARY_PROMPT", { enumerable: true, get: function () { return prompts_1.CONTENT_SUMMARY_PROMPT; } });
13
13
  Object.defineProperty(exports, "DEFAULT_GPT_MEMORY", { enumerable: true, get: function () { return prompts_1.DEFAULT_GPT_MEMORY; } });
14
14
  Object.defineProperty(exports, "REMIX_PROMPT", { enumerable: true, get: function () { return prompts_1.REMIX_PROMPT; } });
15
+ Object.defineProperty(exports, "TITLE_GENERATION_PROMPT", { enumerable: true, get: function () { return prompts_1.TITLE_GENERATION_PROMPT; } });
15
16
  Object.defineProperty(exports, "TRANSLATION_PROMPT", { enumerable: true, get: function () { return prompts_1.TRANSLATION_PROMPT; } });
@@ -2,3 +2,4 @@ export declare const DEFAULT_GPT_MEMORY: string;
2
2
  export declare const REMIX_PROMPT: string;
3
3
  export declare const CONTENT_SUMMARY_PROMPT: string;
4
4
  export declare const TRANSLATION_PROMPT: string;
5
+ export declare const TITLE_GENERATION_PROMPT: string;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TRANSLATION_PROMPT = exports.CONTENT_SUMMARY_PROMPT = exports.REMIX_PROMPT = exports.DEFAULT_GPT_MEMORY = void 0;
3
+ exports.TITLE_GENERATION_PROMPT = exports.TRANSLATION_PROMPT = exports.CONTENT_SUMMARY_PROMPT = exports.REMIX_PROMPT = exports.DEFAULT_GPT_MEMORY = void 0;
4
4
  exports.DEFAULT_GPT_MEMORY = "You are a helpful, friendly AI assistant. Provide clear, accurate, and concise responses. " +
5
5
  "When you don't know something, say so honestly rather than guessing.";
6
6
  exports.REMIX_PROMPT = "Reword the following text to sound more natural and polished while preserving the original " +
@@ -12,3 +12,5 @@ exports.CONTENT_SUMMARY_PROMPT = "Provide a concise two-paragraph summary of the
12
12
  exports.TRANSLATION_PROMPT = "Translate the following text from {sourceLanguage} to {targetLanguage}. " +
13
13
  "Maintain the original tone and meaning as closely as possible. " +
14
14
  "Return only the translated text with no additional commentary.";
15
+ exports.TITLE_GENERATION_PROMPT = "Generate a short title (3-6 words) that summarizes this conversation for a sidebar label. " +
16
+ "Return only the title text with no quotes, punctuation, or additional commentary.";
@@ -0,0 +1,39 @@
1
+ export interface WebSearchResult {
2
+ snippet: string;
3
+ title: string;
4
+ url: string;
5
+ }
6
+ /**
7
+ * Interface for pluggable web search providers.
8
+ *
9
+ * Implement this to integrate any search API (Tavily, Brave, Google Custom Search, etc.)
10
+ * with the AI chat tool system.
11
+ *
12
+ * @example
13
+ * ```typescript
14
+ * import {tool, zodSchema} from "ai";
15
+ * import {z} from "zod";
16
+ * import type {WebSearchProvider} from "@terreno/ai";
17
+ *
18
+ * const myProvider: WebSearchProvider = {
19
+ * search: async (query) => {
20
+ * const res = await fetch(`https://api.tavily.com/search`, { ... });
21
+ * return res.json().results;
22
+ * },
23
+ * };
24
+ *
25
+ * const webSearchTool = tool({
26
+ * description: "Search the web for current information.",
27
+ * execute: async ({query}) => {
28
+ * const results = await myProvider.search(query);
29
+ * return {query, results: results.slice(0, 5)};
30
+ * },
31
+ * inputSchema: zodSchema(z.object({
32
+ * query: z.string().describe("Search query"),
33
+ * })),
34
+ * });
35
+ * ```
36
+ */
37
+ export interface WebSearchProvider {
38
+ search(query: string): Promise<WebSearchResult[]>;
39
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,23 +1,29 @@
1
1
  import type { FindExactlyOnePlugin, FindOneOrNonePlugin } from "@terreno/api";
2
2
  import type { LanguageModel } from "ai";
3
3
  import type mongoose from "mongoose";
4
- export declare const AI_REQUEST_TYPES: readonly ["general", "remix", "summarization", "translation"];
5
- export type AIRequestType = (typeof AI_REQUEST_TYPES)[number];
4
+ export declare const DEFAULT_AI_REQUEST_TYPES: readonly ["general", "remix", "summarization", "translation"];
5
+ export type DefaultAIRequestType = (typeof DEFAULT_AI_REQUEST_TYPES)[number];
6
+ export type AIRequestType = DefaultAIRequestType | (string & {});
6
7
  export type AIRequestDocument = mongoose.Document<mongoose.Types.ObjectId> & {
7
8
  created: Date;
8
9
  deleted: boolean;
9
10
  error?: string;
10
11
  metadata?: Record<string, unknown>;
11
12
  aiModel: string;
13
+ parentRequestId?: mongoose.Types.ObjectId;
12
14
  prompt: string;
13
15
  requestType: AIRequestType;
14
16
  response?: string;
15
17
  responseTime?: number;
18
+ subRequestIds?: mongoose.Types.ObjectId[];
16
19
  tokensUsed?: number;
20
+ totalResponseTime?: number;
21
+ totalTokensUsed?: number;
17
22
  updated: Date;
18
23
  userId?: mongoose.Types.ObjectId;
19
24
  };
20
25
  export interface AIRequestStatics extends FindExactlyOnePlugin<AIRequestDocument>, FindOneOrNonePlugin<AIRequestDocument> {
26
+ logMultiAgentRequest(params: LogMultiAgentRequestParams): Promise<AIRequestDocument>;
21
27
  logRequest(params: LogRequestParams): Promise<AIRequestDocument>;
22
28
  }
23
29
  export type AIRequestModel = mongoose.Model<AIRequestDocument> & AIRequestStatics;
@@ -32,6 +38,15 @@ export interface LogRequestParams {
32
38
  tokensUsed?: number;
33
39
  userId?: mongoose.Types.ObjectId;
34
40
  }
41
+ export interface LogMultiAgentRequestParams {
42
+ aiModel: string;
43
+ metadata?: Record<string, unknown>;
44
+ requestType: AIRequestType;
45
+ subRequestIds: mongoose.Types.ObjectId[];
46
+ totalResponseTime: number;
47
+ totalTokensUsed: number;
48
+ userId?: mongoose.Types.ObjectId;
49
+ }
35
50
  export interface TextContentPart {
36
51
  type: "text";
37
52
  text: string;
@@ -62,6 +77,7 @@ export interface GptHistoryPrompt {
62
77
  export type GptHistoryDocument = mongoose.Document<mongoose.Types.ObjectId> & {
63
78
  created: Date;
64
79
  deleted: boolean;
80
+ projectId?: mongoose.Types.ObjectId;
65
81
  prompts: GptHistoryPrompt[];
66
82
  title?: string;
67
83
  updated: Date;
@@ -70,6 +86,25 @@ export type GptHistoryDocument = mongoose.Document<mongoose.Types.ObjectId> & {
70
86
  export interface GptHistoryStatics extends FindExactlyOnePlugin<GptHistoryDocument>, FindOneOrNonePlugin<GptHistoryDocument> {
71
87
  }
72
88
  export type GptHistoryModel = mongoose.Model<GptHistoryDocument> & GptHistoryStatics;
89
+ export interface ProjectMemory {
90
+ _id?: mongoose.Types.ObjectId;
91
+ category?: string;
92
+ created?: Date;
93
+ source: "user" | "auto";
94
+ text: string;
95
+ }
96
+ export type ProjectDocument = mongoose.Document<mongoose.Types.ObjectId> & {
97
+ created: Date;
98
+ deleted: boolean;
99
+ memories: ProjectMemory[];
100
+ name: string;
101
+ systemContext: string;
102
+ updated: Date;
103
+ userId: mongoose.Types.ObjectId;
104
+ };
105
+ export interface ProjectStatics extends FindExactlyOnePlugin<ProjectDocument>, FindOneOrNonePlugin<ProjectDocument> {
106
+ }
107
+ export type ProjectModel = mongoose.Model<ProjectDocument> & ProjectStatics;
73
108
  export interface AIServiceOptions {
74
109
  defaultTemperature?: number;
75
110
  model: LanguageModel;
@@ -130,6 +165,8 @@ export interface GptRouteOptions {
130
165
  tools?: Record<string, import("ai").Tool>;
131
166
  toolChoice?: "auto" | "none" | "required";
132
167
  maxSteps?: number;
168
+ /** Cheap model ID used for generating conversation titles (e.g. "gemini-2.0-flash-lite"). Falls back to the main model if not set. */
169
+ titleModelId?: string;
133
170
  }
134
171
  export interface GptHistoryRouteOptions {
135
172
  openApiOptions?: Record<string, unknown>;
@@ -1,7 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AI_REQUEST_TYPES = void 0;
3
+ exports.DEFAULT_AI_REQUEST_TYPES = void 0;
4
4
  // ============================================================
5
5
  // AIRequest Types
6
6
  // ============================================================
7
- exports.AI_REQUEST_TYPES = ["general", "remix", "summarization", "translation"];
7
+ exports.DEFAULT_AI_REQUEST_TYPES = [
8
+ "general",
9
+ "remix",
10
+ "summarization",
11
+ "translation",
12
+ ];
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "dependencies": {
7
7
  "@ai-sdk/mcp": "^1.0.21",
8
8
  "@google-cloud/storage": "^7.15.0",
9
- "@terreno/api": "0.3.2",
9
+ "@terreno/api": "0.5.0",
10
10
  "ai": "^6.0.97",
11
11
  "multer": "^1.4.5-lts.1"
12
12
  },
@@ -14,7 +14,7 @@
14
14
  "devDependencies": {
15
15
  "@biomejs/biome": "^2.3.6",
16
16
  "@types/bun": "^1.2.4",
17
- "@types/express": "^4.17.21",
17
+ "@types/express": "^5.0.6",
18
18
  "@types/multer": "^1.4.12",
19
19
  "@types/passport-local-mongoose": "^6.1.5",
20
20
  "@types/supertest": "^6.0.2",
@@ -34,8 +34,8 @@
34
34
  "main": "dist/index.js",
35
35
  "name": "@terreno/ai",
36
36
  "peerDependencies": {
37
- "@terreno/api": "0.3.2",
38
- "mongoose": "^8.0.0"
37
+ "@terreno/api": "0.5.0",
38
+ "mongoose": "^9.0.0"
39
39
  },
40
40
  "repository": {
41
41
  "type": "git",
@@ -51,5 +51,5 @@
51
51
  "test:ci": "bun test --preload ./src/tests/bunSetup.ts"
52
52
  },
53
53
  "types": "dist/index.d.ts",
54
- "version": "0.3.2"
54
+ "version": "0.5.0"
55
55
  }
package/src/aiApp.ts CHANGED
@@ -7,6 +7,7 @@ import {addFileRoutes} from "./routes/files";
7
7
  import {addGptRoutes} from "./routes/gpt";
8
8
  import {addGptHistoryRoutes} from "./routes/gptHistories";
9
9
  import {addMcpRoutes} from "./routes/mcp";
10
+ import {addProjectRoutes} from "./routes/projects";
10
11
  import type {AIService} from "./service/aiService";
11
12
  import type {FileStorageService} from "./service/fileStorage";
12
13
  import type {MCPService} from "./service/mcpService";
@@ -30,6 +31,8 @@ export interface AiAppOptions {
30
31
  openApiOptions?: Record<string, unknown>;
31
32
  /** Tool choice strategy for chat requests. Defaults to "auto" when tools are present. */
32
33
  toolChoice?: "auto" | "none" | "required";
34
+ /** Cheap model ID used for generating conversation titles (e.g. "gemini-2.0-flash-lite"). Falls back to the main model if not set. */
35
+ titleModelId?: string;
33
36
  /** Tool definitions available to the AI model during chat. */
34
37
  tools?: Record<string, Tool>;
35
38
  }
@@ -78,6 +81,7 @@ export class AiApp implements TerrenoPlugin {
78
81
  maxSteps,
79
82
  mcpService,
80
83
  openApiOptions,
84
+ titleModelId,
81
85
  toolChoice,
82
86
  tools,
83
87
  } = this.options;
@@ -90,10 +94,12 @@ export class AiApp implements TerrenoPlugin {
90
94
  maxSteps,
91
95
  mcpService,
92
96
  openApiOptions,
97
+ titleModelId,
93
98
  toolChoice,
94
99
  tools,
95
100
  });
96
101
  addAiRequestsExplorerRoutes(router, {openApiOptions});
102
+ addProjectRoutes(router, {openApiOptions});
97
103
 
98
104
  if (fileStorageService && gcsBucket) {
99
105
  addFileRoutes(router, {
@@ -51,14 +51,14 @@ describe("AIRequest Model", () => {
51
51
  expect(request.metadata).toEqual({key: "value"});
52
52
  });
53
53
 
54
- it("should reject invalid request types", async () => {
55
- await expect(
56
- AIRequest.create({
57
- aiModel: "gpt-4",
58
- prompt: "test",
59
- requestType: "invalid" as any,
60
- })
61
- ).rejects.toThrow();
54
+ it("should accept custom request types", async () => {
55
+ const request = await AIRequest.create({
56
+ aiModel: "gpt-4",
57
+ prompt: "test",
58
+ requestType: "custom-type",
59
+ });
60
+
61
+ expect(request.requestType).toBe("custom-type");
62
62
  });
63
63
  });
64
64