@terreno/ai 0.3.2 → 0.4.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.
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
@@ -75,13 +75,31 @@ var __values = (this && this.__values) || function(o) {
75
75
  };
76
76
  throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
77
77
  };
78
+ var __read = (this && this.__read) || function (o, n) {
79
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
80
+ if (!m) return o;
81
+ var i = m.call(o), r, ar = [], e;
82
+ try {
83
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
84
+ }
85
+ catch (error) { e = { error: error }; }
86
+ finally {
87
+ try {
88
+ if (r && !r.done && (m = i["return"])) m.call(i);
89
+ }
90
+ finally { if (e) throw e.error; }
91
+ }
92
+ return ar;
93
+ };
78
94
  Object.defineProperty(exports, "__esModule", { value: true });
79
95
  exports.addGptRoutes = void 0;
80
96
  var api_1 = require("@terreno/api");
81
97
  var ai_1 = require("ai");
82
98
  var aiRequest_1 = require("../models/aiRequest");
83
99
  var gptHistory_1 = require("../models/gptHistory");
100
+ var project_1 = require("../models/project");
84
101
  var aiService_1 = require("../service/aiService");
102
+ var prompts_1 = require("../service/prompts");
85
103
  var DEMO_RESPONSE = "This is demo mode. To use AI features, paste your Gemini API key in Settings.";
86
104
  /** Send a canned SSE demo response when no AI service is available. */
87
105
  var sendDemoResponse = function (res, historyId) {
@@ -105,8 +123,37 @@ var resolveAiService = function (req, options, modelId) {
105
123
  }
106
124
  return options.aiService;
107
125
  };
126
+ /** Generate a short title for a conversation using a cheap model call. */
127
+ var generateTitle = function (prompt, response, aiService, options, perRequestApiKey) { return __awaiter(void 0, void 0, void 0, function () {
128
+ var titleService, conversationSnippet, title, _a;
129
+ return __generator(this, function (_b) {
130
+ switch (_b.label) {
131
+ case 0:
132
+ _b.trys.push([0, 2, , 3]);
133
+ titleService = aiService;
134
+ if (options.titleModelId && options.createModelFn && perRequestApiKey) {
135
+ titleService = new aiService_1.AIService({
136
+ model: options.createModelFn(perRequestApiKey, options.titleModelId),
137
+ });
138
+ }
139
+ conversationSnippet = "User: ".concat(prompt, "\nAssistant: ").concat(response.substring(0, 500));
140
+ return [4 /*yield*/, titleService.generateText({
141
+ prompt: conversationSnippet,
142
+ systemPrompt: prompts_1.TITLE_GENERATION_PROMPT,
143
+ temperature: 0.3,
144
+ })];
145
+ case 1:
146
+ title = _b.sent();
147
+ return [2 /*return*/, title.trim().replace(/^["']|["']$/g, "")];
148
+ case 2:
149
+ _a = _b.sent();
150
+ return [2 /*return*/, undefined];
151
+ case 3: return [2 /*return*/];
152
+ }
153
+ });
154
+ }); };
108
155
  var addGptRoutes = function (router, options) {
109
- var _a, _b, _c;
156
+ var _a, _b, _c, _d;
110
157
  var mcpService = options.mcpService, routeTools = options.tools, createRequestTools = options.createRequestTools, toolChoice = options.toolChoice, maxSteps = options.maxSteps;
111
158
  router.post("/gpt/prompt", [
112
159
  (0, api_1.authenticateMiddleware)(),
@@ -128,22 +175,30 @@ var addGptRoutes = function (router, options) {
128
175
  },
129
176
  historyId: { type: "string" },
130
177
  model: { type: "string" },
178
+ projectId: { type: "string" },
131
179
  prompt: { type: "string" },
132
180
  systemPrompt: { type: "string" },
133
181
  })
134
182
  .withResponse(200, { data: { type: "string" } })
135
183
  .build(),
136
- ], (0, api_1.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
137
- var _a, prompt, historyId, systemPrompt, attachments, requestModel, userId, hasPerRequestKey, hasCreateModelFn, hasConfiguredService, aiService, history, contentParts, attachments_1, attachments_1_1, attachment, hasAttachments, userPrompt, messages, modelId, supportsTools, allTools, requestTools, mcpTools, _b, fullResponse, generatedImages, startTime, result, partCount, stepTextBuffer, stepHasToolCall, _c, _d, _e, part, cleaned, errMsg, mediaType, dataUrl, textChunk, toolResult, _f, _fileData, cleanResult, e_1_1, cleaned, files, files_1, files_1_1, file, dataUrl, fileErr_1, contentParts_1, assistantPrompt, logErr_1, error_1, logErr_2;
138
- var e_2, _g, e_3, _h;
139
- var _j, e_1, _k, _l;
140
- var _m, _o, _p, _q, _r, _s;
141
- return __generator(this, function (_t) {
142
- switch (_t.label) {
184
+ ],
185
+ // Use a raw handler instead of asyncHandler so we can control error responses
186
+ // for both pre-stream (JSON) and mid-stream (SSE) errors.
187
+ function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
188
+ var sseStarted, _a, prompt_1, historyId, systemPrompt, attachments, requestModel, projectId, userId, hasPerRequestKey, hasCreateModelFn, hasConfiguredService, aiService, history_1, effectiveProjectId, effectiveSystemPrompt, project, parts, projectContext, _b, contentParts, attachments_1, attachments_1_1, attachment, hasAttachments, userPrompt, messages, modelId, supportsTools, allTools, requestTools, mcpTools, _c, fullResponse, generatedImages, startTime, result, partCount, stepTextBuffer, stepHasToolCall, _d, _e, _f, part, cleaned, errMsg, mediaType, dataUrl, textChunk, toolResult, _g, _fileData, cleanResult, e_1_1, cleaned, files, files_1, files_1_1, file, dataUrl, fileErr_1, contentParts_1, assistantPrompt, logErr_1, perRequestApiKey, title, error_1, logErr_2, outerError_1, message, status_1, stack;
189
+ var e_2, _h, e_3, _j;
190
+ var _k, e_1, _l, _m;
191
+ var _o, _p, _q, _r, _s, _t;
192
+ return __generator(this, function (_u) {
193
+ switch (_u.label) {
143
194
  case 0:
144
- _a = req.body, prompt = _a.prompt, historyId = _a.historyId, systemPrompt = _a.systemPrompt, attachments = _a.attachments, requestModel = _a.model;
145
- userId = (_m = req.user) === null || _m === void 0 ? void 0 : _m._id;
146
- if (!prompt || typeof prompt !== "string") {
195
+ sseStarted = false;
196
+ _u.label = 1;
197
+ case 1:
198
+ _u.trys.push([1, 44, , 45]);
199
+ _a = req.body, prompt_1 = _a.prompt, historyId = _a.historyId, systemPrompt = _a.systemPrompt, attachments = _a.attachments, requestModel = _a.model, projectId = _a.projectId;
200
+ userId = (_o = req.user) === null || _o === void 0 ? void 0 : _o._id;
201
+ if (!prompt_1 || typeof prompt_1 !== "string") {
147
202
  throw new api_1.APIError({ status: 400, title: "prompt is required" });
148
203
  }
149
204
  hasPerRequestKey = !!req.headers["x-ai-api-key"];
@@ -159,23 +214,67 @@ var addGptRoutes = function (router, options) {
159
214
  api_1.logger.debug("No AI service available, sending demo response");
160
215
  return [2 /*return*/, sendDemoResponse(res)];
161
216
  }
162
- if (!historyId) return [3 /*break*/, 2];
217
+ if (!historyId) return [3 /*break*/, 3];
163
218
  return [4 /*yield*/, gptHistory_1.GptHistory.findById(historyId)];
164
- case 1:
165
- history = _t.sent();
166
- if (!history) {
219
+ case 2:
220
+ history_1 = _u.sent();
221
+ if (!history_1) {
167
222
  throw new api_1.APIError({ status: 404, title: "History not found" });
168
223
  }
169
- if (history.userId.toString() !== (userId === null || userId === void 0 ? void 0 : userId.toString())) {
224
+ if (history_1.userId.toString() !== (userId === null || userId === void 0 ? void 0 : userId.toString())) {
170
225
  throw new api_1.APIError({ status: 403, title: "Not authorized to access this history" });
171
226
  }
172
- return [3 /*break*/, 3];
173
- case 2:
174
- history = new gptHistory_1.GptHistory({ prompts: [], userId: userId });
175
- _t.label = 3;
227
+ return [3 /*break*/, 4];
176
228
  case 3:
177
- contentParts = [{ text: prompt, type: "text" }];
229
+ history_1 = new gptHistory_1.GptHistory(__assign({ prompts: [], userId: userId }, (projectId ? { projectId: projectId } : {})));
230
+ _u.label = 4;
231
+ case 4:
232
+ // If history doesn't have a projectId yet but one was provided, associate it
233
+ if (projectId && !history_1.projectId) {
234
+ history_1.projectId = projectId;
235
+ }
236
+ effectiveProjectId = projectId !== null && projectId !== void 0 ? projectId : history_1.projectId;
237
+ effectiveSystemPrompt = systemPrompt;
238
+ if (!effectiveProjectId) return [3 /*break*/, 8];
239
+ _u.label = 5;
240
+ case 5:
241
+ _u.trys.push([5, 7, , 8]);
242
+ return [4 /*yield*/, project_1.Project.findById(effectiveProjectId)];
243
+ case 6:
244
+ project = _u.sent();
245
+ if (project && project.userId.toString() === (userId === null || userId === void 0 ? void 0 : userId.toString())) {
246
+ parts = [];
247
+ if (project.systemContext) {
248
+ parts.push(project.systemContext);
249
+ }
250
+ if (project.memories.length > 0) {
251
+ parts.push("## Relevant Memories\n".concat(project.memories.map(function (m) { return "- ".concat(m.text); }).join("\n")));
252
+ }
253
+ if (parts.length > 0) {
254
+ projectContext = parts.join("\n\n");
255
+ effectiveSystemPrompt = effectiveSystemPrompt
256
+ ? "".concat(projectContext, "\n\n").concat(effectiveSystemPrompt)
257
+ : projectContext;
258
+ }
259
+ }
260
+ return [3 /*break*/, 8];
261
+ case 7:
262
+ _b = _u.sent();
263
+ return [3 /*break*/, 8];
264
+ case 8:
265
+ contentParts = [{ text: prompt_1, type: "text" }];
178
266
  if (attachments && Array.isArray(attachments)) {
267
+ api_1.logger.debug("Processing attachments", {
268
+ count: attachments.length,
269
+ types: attachments.map(function (a) {
270
+ var _a, _b;
271
+ return ({
272
+ mimeType: a.mimeType,
273
+ type: a.type,
274
+ urlLength: (_b = (_a = a.url) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0,
275
+ });
276
+ }),
277
+ });
179
278
  try {
180
279
  for (attachments_1 = __values(attachments), attachments_1_1 = attachments_1.next(); !attachments_1_1.done; attachments_1_1 = attachments_1.next()) {
181
280
  attachment = attachments_1_1.value;
@@ -199,43 +298,51 @@ var addGptRoutes = function (router, options) {
199
298
  catch (e_2_1) { e_2 = { error: e_2_1 }; }
200
299
  finally {
201
300
  try {
202
- if (attachments_1_1 && !attachments_1_1.done && (_g = attachments_1.return)) _g.call(attachments_1);
301
+ if (attachments_1_1 && !attachments_1_1.done && (_h = attachments_1.return)) _h.call(attachments_1);
203
302
  }
204
303
  finally { if (e_2) throw e_2.error; }
205
304
  }
206
305
  }
207
306
  hasAttachments = contentParts.length > 1;
208
- userPrompt = __assign({ text: prompt, type: "user" }, (hasAttachments ? { content: contentParts } : {}));
209
- history.prompts.push(userPrompt);
210
- messages = aiService.buildMessages(history.prompts);
307
+ userPrompt = __assign({ text: prompt_1, type: "user" }, (hasAttachments ? { content: contentParts } : {}));
308
+ history_1.prompts.push(userPrompt);
309
+ // Build messages from history using AIService helper
310
+ api_1.logger.debug("Building messages", {
311
+ attachmentCount: contentParts.length - 1,
312
+ historyLength: history_1.prompts.length,
313
+ });
314
+ messages = aiService.buildMessages(history_1.prompts);
315
+ api_1.logger.debug("Messages built", { messageCount: messages.length });
211
316
  modelId = aiService.modelId;
212
317
  supportsTools = !(modelId === null || modelId === void 0 ? void 0 : modelId.includes("image"));
318
+ allTools = void 0;
213
319
  requestTools = createRequestTools ? createRequestTools(req) : undefined;
214
- if (!(supportsTools && (routeTools || requestTools || mcpService))) return [3 /*break*/, 7];
320
+ if (!(supportsTools && (routeTools || requestTools || mcpService))) return [3 /*break*/, 12];
215
321
  allTools = __assign(__assign({}, (routeTools !== null && routeTools !== void 0 ? routeTools : {})), (requestTools !== null && requestTools !== void 0 ? requestTools : {}));
216
- if (!mcpService) return [3 /*break*/, 7];
217
- _t.label = 4;
218
- case 4:
219
- _t.trys.push([4, 6, , 7]);
322
+ if (!mcpService) return [3 /*break*/, 12];
323
+ _u.label = 9;
324
+ case 9:
325
+ _u.trys.push([9, 11, , 12]);
220
326
  return [4 /*yield*/, mcpService.getTools()];
221
- case 5:
222
- mcpTools = _t.sent();
327
+ case 10:
328
+ mcpTools = _u.sent();
223
329
  Object.assign(allTools, mcpTools);
224
- return [3 /*break*/, 7];
225
- case 6:
226
- _b = _t.sent();
227
- return [3 /*break*/, 7];
228
- case 7:
330
+ return [3 /*break*/, 12];
331
+ case 11:
332
+ _c = _u.sent();
333
+ return [3 /*break*/, 12];
334
+ case 12:
229
335
  // Stream response via SSE
230
336
  res.setHeader("Content-Type", "text/event-stream");
231
337
  res.setHeader("Cache-Control", "no-cache");
232
338
  res.setHeader("Connection", "keep-alive");
339
+ sseStarted = true;
233
340
  fullResponse = "";
234
341
  generatedImages = [];
235
342
  startTime = Date.now();
236
- _t.label = 8;
237
- case 8:
238
- _t.trys.push([8, 30, , 35]);
343
+ _u.label = 13;
344
+ case 13:
345
+ _u.trys.push([13, 38, , 43]);
239
346
  api_1.logger.debug("Starting streamText", { model: modelId, supportsTools: supportsTools });
240
347
  result = (0, ai_1.streamText)({
241
348
  messages: messages,
@@ -244,7 +351,7 @@ var addGptRoutes = function (router, options) {
244
351
  ? { google: { responseModalities: ["TEXT", "IMAGE"] } }
245
352
  : undefined,
246
353
  stopWhen: allTools ? (0, ai_1.stepCountIs)(maxSteps !== null && maxSteps !== void 0 ? maxSteps : 5) : (0, ai_1.stepCountIs)(1),
247
- system: systemPrompt !== null && systemPrompt !== void 0 ? systemPrompt : undefined,
354
+ system: effectiveSystemPrompt !== null && effectiveSystemPrompt !== void 0 ? effectiveSystemPrompt : undefined,
248
355
  temperature: aiService.defaultTemperature,
249
356
  toolChoice: allTools ? (toolChoice !== null && toolChoice !== void 0 ? toolChoice : "auto") : undefined,
250
357
  tools: allTools,
@@ -252,26 +359,26 @@ var addGptRoutes = function (router, options) {
252
359
  partCount = 0;
253
360
  stepTextBuffer = "";
254
361
  stepHasToolCall = false;
255
- _t.label = 9;
256
- case 9:
257
- _t.trys.push([9, 14, 15, 20]);
258
- _c = true, _d = __asyncValues(result.fullStream);
259
- _t.label = 10;
260
- case 10: return [4 /*yield*/, _d.next()];
261
- case 11:
262
- if (!(_e = _t.sent(), _j = _e.done, !_j)) return [3 /*break*/, 13];
263
- _l = _e.value;
264
- _c = false;
265
- part = _l;
362
+ _u.label = 14;
363
+ case 14:
364
+ _u.trys.push([14, 19, 20, 25]);
365
+ _d = true, _e = __asyncValues(result.fullStream);
366
+ _u.label = 15;
367
+ case 15: return [4 /*yield*/, _e.next()];
368
+ case 16:
369
+ if (!(_f = _u.sent(), _k = _f.done, !_k)) return [3 /*break*/, 18];
370
+ _m = _f.value;
371
+ _d = false;
372
+ part = _m;
266
373
  partCount++;
267
374
  if (partCount <= 5 || part.type === "error" || part.type === "file") {
268
- api_1.logger.debug("Stream part", __assign(__assign({ partCount: partCount, type: part.type }, (part.type === "file" ? { mediaType: part.mediaType } : {})), (part.type === "error" ? { error: String((_o = part.error) !== null && _o !== void 0 ? _o : part) } : {})));
375
+ api_1.logger.debug("Stream part", __assign(__assign({ partCount: partCount, type: part.type }, (part.type === "file" ? { mediaType: part.mediaType } : {})), (part.type === "error" ? { error: String((_p = part.error) !== null && _p !== void 0 ? _p : part) } : {})));
269
376
  }
270
377
  // Track step boundaries to discard reasoning text from tool-call steps
271
378
  if (part.type === "start-step") {
272
379
  stepTextBuffer = "";
273
380
  stepHasToolCall = false;
274
- return [3 /*break*/, 12];
381
+ return [3 /*break*/, 17];
275
382
  }
276
383
  if (part.type === "finish-step") {
277
384
  // Only emit buffered text if no tool call happened in this step
@@ -286,15 +393,15 @@ var addGptRoutes = function (router, options) {
286
393
  }
287
394
  stepTextBuffer = "";
288
395
  stepHasToolCall = false;
289
- return [3 /*break*/, 12];
396
+ return [3 /*break*/, 17];
290
397
  }
291
398
  if (part.type === "error") {
292
399
  errMsg = part.error instanceof Error
293
400
  ? part.error.message
294
- : String((_p = part.error) !== null && _p !== void 0 ? _p : "Unknown stream error");
401
+ : String((_q = part.error) !== null && _q !== void 0 ? _q : "Unknown stream error");
295
402
  api_1.logger.error("AI stream error part", { error: errMsg });
296
403
  res.write("data: ".concat(JSON.stringify({ error: errMsg }), "\n\n"));
297
- return [3 /*break*/, 12];
404
+ return [3 /*break*/, 17];
298
405
  }
299
406
  if (part.type === "file") {
300
407
  mediaType = part.mediaType;
@@ -304,10 +411,10 @@ var addGptRoutes = function (router, options) {
304
411
  res.write("data: ".concat(JSON.stringify({ image: { mimeType: mediaType, url: dataUrl } }), "\n\n"));
305
412
  api_1.logger.debug("Sent inline image from stream");
306
413
  }
307
- return [3 /*break*/, 12];
414
+ return [3 /*break*/, 17];
308
415
  }
309
416
  if (part.type === "text-delta") {
310
- textChunk = ((_q = part.text) !== null && _q !== void 0 ? _q : "");
417
+ textChunk = ((_r = part.text) !== null && _r !== void 0 ? _r : "");
311
418
  if (textChunk) {
312
419
  stepTextBuffer += textChunk;
313
420
  }
@@ -322,7 +429,7 @@ var addGptRoutes = function (router, options) {
322
429
  },
323
430
  }), "\n\n"));
324
431
  // Persist tool call in history
325
- history.prompts.push({
432
+ history_1.prompts.push({
326
433
  args: part.input,
327
434
  text: "Tool call: ".concat(part.toolName),
328
435
  toolCallId: part.toolCallId,
@@ -336,8 +443,8 @@ var addGptRoutes = function (router, options) {
336
443
  if ((toolResult === null || toolResult === void 0 ? void 0 : toolResult.fileData) && typeof toolResult.fileData === "string") {
337
444
  res.write("data: ".concat(JSON.stringify({
338
445
  file: {
339
- filename: (_r = toolResult.filename) !== null && _r !== void 0 ? _r : "document",
340
- mimeType: (_s = toolResult.mimeType) !== null && _s !== void 0 ? _s : "application/octet-stream",
446
+ filename: (_s = toolResult.filename) !== null && _s !== void 0 ? _s : "document",
447
+ mimeType: (_t = toolResult.mimeType) !== null && _t !== void 0 ? _t : "application/octet-stream",
341
448
  url: toolResult.fileData,
342
449
  },
343
450
  }), "\n\n"));
@@ -346,7 +453,7 @@ var addGptRoutes = function (router, options) {
346
453
  mimeType: toolResult.mimeType,
347
454
  });
348
455
  }
349
- _f = toolResult !== null && toolResult !== void 0 ? toolResult : {}, _fileData = _f.fileData, cleanResult = __rest(_f, ["fileData"]);
456
+ _g = toolResult !== null && toolResult !== void 0 ? toolResult : {}, _fileData = _g.fileData, cleanResult = __rest(_g, ["fileData"]);
350
457
  res.write("data: ".concat(JSON.stringify({
351
458
  toolResult: {
352
459
  result: cleanResult,
@@ -355,7 +462,7 @@ var addGptRoutes = function (router, options) {
355
462
  },
356
463
  }), "\n\n"));
357
464
  // Persist tool result in history (without the large file data)
358
- history.prompts.push({
465
+ history_1.prompts.push({
359
466
  result: cleanResult,
360
467
  text: "Tool result: ".concat(part.toolName),
361
468
  toolCallId: part.toolCallId,
@@ -363,28 +470,28 @@ var addGptRoutes = function (router, options) {
363
470
  type: "tool-result",
364
471
  });
365
472
  }
366
- _t.label = 12;
367
- case 12:
368
- _c = true;
369
- return [3 /*break*/, 10];
370
- case 13: return [3 /*break*/, 20];
371
- case 14:
372
- e_1_1 = _t.sent();
473
+ _u.label = 17;
474
+ case 17:
475
+ _d = true;
476
+ return [3 /*break*/, 15];
477
+ case 18: return [3 /*break*/, 25];
478
+ case 19:
479
+ e_1_1 = _u.sent();
373
480
  e_1 = { error: e_1_1 };
374
- return [3 /*break*/, 20];
375
- case 15:
376
- _t.trys.push([15, , 18, 19]);
377
- if (!(!_c && !_j && (_k = _d.return))) return [3 /*break*/, 17];
378
- return [4 /*yield*/, _k.call(_d)];
379
- case 16:
380
- _t.sent();
381
- _t.label = 17;
382
- case 17: return [3 /*break*/, 19];
383
- case 18:
481
+ return [3 /*break*/, 25];
482
+ case 20:
483
+ _u.trys.push([20, , 23, 24]);
484
+ if (!(!_d && !_k && (_l = _e.return))) return [3 /*break*/, 22];
485
+ return [4 /*yield*/, _l.call(_e)];
486
+ case 21:
487
+ _u.sent();
488
+ _u.label = 22;
489
+ case 22: return [3 /*break*/, 24];
490
+ case 23:
384
491
  if (e_1) throw e_1.error;
385
492
  return [7 /*endfinally*/];
386
- case 19: return [7 /*endfinally*/];
387
- case 20:
493
+ case 24: return [7 /*endfinally*/];
494
+ case 25:
388
495
  // Flush any remaining buffered text from the last step
389
496
  if (!stepHasToolCall && stepTextBuffer) {
390
497
  cleaned = stepTextBuffer.replace(/\{[\s\S]*?"action"[\s\S]*?\}\s*$/g, "").trim();
@@ -394,12 +501,12 @@ var addGptRoutes = function (router, options) {
394
501
  }
395
502
  }
396
503
  api_1.logger.debug("Stream completed", { fullResponseLength: fullResponse.length, partCount: partCount });
397
- _t.label = 21;
398
- case 21:
399
- _t.trys.push([21, 23, , 24]);
504
+ _u.label = 26;
505
+ case 26:
506
+ _u.trys.push([26, 28, , 29]);
400
507
  return [4 /*yield*/, result.files];
401
- case 22:
402
- files = _t.sent();
508
+ case 27:
509
+ files = _u.sent();
403
510
  if (files && files.length > 0) {
404
511
  try {
405
512
  for (files_1 = __values(files), files_1_1 = files_1.next(); !files_1_1.done; files_1_1 = files_1.next()) {
@@ -416,20 +523,20 @@ var addGptRoutes = function (router, options) {
416
523
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
417
524
  finally {
418
525
  try {
419
- if (files_1_1 && !files_1_1.done && (_h = files_1.return)) _h.call(files_1);
526
+ if (files_1_1 && !files_1_1.done && (_j = files_1.return)) _j.call(files_1);
420
527
  }
421
528
  finally { if (e_3) throw e_3.error; }
422
529
  }
423
530
  api_1.logger.debug("Sent generated images", { count: files.length });
424
531
  }
425
- return [3 /*break*/, 24];
426
- case 23:
427
- fileErr_1 = _t.sent();
532
+ return [3 /*break*/, 29];
533
+ case 28:
534
+ fileErr_1 = _u.sent();
428
535
  api_1.logger.debug("No files in response", {
429
536
  error: fileErr_1 instanceof Error ? fileErr_1.message : String(fileErr_1),
430
537
  });
431
- return [3 /*break*/, 24];
432
- case 24:
538
+ return [3 /*break*/, 29];
539
+ case 29:
433
540
  // Save assistant response to history
434
541
  if (fullResponse || generatedImages.length > 0) {
435
542
  contentParts_1 = generatedImages.map(function (img) { return ({
@@ -438,72 +545,105 @@ var addGptRoutes = function (router, options) {
438
545
  url: img.url,
439
546
  }); });
440
547
  assistantPrompt = __assign({ model: aiService.modelId, text: fullResponse || "(image)", type: "assistant" }, (contentParts_1.length > 0 ? { content: contentParts_1 } : {}));
441
- history.prompts.push(assistantPrompt);
548
+ history_1.prompts.push(assistantPrompt);
442
549
  }
443
- return [4 /*yield*/, history.save()];
444
- case 25:
445
- _t.sent();
446
- _t.label = 26;
447
- case 26:
448
- _t.trys.push([26, 28, , 29]);
550
+ return [4 /*yield*/, history_1.save()];
551
+ case 30:
552
+ _u.sent();
553
+ _u.label = 31;
554
+ case 31:
555
+ _u.trys.push([31, 33, , 34]);
449
556
  return [4 /*yield*/, aiRequest_1.AIRequest.logRequest({
450
557
  aiModel: modelId !== null && modelId !== void 0 ? modelId : "unknown",
451
- prompt: prompt,
558
+ prompt: prompt_1,
452
559
  requestType: "general",
453
560
  response: fullResponse,
454
561
  responseTime: Date.now() - startTime,
455
562
  userId: userId !== null && userId !== void 0 ? userId : undefined,
456
563
  })];
457
- case 27:
458
- _t.sent();
459
- return [3 /*break*/, 29];
460
- case 28:
461
- logErr_1 = _t.sent();
564
+ case 32:
565
+ _u.sent();
566
+ return [3 /*break*/, 34];
567
+ case 33:
568
+ logErr_1 = _u.sent();
462
569
  api_1.logger.warn("Failed to log AIRequest", {
463
570
  error: logErr_1 instanceof Error ? logErr_1.message : String(logErr_1),
464
571
  });
465
- return [3 /*break*/, 29];
466
- case 29:
572
+ return [3 /*break*/, 34];
573
+ case 34:
574
+ if (!(!history_1.title && fullResponse)) return [3 /*break*/, 37];
575
+ perRequestApiKey = req.headers["x-ai-api-key"];
576
+ return [4 /*yield*/, generateTitle(prompt_1, fullResponse, aiService, options, perRequestApiKey)];
577
+ case 35:
578
+ title = _u.sent();
579
+ if (!title) return [3 /*break*/, 37];
580
+ history_1.title = title;
581
+ return [4 /*yield*/, history_1.save()];
582
+ case 36:
583
+ _u.sent();
584
+ _u.label = 37;
585
+ case 37:
467
586
  api_1.logger.debug("Sending done event", {
468
587
  fullResponseLength: fullResponse.length,
469
- historyId: history._id.toString(),
588
+ historyId: history_1._id.toString(),
470
589
  });
471
- res.write("data: ".concat(JSON.stringify({ done: true, historyId: history._id.toString() }), "\n\n"));
590
+ res.write("data: ".concat(JSON.stringify(__assign({ done: true, historyId: history_1._id.toString() }, (history_1.title ? { title: history_1.title } : {}))), "\n\n"));
472
591
  res.end();
473
- return [3 /*break*/, 35];
474
- case 30:
475
- error_1 = _t.sent();
592
+ return [3 /*break*/, 43];
593
+ case 38:
594
+ error_1 = _u.sent();
476
595
  api_1.logger.error("Error in GPT stream", {
477
596
  error: error_1 instanceof Error ? error_1.message : String(error_1),
478
597
  });
479
- _t.label = 31;
480
- case 31:
481
- _t.trys.push([31, 33, , 34]);
598
+ _u.label = 39;
599
+ case 39:
600
+ _u.trys.push([39, 41, , 42]);
482
601
  return [4 /*yield*/, aiRequest_1.AIRequest.logRequest({
483
602
  aiModel: modelId !== null && modelId !== void 0 ? modelId : "unknown",
484
603
  error: error_1 instanceof Error ? error_1.message : String(error_1),
485
- prompt: prompt,
604
+ prompt: prompt_1,
486
605
  requestType: "general",
487
606
  responseTime: Date.now() - startTime,
488
607
  userId: userId !== null && userId !== void 0 ? userId : undefined,
489
608
  })];
490
- case 32:
491
- _t.sent();
492
- return [3 /*break*/, 34];
493
- case 33:
494
- logErr_2 = _t.sent();
609
+ case 40:
610
+ _u.sent();
611
+ return [3 /*break*/, 42];
612
+ case 41:
613
+ logErr_2 = _u.sent();
495
614
  api_1.logger.warn("Failed to log AIRequest error", {
496
615
  error: logErr_2 instanceof Error ? logErr_2.message : String(logErr_2),
497
616
  });
498
- return [3 /*break*/, 34];
499
- case 34:
617
+ return [3 /*break*/, 42];
618
+ case 42:
500
619
  res.write("data: ".concat(JSON.stringify({ error: error_1 instanceof Error ? error_1.message : "Unknown error" }), "\n\n"));
501
620
  res.end();
502
- return [3 /*break*/, 35];
503
- case 35: return [2 /*return*/];
621
+ return [3 /*break*/, 43];
622
+ case 43: return [3 /*break*/, 45];
623
+ case 44:
624
+ outerError_1 = _u.sent();
625
+ message = outerError_1 instanceof Error ? outerError_1.message : String(outerError_1);
626
+ status_1 = outerError_1 instanceof api_1.APIError ? outerError_1.status : 500;
627
+ stack = outerError_1 instanceof Error ? outerError_1.stack : undefined;
628
+ api_1.logger.error("GPT prompt handler error", { error: message, stack: stack, status: status_1 });
629
+ if (sseStarted) {
630
+ // Already sent SSE headers — send error as SSE event
631
+ res.write("data: ".concat(JSON.stringify({ error: message }), "\n\n"));
632
+ res.end();
633
+ }
634
+ else {
635
+ // Haven't started SSE — send a normal JSON error response
636
+ res.status(status_1).json({
637
+ detail: message,
638
+ status: status_1,
639
+ title: outerError_1 instanceof api_1.APIError ? outerError_1.title : "Internal server error",
640
+ });
641
+ }
642
+ return [3 /*break*/, 45];
643
+ case 45: return [2 /*return*/];
504
644
  }
505
645
  });
506
- }); }));
646
+ }); });
507
647
  router.patch("/gpt/histories/:id/rating", [
508
648
  (0, api_1.authenticateMiddleware)(),
509
649
  (0, api_1.createOpenApiBuilder)((_b = options.openApiOptions) !== null && _b !== void 0 ? _b : {})
@@ -589,5 +729,105 @@ var addGptRoutes = function (router, options) {
589
729
  }
590
730
  });
591
731
  }); }));
732
+ router.get("/gpt/tools", [
733
+ (0, api_1.authenticateMiddleware)(),
734
+ (0, api_1.createOpenApiBuilder)((_d = options.openApiOptions) !== null && _d !== void 0 ? _d : {})
735
+ .withTags(["gpt"])
736
+ .withSummary("List available AI tools")
737
+ .withResponse(200, {
738
+ data: {
739
+ items: {
740
+ properties: {
741
+ description: { type: "string" },
742
+ name: { type: "string" },
743
+ source: { type: "string" },
744
+ },
745
+ type: "object",
746
+ },
747
+ type: "array",
748
+ },
749
+ })
750
+ .build(),
751
+ ], (0, api_1.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
752
+ var tools, _a, _b, _c, name_1, t, requestTools, _d, _e, _f, name_2, t, mcpTools, _g, _h, _j, name_3, t, _k;
753
+ var e_4, _l, e_5, _m, e_6, _o;
754
+ var _p, _q, _r;
755
+ return __generator(this, function (_s) {
756
+ switch (_s.label) {
757
+ case 0:
758
+ tools = [];
759
+ // Static tools from route config
760
+ if (routeTools) {
761
+ try {
762
+ for (_a = __values(Object.entries(routeTools)), _b = _a.next(); !_b.done; _b = _a.next()) {
763
+ _c = __read(_b.value, 2), name_1 = _c[0], t = _c[1];
764
+ tools.push({
765
+ description: (_p = t.description) !== null && _p !== void 0 ? _p : "",
766
+ name: name_1,
767
+ source: "builtin",
768
+ });
769
+ }
770
+ }
771
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
772
+ finally {
773
+ try {
774
+ if (_b && !_b.done && (_l = _a.return)) _l.call(_a);
775
+ }
776
+ finally { if (e_4) throw e_4.error; }
777
+ }
778
+ }
779
+ // Per-request tools
780
+ if (createRequestTools) {
781
+ requestTools = createRequestTools(req);
782
+ try {
783
+ for (_d = __values(Object.entries(requestTools)), _e = _d.next(); !_e.done; _e = _d.next()) {
784
+ _f = __read(_e.value, 2), name_2 = _f[0], t = _f[1];
785
+ tools.push({
786
+ description: (_q = t.description) !== null && _q !== void 0 ? _q : "",
787
+ name: name_2,
788
+ source: "builtin",
789
+ });
790
+ }
791
+ }
792
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
793
+ finally {
794
+ try {
795
+ if (_e && !_e.done && (_m = _d.return)) _m.call(_d);
796
+ }
797
+ finally { if (e_5) throw e_5.error; }
798
+ }
799
+ }
800
+ if (!mcpService) return [3 /*break*/, 4];
801
+ _s.label = 1;
802
+ case 1:
803
+ _s.trys.push([1, 3, , 4]);
804
+ return [4 /*yield*/, mcpService.getTools()];
805
+ case 2:
806
+ mcpTools = _s.sent();
807
+ try {
808
+ for (_g = __values(Object.entries(mcpTools)), _h = _g.next(); !_h.done; _h = _g.next()) {
809
+ _j = __read(_h.value, 2), name_3 = _j[0], t = _j[1];
810
+ tools.push({
811
+ description: (_r = t.description) !== null && _r !== void 0 ? _r : "",
812
+ name: name_3,
813
+ source: "mcp",
814
+ });
815
+ }
816
+ }
817
+ catch (e_6_1) { e_6 = { error: e_6_1 }; }
818
+ finally {
819
+ try {
820
+ if (_h && !_h.done && (_o = _g.return)) _o.call(_g);
821
+ }
822
+ finally { if (e_6) throw e_6.error; }
823
+ }
824
+ return [3 /*break*/, 4];
825
+ case 3:
826
+ _k = _s.sent();
827
+ return [3 /*break*/, 4];
828
+ case 4: return [2 /*return*/, res.json({ data: tools })];
829
+ }
830
+ });
831
+ }); }));
592
832
  };
593
833
  exports.addGptRoutes = addGptRoutes;