@terreno/ai 57.21.0 → 58.0.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +20 -18
- package/CHANGELOG.md +89 -0
- package/biome.jsonc +2 -2
- package/dist/aiApp.d.ts +5 -2
- package/dist/aiApp.js +3 -2
- package/dist/index.d.ts +1 -1
- package/dist/models/gptHistory.js +2 -0
- package/dist/routes/files.d.ts +7 -1
- package/dist/routes/files.js +62 -13
- package/dist/routes/gptHistories.js +8 -2
- package/dist/service/chatTurn.js +5 -0
- package/dist/service/vertex.d.ts +5 -2
- package/dist/types/index.d.ts +4 -0
- package/package.json +13 -12
- package/src/aiApp.test.ts +21 -1
- package/src/aiApp.ts +6 -3
- package/src/index.ts +1 -1
- package/src/isolated/gptStream.isolated.ts +2 -2
- package/src/models/gptHistory.test.ts +2 -2
- package/src/models/gptHistory.ts +9 -1
- package/src/routes/files.test.ts +121 -0
- package/src/routes/files.ts +90 -15
- package/src/routes/gpt.test.ts +14 -2
- package/src/routes/gptActions.test.ts +3 -3
- package/src/routes/gptApprovals.test.ts +1 -1
- package/src/routes/gptFiles.test.ts +1 -1
- package/src/routes/gptHistories.test.ts +2 -2
- package/src/routes/gptHistories.ts +59 -55
- package/src/routes/gptHistoriesSync.test.ts +230 -0
- package/src/routes/routes.test.ts +6 -5
- package/src/service/chatTurn.ts +5 -0
- package/src/service/vertex.test.ts +1 -1
- package/src/service/vertex.ts +7 -4
- package/src/types/index.ts +4 -0
package/src/index.ts
CHANGED
|
@@ -98,7 +98,7 @@ export {
|
|
|
98
98
|
validateObservabilityConfig,
|
|
99
99
|
} from "./observability/types";
|
|
100
100
|
export {addAiRequestsExplorerRoutes} from "./routes/aiRequestsExplorer";
|
|
101
|
-
export {addFileRoutes} from "./routes/files";
|
|
101
|
+
export {addFileRoutes, type FileStorageServiceSource} from "./routes/files";
|
|
102
102
|
export {addGptRoutes} from "./routes/gpt";
|
|
103
103
|
export {addGptHistoryRoutes} from "./routes/gptHistories";
|
|
104
104
|
export {addMcpRoutes} from "./routes/mcp";
|
|
@@ -83,7 +83,7 @@ describe("GPT prompt streaming edge cases", () => {
|
|
|
83
83
|
|
|
84
84
|
beforeAll(async () => {
|
|
85
85
|
await ensureTestUsers();
|
|
86
|
-
await GptHistory.deleteMany({});
|
|
86
|
+
await GptHistory.collection.deleteMany({});
|
|
87
87
|
const aiService = new AIService({
|
|
88
88
|
model: createMockModel() as unknown as LanguageModel,
|
|
89
89
|
});
|
|
@@ -97,7 +97,7 @@ describe("GPT prompt streaming edge cases", () => {
|
|
|
97
97
|
});
|
|
98
98
|
|
|
99
99
|
afterAll(async () => {
|
|
100
|
-
await GptHistory.deleteMany({});
|
|
100
|
+
await GptHistory.collection.deleteMany({});
|
|
101
101
|
});
|
|
102
102
|
|
|
103
103
|
it("emits an inline image and flushes buffered text with no finish-step", async () => {
|
|
@@ -6,11 +6,11 @@ import {GptHistory} from "./gptHistory";
|
|
|
6
6
|
|
|
7
7
|
describe("GptHistory Model", () => {
|
|
8
8
|
beforeEach(async () => {
|
|
9
|
-
await GptHistory.deleteMany({});
|
|
9
|
+
await GptHistory.collection.deleteMany({});
|
|
10
10
|
});
|
|
11
11
|
|
|
12
12
|
afterEach(async () => {
|
|
13
|
-
await GptHistory.deleteMany({});
|
|
13
|
+
await GptHistory.collection.deleteMany({});
|
|
14
14
|
});
|
|
15
15
|
|
|
16
16
|
describe("schema", () => {
|
package/src/models/gptHistory.ts
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
createdUpdatedPlugin,
|
|
3
|
+
findExactlyOne,
|
|
4
|
+
findOneOrNone,
|
|
5
|
+
isDeletedPlugin,
|
|
6
|
+
syncPlugin,
|
|
7
|
+
} from "@terreno/api";
|
|
2
8
|
import {ASK_KINDS} from "@terreno/blocks";
|
|
3
9
|
import mongoose from "mongoose";
|
|
4
10
|
|
|
@@ -185,6 +191,8 @@ gptHistorySchema.plugin(createdUpdatedPlugin);
|
|
|
185
191
|
gptHistorySchema.plugin(isDeletedPlugin);
|
|
186
192
|
gptHistorySchema.plugin(findOneOrNone);
|
|
187
193
|
gptHistorySchema.plugin(findExactlyOne);
|
|
194
|
+
// Stamps a per-stream _syncSeq on every write; required by the /gpt/histories sync config.
|
|
195
|
+
gptHistorySchema.plugin(syncPlugin);
|
|
188
196
|
|
|
189
197
|
// Virtual ownerId alias so Permissions.IsOwner works with userId field
|
|
190
198
|
gptHistorySchema.virtual("ownerId").get(function () {
|
package/src/routes/files.test.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import {beforeAll, beforeEach, describe, expect, it, mock} from "bun:test";
|
|
2
2
|
import {TerrenoApp} from "@terreno/api";
|
|
3
|
+
// The side-effect-free entry: `@terreno/api/testing` registers api's own test `User` model,
|
|
4
|
+
// which collides with this package's `User` when the whole suite shares one process.
|
|
5
|
+
import {expectDocumentedResponse, type OpenApiResponseSpec} from "@terreno/api/testing/openApi";
|
|
3
6
|
import type express from "express";
|
|
4
7
|
import type mongoose from "mongoose";
|
|
5
8
|
import supertest from "supertest";
|
|
@@ -221,4 +224,122 @@ describe("File Routes", () => {
|
|
|
221
224
|
expect(fileStorageService.delete as ReturnType<typeof mock>).not.toHaveBeenCalled();
|
|
222
225
|
});
|
|
223
226
|
});
|
|
227
|
+
describe("OpenAPI", () => {
|
|
228
|
+
it("documents POST /files/upload as multipart/form-data with the data envelope", async () => {
|
|
229
|
+
const res = await supertest(app).get("/openapi.json").expect(200);
|
|
230
|
+
const operation = res.body.paths["/files/upload"]?.post;
|
|
231
|
+
expect(operation?.tags).toEqual(["files"]);
|
|
232
|
+
expect(Object.keys(operation.requestBody.content)).toEqual(["multipart/form-data"]);
|
|
233
|
+
const requestSchema = operation.requestBody.content["multipart/form-data"].schema;
|
|
234
|
+
expect(requestSchema.required).toEqual(["file"]);
|
|
235
|
+
expect(requestSchema.properties.file.format).toBe("binary");
|
|
236
|
+
expect(requestSchema.properties.file.type).toBe("string");
|
|
237
|
+
const responseSchema = operation.responses["200"].content["application/json"].schema;
|
|
238
|
+
expect(responseSchema.required).toEqual(["data"]);
|
|
239
|
+
expect(responseSchema.properties.data.required).toEqual([
|
|
240
|
+
"filename",
|
|
241
|
+
"gcsKey",
|
|
242
|
+
"id",
|
|
243
|
+
"mimeType",
|
|
244
|
+
"size",
|
|
245
|
+
"url",
|
|
246
|
+
]);
|
|
247
|
+
|
|
248
|
+
// The generator keeps Express 5's `*gcsKey` wildcard as written, so find the key route.
|
|
249
|
+
const keyPath = Object.keys(res.body.paths).find(
|
|
250
|
+
(path) => path.startsWith("/files/") && path !== "/files/upload"
|
|
251
|
+
);
|
|
252
|
+
const keyRoute = res.body.paths[keyPath ?? ""];
|
|
253
|
+
interface SchemaNode {
|
|
254
|
+
properties: Record<string, SchemaNode & {type?: string}>;
|
|
255
|
+
}
|
|
256
|
+
const dataOf = (operation: {
|
|
257
|
+
responses: Record<string, {content: Record<string, {schema: SchemaNode}>}>;
|
|
258
|
+
}): SchemaNode =>
|
|
259
|
+
operation.responses["200"].content["application/json"].schema.properties.data;
|
|
260
|
+
expect(dataOf(keyRoute.get).properties.url.type).toBe("string");
|
|
261
|
+
expect(dataOf(keyRoute.delete).properties.success.type).toBe("boolean");
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
it("documents every field the upload returns", async () => {
|
|
265
|
+
const docs = await supertest(app).get("/openapi.json").expect(200);
|
|
266
|
+
const documented = Object.keys(
|
|
267
|
+
docs.body.paths["/files/upload"].post.responses["200"].content["application/json"].schema
|
|
268
|
+
.properties.data.properties
|
|
269
|
+
);
|
|
270
|
+
const agent = await authAsUser(app, "notAdmin");
|
|
271
|
+
const res = await agent
|
|
272
|
+
.post("/files/upload")
|
|
273
|
+
.attach("file", Buffer.from("hello"), {contentType: "text/plain", filename: "hi.txt"})
|
|
274
|
+
.expect(200);
|
|
275
|
+
expect(documented).toEqual(expect.arrayContaining(Object.keys(res.body.data)));
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
it("returns upload, read, and delete bodies that match the documented schemas", async () => {
|
|
279
|
+
const spec = (await supertest(app).get("/openapi.json").expect(200))
|
|
280
|
+
.body as OpenApiResponseSpec;
|
|
281
|
+
const keyPath = Object.keys(spec.paths ?? {}).find(
|
|
282
|
+
(path) => path.startsWith("/files/") && path !== "/files/upload"
|
|
283
|
+
);
|
|
284
|
+
expect(keyPath).toBeDefined();
|
|
285
|
+
const agent = await authAsUser(app, "notAdmin");
|
|
286
|
+
|
|
287
|
+
const uploaded = await agent
|
|
288
|
+
.post("/files/upload")
|
|
289
|
+
.attach("file", Buffer.from("hello"), {contentType: "text/plain", filename: "hi.txt"})
|
|
290
|
+
.expect(200);
|
|
291
|
+
expectDocumentedResponse({method: "post", path: "/files/upload", response: uploaded, spec});
|
|
292
|
+
|
|
293
|
+
const gcsKey = `uploads/${userId.toString()}/1727550000000-documented.txt`;
|
|
294
|
+
await FileAttachment.create({
|
|
295
|
+
filename: "documented.txt",
|
|
296
|
+
gcsKey,
|
|
297
|
+
mimeType: "text/plain",
|
|
298
|
+
size: 5,
|
|
299
|
+
url: "https://example.com/documented.txt",
|
|
300
|
+
userId,
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
const read = await agent.get(`/files/${gcsKey}`).expect(200);
|
|
304
|
+
expectDocumentedResponse({method: "get", path: keyPath ?? "", response: read, spec});
|
|
305
|
+
|
|
306
|
+
const deleted = await agent.delete(`/files/${gcsKey}`).expect(200);
|
|
307
|
+
expectDocumentedResponse({method: "delete", path: keyPath ?? "", response: deleted, spec});
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
describe("runtime-resolved storage", () => {
|
|
312
|
+
it("answers 503 while storage is unconfigured and uploads once it resolves", async () => {
|
|
313
|
+
let current: FileStorageService | undefined;
|
|
314
|
+
const runtimeApp = new TerrenoApp({
|
|
315
|
+
configureApp: (router, options) => {
|
|
316
|
+
addFileRoutes(router, {
|
|
317
|
+
fileStorageService: () => current,
|
|
318
|
+
gcsBucket: "",
|
|
319
|
+
openApiOptions: options,
|
|
320
|
+
});
|
|
321
|
+
},
|
|
322
|
+
skipListen: true,
|
|
323
|
+
userModel: terrenoUserModel,
|
|
324
|
+
}).build();
|
|
325
|
+
const agent = await authAsUser(runtimeApp, "notAdmin");
|
|
326
|
+
|
|
327
|
+
const docs = await supertest(runtimeApp).get("/openapi.json").expect(200);
|
|
328
|
+
expect(docs.body.paths["/files/upload"]?.post).toBeDefined();
|
|
329
|
+
|
|
330
|
+
const unconfigured = await agent
|
|
331
|
+
.post("/files/upload")
|
|
332
|
+
.attach("file", Buffer.from("hello"), {contentType: "text/plain", filename: "hi.txt"});
|
|
333
|
+
expect(unconfigured.status).toBe(503);
|
|
334
|
+
expect(unconfigured.body.title).toBe("File storage is not configured");
|
|
335
|
+
expect(fileStorageService.upload as ReturnType<typeof mock>).not.toHaveBeenCalled();
|
|
336
|
+
|
|
337
|
+
current = fileStorageService as FileStorageService;
|
|
338
|
+
const configured = await agent
|
|
339
|
+
.post("/files/upload")
|
|
340
|
+
.attach("file", Buffer.from("hello"), {contentType: "text/plain", filename: "hi.txt"});
|
|
341
|
+
expect(configured.status).toBe(200);
|
|
342
|
+
expect(fileStorageService.upload as ReturnType<typeof mock>).toHaveBeenCalledTimes(1);
|
|
343
|
+
});
|
|
344
|
+
});
|
|
224
345
|
});
|
package/src/routes/files.ts
CHANGED
|
@@ -30,11 +30,40 @@ const gcsKeyParam = (req: express.Request): string => {
|
|
|
30
30
|
const requestUserId = (req: express.Request): mongoose.Types.ObjectId =>
|
|
31
31
|
(req.user as {_id?: mongoose.Types.ObjectId} | undefined)?._id as mongoose.Types.ObjectId;
|
|
32
32
|
|
|
33
|
+
/**
|
|
34
|
+
* A storage service, or a function that returns the current one. Pass a function when storage
|
|
35
|
+
* can be configured or cleared at runtime: the routes stay mounted (and documented in OpenAPI)
|
|
36
|
+
* and answer 503 while it returns `undefined`.
|
|
37
|
+
*/
|
|
38
|
+
export type FileStorageServiceSource = FileStorageService | (() => FileStorageService | undefined);
|
|
39
|
+
|
|
40
|
+
const resolveFileStorageService = (source: FileStorageServiceSource): FileStorageService => {
|
|
41
|
+
const service = typeof source === "function" ? source() : source;
|
|
42
|
+
if (!service) {
|
|
43
|
+
throw new APIError({status: 503, title: "File storage is not configured"});
|
|
44
|
+
}
|
|
45
|
+
return service;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const uploadResultSchema = {
|
|
49
|
+
filename: {type: "string"},
|
|
50
|
+
gcsKey: {
|
|
51
|
+
description: "Storage key; GET or DELETE /files/<gcsKey> reads or removes the file",
|
|
52
|
+
type: "string",
|
|
53
|
+
},
|
|
54
|
+
id: {description: "The FileAttachment id", type: "string"},
|
|
55
|
+
mimeType: {type: "string"},
|
|
56
|
+
size: {description: "Size in bytes", type: "number"},
|
|
57
|
+
url: {type: "string"},
|
|
58
|
+
};
|
|
59
|
+
|
|
33
60
|
export const addFileRoutes = (
|
|
34
61
|
router: express.Router,
|
|
35
|
-
options: FileRouteOptions & {fileStorageService:
|
|
62
|
+
options: FileRouteOptions & {fileStorageService: FileStorageServiceSource}
|
|
36
63
|
): void => {
|
|
37
|
-
const {
|
|
64
|
+
const {maxFileSize = DEFAULT_MAX_FILE_SIZE} = options;
|
|
65
|
+
const fileStorageService = (): FileStorageService =>
|
|
66
|
+
resolveFileStorageService(options.fileStorageService);
|
|
38
67
|
|
|
39
68
|
const upload = multer({
|
|
40
69
|
fileFilter: (_req, file, cb) => {
|
|
@@ -52,22 +81,46 @@ export const addFileRoutes = (
|
|
|
52
81
|
"/files/upload",
|
|
53
82
|
[
|
|
54
83
|
authenticateMiddleware(),
|
|
84
|
+
// Fail before multer buffers the upload when no storage is configured.
|
|
85
|
+
(_req: express.Request, _res: express.Response, next: express.NextFunction): void => {
|
|
86
|
+
try {
|
|
87
|
+
fileStorageService();
|
|
88
|
+
next();
|
|
89
|
+
} catch (error) {
|
|
90
|
+
next(error);
|
|
91
|
+
}
|
|
92
|
+
},
|
|
55
93
|
upload.single("file"),
|
|
56
94
|
createOpenApiBuilder(options.openApiOptions ?? {})
|
|
57
95
|
.withTags(["files"])
|
|
58
96
|
.withSummary("Upload a file")
|
|
59
|
-
.
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
97
|
+
.withDescription(
|
|
98
|
+
`Send the file as multipart/form-data in the \`file\` field. Allowed types: ${[
|
|
99
|
+
...ALLOWED_MIME_TYPES,
|
|
100
|
+
].join(", ")}. Maximum size: ${maxFileSize} bytes.`
|
|
101
|
+
)
|
|
102
|
+
.withRequestBody(
|
|
103
|
+
{file: {format: "binary", required: true, type: "string"}},
|
|
104
|
+
{mediaType: "multipart/form-data"}
|
|
105
|
+
)
|
|
106
|
+
.withResponse(
|
|
107
|
+
200,
|
|
108
|
+
{
|
|
109
|
+
data: {
|
|
110
|
+
properties: uploadResultSchema,
|
|
111
|
+
required: Object.keys(uploadResultSchema),
|
|
112
|
+
type: "object",
|
|
113
|
+
},
|
|
114
|
+
},
|
|
115
|
+
{required: ["data"]}
|
|
116
|
+
)
|
|
117
|
+
// Multer puts the file on req.file, not req.body, so JSON body validation must stay off.
|
|
118
|
+
.withValidation({enabled: false})
|
|
67
119
|
.build(),
|
|
68
120
|
],
|
|
69
121
|
asyncHandler(async (req: express.Request, res: express.Response) => {
|
|
70
122
|
await assertFileUploadsEnabled(req, options.fileUploadsEnabled);
|
|
123
|
+
const storage = fileStorageService();
|
|
71
124
|
const file = (req as express.Request & {file?: Express.Multer.File}).file;
|
|
72
125
|
const userId = requestUserId(req);
|
|
73
126
|
|
|
@@ -75,7 +128,7 @@ export const addFileRoutes = (
|
|
|
75
128
|
throw new APIError({status: 400, title: "No file provided"});
|
|
76
129
|
}
|
|
77
130
|
|
|
78
|
-
const result = await
|
|
131
|
+
const result = await storage.upload({
|
|
79
132
|
buffer: file.buffer,
|
|
80
133
|
filename: file.originalname,
|
|
81
134
|
mimeType: file.mimetype,
|
|
@@ -94,10 +147,21 @@ export const addFileRoutes = (
|
|
|
94
147
|
.withTags(["files"])
|
|
95
148
|
.withSummary("Get file URL")
|
|
96
149
|
.withPathParameter("gcsKey", {type: "string"})
|
|
97
|
-
.withResponse(
|
|
150
|
+
.withResponse(
|
|
151
|
+
200,
|
|
152
|
+
{
|
|
153
|
+
data: {
|
|
154
|
+
properties: {url: {description: "Signed URL for the file", type: "string"}},
|
|
155
|
+
required: ["url"],
|
|
156
|
+
type: "object",
|
|
157
|
+
},
|
|
158
|
+
},
|
|
159
|
+
{required: ["data"]}
|
|
160
|
+
)
|
|
98
161
|
.build(),
|
|
99
162
|
],
|
|
100
163
|
asyncHandler(async (req: express.Request, res: express.Response) => {
|
|
164
|
+
const storage = fileStorageService();
|
|
101
165
|
const gcsKey = gcsKeyParam(req);
|
|
102
166
|
|
|
103
167
|
// Another user's file is "not found", so keys cannot be probed.
|
|
@@ -110,7 +174,7 @@ export const addFileRoutes = (
|
|
|
110
174
|
throw new APIError({status: 404, title: "File not found"});
|
|
111
175
|
}
|
|
112
176
|
|
|
113
|
-
const url = await
|
|
177
|
+
const url = await storage.getSignedUrl(gcsKey);
|
|
114
178
|
return res.json({data: {url}});
|
|
115
179
|
})
|
|
116
180
|
);
|
|
@@ -123,10 +187,21 @@ export const addFileRoutes = (
|
|
|
123
187
|
.withTags(["files"])
|
|
124
188
|
.withSummary("Delete a file")
|
|
125
189
|
.withPathParameter("gcsKey", {type: "string"})
|
|
126
|
-
.withResponse(
|
|
190
|
+
.withResponse(
|
|
191
|
+
200,
|
|
192
|
+
{
|
|
193
|
+
data: {
|
|
194
|
+
properties: {success: {type: "boolean"}},
|
|
195
|
+
required: ["success"],
|
|
196
|
+
type: "object",
|
|
197
|
+
},
|
|
198
|
+
},
|
|
199
|
+
{required: ["data"]}
|
|
200
|
+
)
|
|
127
201
|
.build(),
|
|
128
202
|
],
|
|
129
203
|
asyncHandler(async (req: express.Request, res: express.Response) => {
|
|
204
|
+
const storage = fileStorageService();
|
|
130
205
|
const gcsKey = gcsKeyParam(req);
|
|
131
206
|
const userId = requestUserId(req);
|
|
132
207
|
|
|
@@ -139,7 +214,7 @@ export const addFileRoutes = (
|
|
|
139
214
|
throw new APIError({status: 403, title: "Not authorized to delete this file"});
|
|
140
215
|
}
|
|
141
216
|
|
|
142
|
-
await
|
|
217
|
+
await storage.delete(gcsKey);
|
|
143
218
|
return res.json({data: {success: true}});
|
|
144
219
|
})
|
|
145
220
|
);
|
package/src/routes/gpt.test.ts
CHANGED
|
@@ -74,7 +74,7 @@ describe("/gpt/prompt asks", () => {
|
|
|
74
74
|
|
|
75
75
|
afterEach(async () => {
|
|
76
76
|
await AIRequest.deleteMany({});
|
|
77
|
-
await GptHistory.deleteMany({});
|
|
77
|
+
await GptHistory.collection.deleteMany({});
|
|
78
78
|
});
|
|
79
79
|
|
|
80
80
|
describe("pausing on an ask", () => {
|
|
@@ -1730,6 +1730,18 @@ describe("/gpt/prompt asks", () => {
|
|
|
1730
1730
|
expect(res.status).toBe(404);
|
|
1731
1731
|
expect(res.body.title).toBe("History not found");
|
|
1732
1732
|
});
|
|
1733
|
+
|
|
1734
|
+
it("returns 400 for a history id that is not an ObjectId hex string", async () => {
|
|
1735
|
+
const model = createScriptedModel({steps: []});
|
|
1736
|
+
const agent = await authAsUser(buildApp({asks: true, model}), "notAdmin");
|
|
1737
|
+
|
|
1738
|
+
for (const historyId of [crypto.randomUUID(), "abcdefghijkl", {$ne: null}]) {
|
|
1739
|
+
const res = await agent.post("/gpt/prompt").send({historyId, prompt: "Hi"});
|
|
1740
|
+
expect(res.status).toBe(400);
|
|
1741
|
+
expect(res.body.title).toBe("historyId is not valid");
|
|
1742
|
+
}
|
|
1743
|
+
expect(model.doStream).not.toHaveBeenCalled();
|
|
1744
|
+
});
|
|
1733
1745
|
});
|
|
1734
1746
|
|
|
1735
1747
|
describe("a prompt while an ask is pending", () => {
|
|
@@ -3002,7 +3014,7 @@ describe("/gpt/prompt uiBlocks", () => {
|
|
|
3002
3014
|
|
|
3003
3015
|
afterEach(async () => {
|
|
3004
3016
|
await AIRequest.deleteMany({});
|
|
3005
|
-
await GptHistory.deleteMany({});
|
|
3017
|
+
await GptHistory.collection.deleteMany({});
|
|
3006
3018
|
});
|
|
3007
3019
|
|
|
3008
3020
|
it("leaves the prompt and the event list unchanged when uiBlocks is off", async () => {
|
|
@@ -29,7 +29,7 @@ const validBlocks = (): Record<string, unknown> => {
|
|
|
29
29
|
describe("POST /gpt/actions", () => {
|
|
30
30
|
afterEach(async () => {
|
|
31
31
|
await AIRequest.deleteMany({});
|
|
32
|
-
await GptHistory.deleteMany({});
|
|
32
|
+
await GptHistory.collection.deleteMany({});
|
|
33
33
|
});
|
|
34
34
|
|
|
35
35
|
it("keeps the default handler cap at 10 seconds", () => {
|
|
@@ -283,7 +283,7 @@ blocks:
|
|
|
283
283
|
describe("POST /gpt/actions with scaleStepperHostAction", () => {
|
|
284
284
|
afterEach(async () => {
|
|
285
285
|
await AIRequest.deleteMany({});
|
|
286
|
-
await GptHistory.deleteMany({});
|
|
286
|
+
await GptHistory.collection.deleteMany({});
|
|
287
287
|
});
|
|
288
288
|
|
|
289
289
|
const setup = async (
|
|
@@ -395,7 +395,7 @@ blocks:
|
|
|
395
395
|
describe("POST /gpt/actions with toggleChecklistHostAction", () => {
|
|
396
396
|
afterEach(async () => {
|
|
397
397
|
await AIRequest.deleteMany({});
|
|
398
|
-
await GptHistory.deleteMany({});
|
|
398
|
+
await GptHistory.collection.deleteMany({});
|
|
399
399
|
});
|
|
400
400
|
|
|
401
401
|
const setup = async (
|
|
@@ -181,7 +181,7 @@ describe("/gpt/prompt files asks", () => {
|
|
|
181
181
|
afterEach(async () => {
|
|
182
182
|
await AIRequest.deleteMany({});
|
|
183
183
|
await FileAttachment.deleteMany({});
|
|
184
|
-
await GptHistory.deleteMany({});
|
|
184
|
+
await GptHistory.collection.deleteMany({});
|
|
185
185
|
});
|
|
186
186
|
|
|
187
187
|
describe("with data URLs", () => {
|
|
@@ -103,12 +103,12 @@ describe("/gpt/histories headless turns", () => {
|
|
|
103
103
|
beforeAll(async () => {
|
|
104
104
|
await ensureTestUsers();
|
|
105
105
|
await ensureTestUsers([OTHER_USER]);
|
|
106
|
-
await GptHistory.deleteMany({});
|
|
106
|
+
await GptHistory.collection.deleteMany({});
|
|
107
107
|
});
|
|
108
108
|
|
|
109
109
|
afterEach(async () => {
|
|
110
110
|
await AIRequest.deleteMany({});
|
|
111
|
-
await GptHistory.deleteMany({});
|
|
111
|
+
await GptHistory.collection.deleteMany({});
|
|
112
112
|
});
|
|
113
113
|
|
|
114
114
|
describe("POST /gpt/histories/:id/turn", () => {
|
|
@@ -27,6 +27,9 @@ import type {GptHistoryDocument, GptHistoryRouteOptions, GptRouteOptions} from "
|
|
|
27
27
|
|
|
28
28
|
type HistoryRouterOptions = Partial<ModelRouterOptions<GptHistoryDocument>>;
|
|
29
29
|
|
|
30
|
+
/** Route path of the history CRUD; the sync collection tag is this path without the slash. */
|
|
31
|
+
const GPT_HISTORIES_PATH = "/gpt/histories";
|
|
32
|
+
|
|
30
33
|
/**
|
|
31
34
|
* Only the chat turn writes `pendingAsk`: it holds messages replayed verbatim to the model, so a
|
|
32
35
|
* client must not be able to plant or edit one, including through dotted paths.
|
|
@@ -332,59 +335,60 @@ export const addGptHistoryRoutes = (
|
|
|
332
335
|
if (headlessChat) {
|
|
333
336
|
assertNoReservedToolNames(headlessChat.tools);
|
|
334
337
|
}
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
);
|
|
338
|
+
// The three-argument form registers the collection, so SyncApp serves it to @terreno/syncdb
|
|
339
|
+
// clients as the `gpt/histories` collection on the caller's owner stream.
|
|
340
|
+
const registration = modelRouter(GPT_HISTORIES_PATH, GptHistory, {
|
|
341
|
+
...openApiOptions,
|
|
342
|
+
...routerOptions,
|
|
343
|
+
...(headlessChat ? headlessActions({chat: headlessChat, routerOptions}) : {}),
|
|
344
|
+
openApiExtraModelProperties: {
|
|
345
|
+
...routerOptions.openApiExtraModelProperties,
|
|
346
|
+
pendingAsk: clientPendingAskSchema(),
|
|
347
|
+
},
|
|
348
|
+
openApiOverwrite: {
|
|
349
|
+
...routerOptions.openApiOverwrite,
|
|
350
|
+
create: mergeFragments(READ_ONLY_PENDING_ASK, routerOptions.openApiOverwrite?.create),
|
|
351
|
+
update: mergeFragments(READ_ONLY_PENDING_ASK, routerOptions.openApiOverwrite?.update),
|
|
352
|
+
},
|
|
353
|
+
permissions: {
|
|
354
|
+
create: [Permissions.IsAuthenticated],
|
|
355
|
+
delete: [Permissions.IsOwner],
|
|
356
|
+
list: [Permissions.IsAuthenticated],
|
|
357
|
+
read: [Permissions.IsOwner],
|
|
358
|
+
update: [Permissions.IsOwner],
|
|
359
|
+
},
|
|
360
|
+
preCreate: async (body, req): Promise<GptHistoryDocument> => {
|
|
361
|
+
return {
|
|
362
|
+
...(await withoutClientGcsKeys(withoutPendingAsk(body))),
|
|
363
|
+
userId: (req.user as {_id: unknown})?._id,
|
|
364
|
+
} as GptHistoryDocument;
|
|
365
|
+
},
|
|
366
|
+
preUpdate: async (body, req): Promise<GptHistoryDocument> => {
|
|
367
|
+
const update = await withoutClientGcsKeys(withoutPendingAsk(body), req.params.id);
|
|
368
|
+
// A host hook that returns null still refuses the update; modelRouter checks the value.
|
|
369
|
+
return (
|
|
370
|
+
routerOptions.preUpdate ? await routerOptions.preUpdate(update, req) : update
|
|
371
|
+
) as GptHistoryDocument;
|
|
372
|
+
},
|
|
373
|
+
queryFields: ["userId", "projectId"],
|
|
374
|
+
queryFilter: (user) => ({userId: user?.id}),
|
|
375
|
+
responseHandler: async (value, method, req, handlerOptions) => {
|
|
376
|
+
const hostHandler = routerOptions.responseHandler ?? defaultResponseHandler;
|
|
377
|
+
const serialized = await hostHandler(
|
|
378
|
+
value,
|
|
379
|
+
method as Parameters<typeof defaultResponseHandler>[1],
|
|
380
|
+
req,
|
|
381
|
+
handlerOptions
|
|
382
|
+
);
|
|
383
|
+
return (
|
|
384
|
+
Array.isArray(serialized)
|
|
385
|
+
? serialized.map(withClientPendingAsk)
|
|
386
|
+
: withClientPendingAsk(serialized)
|
|
387
|
+
) as JSONValue;
|
|
388
|
+
},
|
|
389
|
+
sort: "-updated",
|
|
390
|
+
sync: {scope: {field: "userId", type: "owner"}},
|
|
391
|
+
validation: withCallerUserId(routerOptions.validation),
|
|
392
|
+
});
|
|
393
|
+
router.use(registration.path, registration.router);
|
|
390
394
|
};
|