@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.
Files changed (81) hide show
  1. package/.claude/CLAUDE.local.md +208 -0
  2. package/.cursor/rules/00-root.mdc +342 -0
  3. package/.cursorrules +221 -0
  4. package/.github/copilot-instructions.md +337 -0
  5. package/AGENTS.md +337 -0
  6. package/biome.jsonc +20 -0
  7. package/bunfig.toml +3 -0
  8. package/dist/aiApp.d.ts +59 -0
  9. package/dist/aiApp.js +67 -0
  10. package/dist/index.d.ts +6 -0
  11. package/dist/index.js +23 -0
  12. package/dist/models/aiRequest.d.ts +2 -0
  13. package/dist/models/aiRequest.js +76 -0
  14. package/dist/models/aiRequest.test.d.ts +1 -0
  15. package/dist/models/aiRequest.test.js +187 -0
  16. package/dist/models/fileAttachment.d.ts +2 -0
  17. package/dist/models/fileAttachment.js +25 -0
  18. package/dist/models/fileAttachment.test.d.ts +1 -0
  19. package/dist/models/fileAttachment.test.js +217 -0
  20. package/dist/models/gptHistory.d.ts +2 -0
  21. package/dist/models/gptHistory.js +56 -0
  22. package/dist/models/gptHistory.test.d.ts +1 -0
  23. package/dist/models/gptHistory.test.js +336 -0
  24. package/dist/models/index.d.ts +3 -0
  25. package/dist/models/index.js +9 -0
  26. package/dist/routes/aiRequestsExplorer.d.ts +2 -0
  27. package/dist/routes/aiRequestsExplorer.js +153 -0
  28. package/dist/routes/files.d.ts +5 -0
  29. package/dist/routes/files.js +168 -0
  30. package/dist/routes/gpt.d.ts +2 -0
  31. package/dist/routes/gpt.js +593 -0
  32. package/dist/routes/gptHistories.d.ts +3 -0
  33. package/dist/routes/gptHistories.js +29 -0
  34. package/dist/routes/index.d.ts +5 -0
  35. package/dist/routes/index.js +13 -0
  36. package/dist/routes/mcp.d.ts +2 -0
  37. package/dist/routes/mcp.js +133 -0
  38. package/dist/routes/routes.test.d.ts +1 -0
  39. package/dist/routes/routes.test.js +303 -0
  40. package/dist/service/aiService.d.ts +24 -0
  41. package/dist/service/aiService.js +453 -0
  42. package/dist/service/aiService.test.d.ts +1 -0
  43. package/dist/service/aiService.test.js +367 -0
  44. package/dist/service/fileStorage.d.ts +24 -0
  45. package/dist/service/fileStorage.js +143 -0
  46. package/dist/service/index.d.ts +4 -0
  47. package/dist/service/index.js +15 -0
  48. package/dist/service/mcpService.d.ts +14 -0
  49. package/dist/service/mcpService.js +271 -0
  50. package/dist/service/prompts.d.ts +4 -0
  51. package/dist/service/prompts.js +14 -0
  52. package/dist/tests/bunSetup.d.ts +1 -0
  53. package/dist/tests/bunSetup.js +227 -0
  54. package/dist/types/index.d.ts +170 -0
  55. package/dist/types/index.js +7 -0
  56. package/package.json +55 -0
  57. package/src/aiApp.ts +110 -0
  58. package/src/index.ts +6 -0
  59. package/src/models/aiRequest.test.ts +101 -0
  60. package/src/models/aiRequest.ts +45 -0
  61. package/src/models/fileAttachment.test.ts +119 -0
  62. package/src/models/fileAttachment.ts +31 -0
  63. package/src/models/gptHistory.test.ts +209 -0
  64. package/src/models/gptHistory.ts +71 -0
  65. package/src/models/index.ts +3 -0
  66. package/src/routes/aiRequestsExplorer.ts +107 -0
  67. package/src/routes/files.ts +128 -0
  68. package/src/routes/gpt.ts +503 -0
  69. package/src/routes/gptHistories.ts +31 -0
  70. package/src/routes/index.ts +5 -0
  71. package/src/routes/mcp.ts +76 -0
  72. package/src/routes/routes.test.ts +168 -0
  73. package/src/service/aiService.test.ts +242 -0
  74. package/src/service/aiService.ts +269 -0
  75. package/src/service/fileStorage.ts +74 -0
  76. package/src/service/index.ts +9 -0
  77. package/src/service/mcpService.ts +120 -0
  78. package/src/service/prompts.ts +18 -0
  79. package/src/tests/bunSetup.ts +163 -0
  80. package/src/types/index.ts +224 -0
  81. package/tsconfig.json +31 -0
@@ -0,0 +1,593 @@
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
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
50
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
51
+ var m = o[Symbol.asyncIterator], i;
52
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
53
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
54
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
55
+ };
56
+ var __rest = (this && this.__rest) || function (s, e) {
57
+ var t = {};
58
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
59
+ t[p] = s[p];
60
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
61
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
62
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
63
+ t[p[i]] = s[p[i]];
64
+ }
65
+ return t;
66
+ };
67
+ var __values = (this && this.__values) || function(o) {
68
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
69
+ if (m) return m.call(o);
70
+ if (o && typeof o.length === "number") return {
71
+ next: function () {
72
+ if (o && i >= o.length) o = void 0;
73
+ return { value: o && o[i++], done: !o };
74
+ }
75
+ };
76
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
77
+ };
78
+ Object.defineProperty(exports, "__esModule", { value: true });
79
+ exports.addGptRoutes = void 0;
80
+ var api_1 = require("@terreno/api");
81
+ var ai_1 = require("ai");
82
+ var aiRequest_1 = require("../models/aiRequest");
83
+ var gptHistory_1 = require("../models/gptHistory");
84
+ var aiService_1 = require("../service/aiService");
85
+ var DEMO_RESPONSE = "This is demo mode. To use AI features, paste your Gemini API key in Settings.";
86
+ /** Send a canned SSE demo response when no AI service is available. */
87
+ var sendDemoResponse = function (res, historyId) {
88
+ res.setHeader("Content-Type", "text/event-stream");
89
+ res.setHeader("Cache-Control", "no-cache");
90
+ res.setHeader("Connection", "keep-alive");
91
+ res.write("data: ".concat(JSON.stringify({ text: DEMO_RESPONSE }), "\n\n"));
92
+ res.write("data: ".concat(JSON.stringify(__assign({ done: true }, (historyId ? { historyId: historyId } : {}))), "\n\n"));
93
+ res.end();
94
+ };
95
+ /**
96
+ * Resolve the AIService for a request. Priority:
97
+ * 1. Per-request API key via `x-ai-api-key` header (creates a temporary AIService)
98
+ * 2. Pre-configured aiService from route options
99
+ * 3. undefined (triggers demo mode response)
100
+ */
101
+ var resolveAiService = function (req, options, modelId) {
102
+ var perRequestKey = req.headers["x-ai-api-key"];
103
+ if (perRequestKey && options.createModelFn) {
104
+ return new aiService_1.AIService({ model: options.createModelFn(perRequestKey, modelId) });
105
+ }
106
+ return options.aiService;
107
+ };
108
+ var addGptRoutes = function (router, options) {
109
+ var _a, _b, _c;
110
+ var mcpService = options.mcpService, routeTools = options.tools, createRequestTools = options.createRequestTools, toolChoice = options.toolChoice, maxSteps = options.maxSteps;
111
+ router.post("/gpt/prompt", [
112
+ (0, api_1.authenticateMiddleware)(),
113
+ (0, api_1.createOpenApiBuilder)((_a = options.openApiOptions) !== null && _a !== void 0 ? _a : {})
114
+ .withTags(["gpt"])
115
+ .withSummary("Stream a GPT chat response")
116
+ .withRequestBody({
117
+ attachments: {
118
+ items: {
119
+ properties: {
120
+ filename: { type: "string" },
121
+ mimeType: { type: "string" },
122
+ type: { type: "string" },
123
+ url: { type: "string" },
124
+ },
125
+ type: "object",
126
+ },
127
+ type: "array",
128
+ },
129
+ historyId: { type: "string" },
130
+ model: { type: "string" },
131
+ prompt: { type: "string" },
132
+ systemPrompt: { type: "string" },
133
+ })
134
+ .withResponse(200, { data: { type: "string" } })
135
+ .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) {
143
+ 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") {
147
+ throw new api_1.APIError({ status: 400, title: "prompt is required" });
148
+ }
149
+ hasPerRequestKey = !!req.headers["x-ai-api-key"];
150
+ hasCreateModelFn = !!options.createModelFn;
151
+ hasConfiguredService = !!options.aiService;
152
+ api_1.logger.debug("Resolving AI service", {
153
+ hasConfiguredService: hasConfiguredService,
154
+ hasCreateModelFn: hasCreateModelFn,
155
+ hasPerRequestKey: hasPerRequestKey,
156
+ });
157
+ aiService = resolveAiService(req, options, requestModel);
158
+ if (!aiService) {
159
+ api_1.logger.debug("No AI service available, sending demo response");
160
+ return [2 /*return*/, sendDemoResponse(res)];
161
+ }
162
+ if (!historyId) return [3 /*break*/, 2];
163
+ return [4 /*yield*/, gptHistory_1.GptHistory.findById(historyId)];
164
+ case 1:
165
+ history = _t.sent();
166
+ if (!history) {
167
+ throw new api_1.APIError({ status: 404, title: "History not found" });
168
+ }
169
+ if (history.userId.toString() !== (userId === null || userId === void 0 ? void 0 : userId.toString())) {
170
+ throw new api_1.APIError({ status: 403, title: "Not authorized to access this history" });
171
+ }
172
+ return [3 /*break*/, 3];
173
+ case 2:
174
+ history = new gptHistory_1.GptHistory({ prompts: [], userId: userId });
175
+ _t.label = 3;
176
+ case 3:
177
+ contentParts = [{ text: prompt, type: "text" }];
178
+ if (attachments && Array.isArray(attachments)) {
179
+ try {
180
+ for (attachments_1 = __values(attachments), attachments_1_1 = attachments_1.next(); !attachments_1_1.done; attachments_1_1 = attachments_1.next()) {
181
+ attachment = attachments_1_1.value;
182
+ if (attachment.type === "image") {
183
+ contentParts.push({
184
+ mimeType: attachment.mimeType,
185
+ type: "image",
186
+ url: attachment.url,
187
+ });
188
+ }
189
+ else if (attachment.type === "file") {
190
+ contentParts.push({
191
+ filename: attachment.filename,
192
+ mimeType: attachment.mimeType,
193
+ type: "file",
194
+ url: attachment.url,
195
+ });
196
+ }
197
+ }
198
+ }
199
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
200
+ finally {
201
+ try {
202
+ if (attachments_1_1 && !attachments_1_1.done && (_g = attachments_1.return)) _g.call(attachments_1);
203
+ }
204
+ finally { if (e_2) throw e_2.error; }
205
+ }
206
+ }
207
+ 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);
211
+ modelId = aiService.modelId;
212
+ supportsTools = !(modelId === null || modelId === void 0 ? void 0 : modelId.includes("image"));
213
+ requestTools = createRequestTools ? createRequestTools(req) : undefined;
214
+ if (!(supportsTools && (routeTools || requestTools || mcpService))) return [3 /*break*/, 7];
215
+ 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]);
220
+ return [4 /*yield*/, mcpService.getTools()];
221
+ case 5:
222
+ mcpTools = _t.sent();
223
+ Object.assign(allTools, mcpTools);
224
+ return [3 /*break*/, 7];
225
+ case 6:
226
+ _b = _t.sent();
227
+ return [3 /*break*/, 7];
228
+ case 7:
229
+ // Stream response via SSE
230
+ res.setHeader("Content-Type", "text/event-stream");
231
+ res.setHeader("Cache-Control", "no-cache");
232
+ res.setHeader("Connection", "keep-alive");
233
+ fullResponse = "";
234
+ generatedImages = [];
235
+ startTime = Date.now();
236
+ _t.label = 8;
237
+ case 8:
238
+ _t.trys.push([8, 30, , 35]);
239
+ api_1.logger.debug("Starting streamText", { model: modelId, supportsTools: supportsTools });
240
+ result = (0, ai_1.streamText)({
241
+ messages: messages,
242
+ model: aiService.model,
243
+ providerOptions: !supportsTools
244
+ ? { google: { responseModalities: ["TEXT", "IMAGE"] } }
245
+ : undefined,
246
+ 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,
248
+ temperature: aiService.defaultTemperature,
249
+ toolChoice: allTools ? (toolChoice !== null && toolChoice !== void 0 ? toolChoice : "auto") : undefined,
250
+ tools: allTools,
251
+ });
252
+ partCount = 0;
253
+ stepTextBuffer = "";
254
+ 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;
266
+ partCount++;
267
+ 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) } : {})));
269
+ }
270
+ // Track step boundaries to discard reasoning text from tool-call steps
271
+ if (part.type === "start-step") {
272
+ stepTextBuffer = "";
273
+ stepHasToolCall = false;
274
+ return [3 /*break*/, 12];
275
+ }
276
+ if (part.type === "finish-step") {
277
+ // Only emit buffered text if no tool call happened in this step
278
+ if (!stepHasToolCall && stepTextBuffer) {
279
+ cleaned = stepTextBuffer
280
+ .replace(/\{[\s\S]*?"action"[\s\S]*?\}\s*$/g, "")
281
+ .trim();
282
+ if (cleaned) {
283
+ fullResponse += cleaned;
284
+ res.write("data: ".concat(JSON.stringify({ text: cleaned }), "\n\n"));
285
+ }
286
+ }
287
+ stepTextBuffer = "";
288
+ stepHasToolCall = false;
289
+ return [3 /*break*/, 12];
290
+ }
291
+ if (part.type === "error") {
292
+ errMsg = part.error instanceof Error
293
+ ? part.error.message
294
+ : String((_p = part.error) !== null && _p !== void 0 ? _p : "Unknown stream error");
295
+ api_1.logger.error("AI stream error part", { error: errMsg });
296
+ res.write("data: ".concat(JSON.stringify({ error: errMsg }), "\n\n"));
297
+ return [3 /*break*/, 12];
298
+ }
299
+ if (part.type === "file") {
300
+ mediaType = part.mediaType;
301
+ if (mediaType === null || mediaType === void 0 ? void 0 : mediaType.startsWith("image/")) {
302
+ dataUrl = "data:".concat(mediaType, ";base64,").concat(part.base64);
303
+ generatedImages.push({ mimeType: mediaType, url: dataUrl });
304
+ res.write("data: ".concat(JSON.stringify({ image: { mimeType: mediaType, url: dataUrl } }), "\n\n"));
305
+ api_1.logger.debug("Sent inline image from stream");
306
+ }
307
+ return [3 /*break*/, 12];
308
+ }
309
+ if (part.type === "text-delta") {
310
+ textChunk = ((_q = part.text) !== null && _q !== void 0 ? _q : "");
311
+ if (textChunk) {
312
+ stepTextBuffer += textChunk;
313
+ }
314
+ }
315
+ else if (part.type === "tool-call") {
316
+ stepHasToolCall = true;
317
+ res.write("data: ".concat(JSON.stringify({
318
+ toolCall: {
319
+ args: part.input,
320
+ toolCallId: part.toolCallId,
321
+ toolName: part.toolName,
322
+ },
323
+ }), "\n\n"));
324
+ // Persist tool call in history
325
+ history.prompts.push({
326
+ args: part.input,
327
+ text: "Tool call: ".concat(part.toolName),
328
+ toolCallId: part.toolCallId,
329
+ toolName: part.toolName,
330
+ type: "tool-call",
331
+ });
332
+ }
333
+ else if (part.type === "tool-result") {
334
+ toolResult = part.output;
335
+ // If the tool result contains file data, send it as a separate file SSE event
336
+ if ((toolResult === null || toolResult === void 0 ? void 0 : toolResult.fileData) && typeof toolResult.fileData === "string") {
337
+ res.write("data: ".concat(JSON.stringify({
338
+ 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",
341
+ url: toolResult.fileData,
342
+ },
343
+ }), "\n\n"));
344
+ api_1.logger.debug("Sent generated file from tool result", {
345
+ filename: toolResult.filename,
346
+ mimeType: toolResult.mimeType,
347
+ });
348
+ }
349
+ _f = toolResult !== null && toolResult !== void 0 ? toolResult : {}, _fileData = _f.fileData, cleanResult = __rest(_f, ["fileData"]);
350
+ res.write("data: ".concat(JSON.stringify({
351
+ toolResult: {
352
+ result: cleanResult,
353
+ toolCallId: part.toolCallId,
354
+ toolName: part.toolName,
355
+ },
356
+ }), "\n\n"));
357
+ // Persist tool result in history (without the large file data)
358
+ history.prompts.push({
359
+ result: cleanResult,
360
+ text: "Tool result: ".concat(part.toolName),
361
+ toolCallId: part.toolCallId,
362
+ toolName: part.toolName,
363
+ type: "tool-result",
364
+ });
365
+ }
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();
373
+ 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:
384
+ if (e_1) throw e_1.error;
385
+ return [7 /*endfinally*/];
386
+ case 19: return [7 /*endfinally*/];
387
+ case 20:
388
+ // Flush any remaining buffered text from the last step
389
+ if (!stepHasToolCall && stepTextBuffer) {
390
+ cleaned = stepTextBuffer.replace(/\{[\s\S]*?"action"[\s\S]*?\}\s*$/g, "").trim();
391
+ if (cleaned) {
392
+ fullResponse += cleaned;
393
+ res.write("data: ".concat(JSON.stringify({ text: cleaned }), "\n\n"));
394
+ }
395
+ }
396
+ 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]);
400
+ return [4 /*yield*/, result.files];
401
+ case 22:
402
+ files = _t.sent();
403
+ if (files && files.length > 0) {
404
+ try {
405
+ for (files_1 = __values(files), files_1_1 = files_1.next(); !files_1_1.done; files_1_1 = files_1.next()) {
406
+ file = files_1_1.value;
407
+ if (file.mediaType.startsWith("image/")) {
408
+ dataUrl = "data:".concat(file.mediaType, ";base64,").concat(file.base64);
409
+ generatedImages.push({ mimeType: file.mediaType, url: dataUrl });
410
+ res.write("data: ".concat(JSON.stringify({
411
+ image: { mimeType: file.mediaType, url: dataUrl },
412
+ }), "\n\n"));
413
+ }
414
+ }
415
+ }
416
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
417
+ finally {
418
+ try {
419
+ if (files_1_1 && !files_1_1.done && (_h = files_1.return)) _h.call(files_1);
420
+ }
421
+ finally { if (e_3) throw e_3.error; }
422
+ }
423
+ api_1.logger.debug("Sent generated images", { count: files.length });
424
+ }
425
+ return [3 /*break*/, 24];
426
+ case 23:
427
+ fileErr_1 = _t.sent();
428
+ api_1.logger.debug("No files in response", {
429
+ error: fileErr_1 instanceof Error ? fileErr_1.message : String(fileErr_1),
430
+ });
431
+ return [3 /*break*/, 24];
432
+ case 24:
433
+ // Save assistant response to history
434
+ if (fullResponse || generatedImages.length > 0) {
435
+ contentParts_1 = generatedImages.map(function (img) { return ({
436
+ mimeType: img.mimeType,
437
+ type: "image",
438
+ url: img.url,
439
+ }); });
440
+ assistantPrompt = __assign({ model: aiService.modelId, text: fullResponse || "(image)", type: "assistant" }, (contentParts_1.length > 0 ? { content: contentParts_1 } : {}));
441
+ history.prompts.push(assistantPrompt);
442
+ }
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]);
449
+ return [4 /*yield*/, aiRequest_1.AIRequest.logRequest({
450
+ aiModel: modelId !== null && modelId !== void 0 ? modelId : "unknown",
451
+ prompt: prompt,
452
+ requestType: "general",
453
+ response: fullResponse,
454
+ responseTime: Date.now() - startTime,
455
+ userId: userId !== null && userId !== void 0 ? userId : undefined,
456
+ })];
457
+ case 27:
458
+ _t.sent();
459
+ return [3 /*break*/, 29];
460
+ case 28:
461
+ logErr_1 = _t.sent();
462
+ api_1.logger.warn("Failed to log AIRequest", {
463
+ error: logErr_1 instanceof Error ? logErr_1.message : String(logErr_1),
464
+ });
465
+ return [3 /*break*/, 29];
466
+ case 29:
467
+ api_1.logger.debug("Sending done event", {
468
+ fullResponseLength: fullResponse.length,
469
+ historyId: history._id.toString(),
470
+ });
471
+ res.write("data: ".concat(JSON.stringify({ done: true, historyId: history._id.toString() }), "\n\n"));
472
+ res.end();
473
+ return [3 /*break*/, 35];
474
+ case 30:
475
+ error_1 = _t.sent();
476
+ api_1.logger.error("Error in GPT stream", {
477
+ error: error_1 instanceof Error ? error_1.message : String(error_1),
478
+ });
479
+ _t.label = 31;
480
+ case 31:
481
+ _t.trys.push([31, 33, , 34]);
482
+ return [4 /*yield*/, aiRequest_1.AIRequest.logRequest({
483
+ aiModel: modelId !== null && modelId !== void 0 ? modelId : "unknown",
484
+ error: error_1 instanceof Error ? error_1.message : String(error_1),
485
+ prompt: prompt,
486
+ requestType: "general",
487
+ responseTime: Date.now() - startTime,
488
+ userId: userId !== null && userId !== void 0 ? userId : undefined,
489
+ })];
490
+ case 32:
491
+ _t.sent();
492
+ return [3 /*break*/, 34];
493
+ case 33:
494
+ logErr_2 = _t.sent();
495
+ api_1.logger.warn("Failed to log AIRequest error", {
496
+ error: logErr_2 instanceof Error ? logErr_2.message : String(logErr_2),
497
+ });
498
+ return [3 /*break*/, 34];
499
+ case 34:
500
+ res.write("data: ".concat(JSON.stringify({ error: error_1 instanceof Error ? error_1.message : "Unknown error" }), "\n\n"));
501
+ res.end();
502
+ return [3 /*break*/, 35];
503
+ case 35: return [2 /*return*/];
504
+ }
505
+ });
506
+ }); }));
507
+ router.patch("/gpt/histories/:id/rating", [
508
+ (0, api_1.authenticateMiddleware)(),
509
+ (0, api_1.createOpenApiBuilder)((_b = options.openApiOptions) !== null && _b !== void 0 ? _b : {})
510
+ .withTags(["gpt"])
511
+ .withSummary("Rate a prompt in a GPT history")
512
+ .withPathParameter("id", { type: "string" })
513
+ .withRequestBody({
514
+ promptIndex: { type: "number" },
515
+ rating: { type: "string" },
516
+ })
517
+ .withResponse(200, { data: { type: "object" } })
518
+ .build(),
519
+ ], (0, api_1.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
520
+ var id, _a, promptIndex, rating, userId, history;
521
+ var _b, _c;
522
+ return __generator(this, function (_d) {
523
+ switch (_d.label) {
524
+ case 0:
525
+ id = req.params.id;
526
+ _a = req.body, promptIndex = _a.promptIndex, rating = _a.rating;
527
+ userId = (_b = req.user) === null || _b === void 0 ? void 0 : _b._id;
528
+ if (typeof promptIndex !== "number" || promptIndex < 0) {
529
+ throw new api_1.APIError({ status: 400, title: "promptIndex must be a non-negative number" });
530
+ }
531
+ if (rating !== null && rating !== "up" && rating !== "down") {
532
+ throw new api_1.APIError({ status: 400, title: "rating must be 'up', 'down', or null" });
533
+ }
534
+ return [4 /*yield*/, gptHistory_1.GptHistory.findById(id)];
535
+ case 1:
536
+ history = _d.sent();
537
+ if (!history) {
538
+ throw new api_1.APIError({ status: 404, title: "History not found" });
539
+ }
540
+ if (history.userId.toString() !== (userId === null || userId === void 0 ? void 0 : userId.toString())) {
541
+ throw new api_1.APIError({ status: 403, title: "Not authorized to access this history" });
542
+ }
543
+ if (promptIndex >= history.prompts.length) {
544
+ throw new api_1.APIError({ status: 400, title: "promptIndex out of range" });
545
+ }
546
+ if (rating === null) {
547
+ history.prompts[promptIndex].rating = undefined;
548
+ }
549
+ else {
550
+ history.prompts[promptIndex].rating = rating;
551
+ }
552
+ history.markModified("prompts");
553
+ return [4 /*yield*/, history.save()];
554
+ case 2:
555
+ _d.sent();
556
+ return [2 /*return*/, res.json({ data: { promptIndex: promptIndex, rating: (_c = history.prompts[promptIndex].rating) !== null && _c !== void 0 ? _c : null } })];
557
+ }
558
+ });
559
+ }); }));
560
+ router.post("/gpt/remix", [
561
+ (0, api_1.authenticateMiddleware)(),
562
+ (0, api_1.createOpenApiBuilder)((_c = options.openApiOptions) !== null && _c !== void 0 ? _c : {})
563
+ .withTags(["gpt"])
564
+ .withSummary("Remix text")
565
+ .withRequestBody({
566
+ text: { type: "string" },
567
+ })
568
+ .withResponse(200, { data: { type: "string" } })
569
+ .build(),
570
+ ], (0, api_1.asyncHandler)(function (req, res) { return __awaiter(void 0, void 0, void 0, function () {
571
+ var text, userId, aiService, result;
572
+ var _a;
573
+ return __generator(this, function (_b) {
574
+ switch (_b.label) {
575
+ case 0:
576
+ text = req.body.text;
577
+ userId = (_a = req.user) === null || _a === void 0 ? void 0 : _a._id;
578
+ if (!text || typeof text !== "string") {
579
+ throw new api_1.APIError({ status: 400, title: "text is required" });
580
+ }
581
+ aiService = resolveAiService(req, options);
582
+ if (!aiService) {
583
+ return [2 /*return*/, res.json({ data: DEMO_RESPONSE })];
584
+ }
585
+ return [4 /*yield*/, aiService.generateRemix({ text: text, userId: userId })];
586
+ case 1:
587
+ result = _b.sent();
588
+ return [2 /*return*/, res.json({ data: result })];
589
+ }
590
+ });
591
+ }); }));
592
+ };
593
+ exports.addGptRoutes = addGptRoutes;
@@ -0,0 +1,3 @@
1
+ import { type ModelRouterOptions } from "@terreno/api";
2
+ import type { GptHistoryDocument, GptHistoryRouteOptions } from "../types";
3
+ export declare const addGptHistoryRoutes: (router: any, options?: Partial<ModelRouterOptions<GptHistoryDocument>> & GptHistoryRouteOptions) => void;
@@ -0,0 +1,29 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.addGptHistoryRoutes = void 0;
15
+ var api_1 = require("@terreno/api");
16
+ var gptHistory_1 = require("../models/gptHistory");
17
+ var addGptHistoryRoutes = function (router, options) {
18
+ router.use("/gpt/histories", (0, api_1.modelRouter)(gptHistory_1.GptHistory, __assign(__assign({}, options), { permissions: {
19
+ create: [api_1.Permissions.IsAuthenticated],
20
+ delete: [api_1.Permissions.IsOwner],
21
+ list: [api_1.Permissions.IsAuthenticated],
22
+ read: [api_1.Permissions.IsOwner],
23
+ update: [api_1.Permissions.IsOwner],
24
+ }, preCreate: function (body, req) {
25
+ var _a;
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" })));
28
+ };
29
+ exports.addGptHistoryRoutes = addGptHistoryRoutes;
@@ -0,0 +1,5 @@
1
+ export { addAiRequestsExplorerRoutes } from "./aiRequestsExplorer";
2
+ export { addFileRoutes } from "./files";
3
+ export { addGptRoutes } from "./gpt";
4
+ export { addGptHistoryRoutes } from "./gptHistories";
5
+ export { addMcpRoutes } from "./mcp";
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addMcpRoutes = exports.addGptHistoryRoutes = exports.addGptRoutes = exports.addFileRoutes = exports.addAiRequestsExplorerRoutes = void 0;
4
+ var aiRequestsExplorer_1 = require("./aiRequestsExplorer");
5
+ Object.defineProperty(exports, "addAiRequestsExplorerRoutes", { enumerable: true, get: function () { return aiRequestsExplorer_1.addAiRequestsExplorerRoutes; } });
6
+ var files_1 = require("./files");
7
+ Object.defineProperty(exports, "addFileRoutes", { enumerable: true, get: function () { return files_1.addFileRoutes; } });
8
+ var gpt_1 = require("./gpt");
9
+ Object.defineProperty(exports, "addGptRoutes", { enumerable: true, get: function () { return gpt_1.addGptRoutes; } });
10
+ var gptHistories_1 = require("./gptHistories");
11
+ Object.defineProperty(exports, "addGptHistoryRoutes", { enumerable: true, get: function () { return gptHistories_1.addGptHistoryRoutes; } });
12
+ var mcp_1 = require("./mcp");
13
+ Object.defineProperty(exports, "addMcpRoutes", { enumerable: true, get: function () { return mcp_1.addMcpRoutes; } });
@@ -0,0 +1,2 @@
1
+ import type { McpRouteOptions } from "../types";
2
+ export declare const addMcpRoutes: (router: any, options: McpRouteOptions) => void;