@terreno/ai 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/CLAUDE.local.md +208 -0
- package/.cursor/rules/00-root.mdc +342 -0
- package/.cursorrules +221 -0
- package/.github/copilot-instructions.md +337 -0
- package/AGENTS.md +337 -0
- package/biome.jsonc +20 -0
- package/bunfig.toml +3 -0
- package/dist/aiApp.d.ts +59 -0
- package/dist/aiApp.js +67 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +23 -0
- package/dist/models/aiRequest.d.ts +2 -0
- package/dist/models/aiRequest.js +76 -0
- package/dist/models/aiRequest.test.d.ts +1 -0
- package/dist/models/aiRequest.test.js +187 -0
- package/dist/models/fileAttachment.d.ts +2 -0
- package/dist/models/fileAttachment.js +25 -0
- package/dist/models/fileAttachment.test.d.ts +1 -0
- package/dist/models/fileAttachment.test.js +217 -0
- package/dist/models/gptHistory.d.ts +2 -0
- package/dist/models/gptHistory.js +56 -0
- package/dist/models/gptHistory.test.d.ts +1 -0
- package/dist/models/gptHistory.test.js +336 -0
- package/dist/models/index.d.ts +3 -0
- package/dist/models/index.js +9 -0
- package/dist/routes/aiRequestsExplorer.d.ts +2 -0
- package/dist/routes/aiRequestsExplorer.js +153 -0
- package/dist/routes/files.d.ts +5 -0
- package/dist/routes/files.js +168 -0
- package/dist/routes/gpt.d.ts +2 -0
- package/dist/routes/gpt.js +593 -0
- package/dist/routes/gptHistories.d.ts +3 -0
- package/dist/routes/gptHistories.js +29 -0
- package/dist/routes/index.d.ts +5 -0
- package/dist/routes/index.js +13 -0
- package/dist/routes/mcp.d.ts +2 -0
- package/dist/routes/mcp.js +133 -0
- package/dist/routes/routes.test.d.ts +1 -0
- package/dist/routes/routes.test.js +303 -0
- package/dist/service/aiService.d.ts +24 -0
- package/dist/service/aiService.js +453 -0
- package/dist/service/aiService.test.d.ts +1 -0
- package/dist/service/aiService.test.js +367 -0
- package/dist/service/fileStorage.d.ts +24 -0
- package/dist/service/fileStorage.js +143 -0
- package/dist/service/index.d.ts +4 -0
- package/dist/service/index.js +15 -0
- package/dist/service/mcpService.d.ts +14 -0
- package/dist/service/mcpService.js +271 -0
- package/dist/service/prompts.d.ts +4 -0
- package/dist/service/prompts.js +14 -0
- package/dist/tests/bunSetup.d.ts +1 -0
- package/dist/tests/bunSetup.js +227 -0
- package/dist/types/index.d.ts +170 -0
- package/dist/types/index.js +7 -0
- package/package.json +55 -0
- package/src/aiApp.ts +110 -0
- package/src/index.ts +6 -0
- package/src/models/aiRequest.test.ts +101 -0
- package/src/models/aiRequest.ts +45 -0
- package/src/models/fileAttachment.test.ts +119 -0
- package/src/models/fileAttachment.ts +31 -0
- package/src/models/gptHistory.test.ts +209 -0
- package/src/models/gptHistory.ts +71 -0
- package/src/models/index.ts +3 -0
- package/src/routes/aiRequestsExplorer.ts +107 -0
- package/src/routes/files.ts +128 -0
- package/src/routes/gpt.ts +503 -0
- package/src/routes/gptHistories.ts +31 -0
- package/src/routes/index.ts +5 -0
- package/src/routes/mcp.ts +76 -0
- package/src/routes/routes.test.ts +168 -0
- package/src/service/aiService.test.ts +242 -0
- package/src/service/aiService.ts +269 -0
- package/src/service/fileStorage.ts +74 -0
- package/src/service/index.ts +9 -0
- package/src/service/mcpService.ts +120 -0
- package/src/service/prompts.ts +18 -0
- package/src/tests/bunSetup.ts +163 -0
- package/src/types/index.ts +224 -0
- package/tsconfig.json +31 -0
package/AGENTS.md
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
# Terreno
|
|
2
|
+
|
|
3
|
+
A monorepo containing shared packages for building full-stack applications with React Native and Express/Mongoose.
|
|
4
|
+
|
|
5
|
+
## Packages
|
|
6
|
+
|
|
7
|
+
- **api/** - REST API framework built on Express/Mongoose (`@terreno/api`)
|
|
8
|
+
- **ui/** - React Native UI component library (`@terreno/ui`)
|
|
9
|
+
- **rtk/** - Redux Toolkit Query utilities for API backends (`@terreno/rtk`)
|
|
10
|
+
- **admin-backend/** - Admin panel backend plugin for @terreno/api (`@terreno/admin-backend`)
|
|
11
|
+
- **admin-frontend/** - Admin panel frontend screens for @terreno/api backends (`@terreno/admin-frontend`)
|
|
12
|
+
- **mcp-server/** - MCP server for AI assistant integration (`@terreno/mcp-server`)
|
|
13
|
+
- **demo/** - Demo app for showcasing and testing UI components
|
|
14
|
+
- **example-frontend/** - Example Expo app demonstrating full stack usage
|
|
15
|
+
- **example-backend/** - Example Express backend using @terreno/api
|
|
16
|
+
|
|
17
|
+
## Development
|
|
18
|
+
|
|
19
|
+
Uses [Bun](https://bun.sh/) as the package manager.
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
bun install # Install dependencies
|
|
23
|
+
bun run compile # Compile all packages
|
|
24
|
+
bun run lint # Lint all packages
|
|
25
|
+
bun run lint:fix # Fix lint issues
|
|
26
|
+
bun run test # Run tests in api and ui
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### Package-specific commands
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
bun run api:test # Test API package
|
|
33
|
+
bun run ui:test # Test UI package
|
|
34
|
+
bun run demo:start # Start demo app
|
|
35
|
+
bun run frontend:web # Start frontend example
|
|
36
|
+
bun run backend:dev # Start backend example
|
|
37
|
+
bun run mcp:build # Build MCP server
|
|
38
|
+
bun run mcp:start # Start MCP server
|
|
39
|
+
bun run admin-backend:compile # Compile admin backend
|
|
40
|
+
bun run admin-frontend:compile # Compile admin frontend
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## How the Packages Work Together
|
|
44
|
+
|
|
45
|
+
The three core packages form a complete full-stack framework:
|
|
46
|
+
|
|
47
|
+
```
|
|
48
|
+
BACKEND
|
|
49
|
+
@terreno/api
|
|
50
|
+
- Mongoose models with modelRouter -> CRUD endpoints
|
|
51
|
+
- Built-in auth (JWT + Passport)
|
|
52
|
+
- Automatic OpenAPI spec generation
|
|
53
|
+
|
|
|
54
|
+
/openapi.json
|
|
55
|
+
|
|
|
56
|
+
RTK Query SDK Codegen
|
|
57
|
+
|
|
|
58
|
+
FRONTEND
|
|
59
|
+
@terreno/rtk
|
|
60
|
+
- Generated hooks from OpenAPI spec
|
|
61
|
+
- Auth slice with JWT token management
|
|
62
|
+
- Automatic token refresh
|
|
63
|
+
+
|
|
64
|
+
@terreno/ui
|
|
65
|
+
- React Native components (Box, Button, TextField, etc.)
|
|
66
|
+
- TerrenoProvider for theming
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Integration Flow
|
|
70
|
+
|
|
71
|
+
1. **Backend (api)**: Define Mongoose models, use `modelRouter` to create CRUD endpoints with permissions
|
|
72
|
+
2. **OpenAPI Generation**: `setupServer` automatically generates `/openapi.json`
|
|
73
|
+
3. **SDK Codegen**: Frontend runs `bun run sdk` to generate RTK Query hooks from OpenAPI spec
|
|
74
|
+
4. **Frontend (rtk + ui)**: Use generated hooks with UI components for type-safe API calls
|
|
75
|
+
|
|
76
|
+
## Example Apps (Keep These Updated!)
|
|
77
|
+
|
|
78
|
+
The `example-frontend/` and `example-backend/` directories serve as both documentation and integration tests. When adding features to api, ui, or rtk:
|
|
79
|
+
|
|
80
|
+
1. **Add examples** demonstrating new features
|
|
81
|
+
2. **Update SDK** after backend changes: `cd example-frontend && bun run sdk`
|
|
82
|
+
3. **Verify integration** by running both examples together
|
|
83
|
+
|
|
84
|
+
### Running the Full Stack
|
|
85
|
+
|
|
86
|
+
```bash
|
|
87
|
+
# Terminal 1: Start backend
|
|
88
|
+
bun run backend:dev
|
|
89
|
+
|
|
90
|
+
# Terminal 2: Start frontend
|
|
91
|
+
bun run frontend:web
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Code Style
|
|
95
|
+
|
|
96
|
+
### TypeScript/JavaScript
|
|
97
|
+
- Use ES module syntax and TypeScript for all code
|
|
98
|
+
- Prefer interfaces over types; avoid enums, use maps
|
|
99
|
+
- Prefer const arrow functions over `function` keyword
|
|
100
|
+
- Use descriptive variable names with auxiliary verbs (e.g., `isLoading`)
|
|
101
|
+
- Use camelCase directories (e.g., `components/authWizard`)
|
|
102
|
+
- Favor named exports
|
|
103
|
+
- Use the RORO pattern (Receive an Object, Return an Object)
|
|
104
|
+
|
|
105
|
+
### Dates and Time
|
|
106
|
+
- Always use Luxon instead of Date or dayjs
|
|
107
|
+
|
|
108
|
+
### Error Handling
|
|
109
|
+
- Check error conditions at start of functions and return early
|
|
110
|
+
- Limit nested if statements
|
|
111
|
+
- Use multiline syntax with curly braces for all conditionals
|
|
112
|
+
|
|
113
|
+
### Testing
|
|
114
|
+
- Use bun test with expect for testing
|
|
115
|
+
|
|
116
|
+
### Logging
|
|
117
|
+
- Frontend: Use `console.info`, `console.debug`, `console.warn`, or `console.error` for permanent logs
|
|
118
|
+
- Backend: Use `logger.info/warn/error/debug` for permanent logs
|
|
119
|
+
- Use `console.log` only for debugging (to be removed)
|
|
120
|
+
|
|
121
|
+
### Development Practices
|
|
122
|
+
- Don't apologize for errors: fix them
|
|
123
|
+
- Prioritize modularity, DRY, performance, and security
|
|
124
|
+
- Focus on readability over performance
|
|
125
|
+
- Write complete, functional code without TODOs when possible
|
|
126
|
+
- Comments should describe purpose, not effect
|
|
127
|
+
|
|
128
|
+
## Package Reference
|
|
129
|
+
|
|
130
|
+
### @terreno/api
|
|
131
|
+
|
|
132
|
+
REST API framework providing:
|
|
133
|
+
|
|
134
|
+
- **modelRouter**: Auto-generates CRUD endpoints for Mongoose models
|
|
135
|
+
- **Permissions**: `IsAuthenticated`, `IsOwner`, `IsAdmin`, `IsAuthenticatedOrReadOnly`
|
|
136
|
+
- **Query Filters**: `OwnerQueryFilter` for filtering list queries by owner
|
|
137
|
+
- **setupServer**: Express server setup with auth, OpenAPI, and middleware
|
|
138
|
+
- **APIError**: Standardized error handling
|
|
139
|
+
- **logger**: Winston-based logging
|
|
140
|
+
|
|
141
|
+
Key imports:
|
|
142
|
+
```typescript
|
|
143
|
+
import {
|
|
144
|
+
modelRouter,
|
|
145
|
+
setupServer,
|
|
146
|
+
Permissions,
|
|
147
|
+
OwnerQueryFilter,
|
|
148
|
+
APIError,
|
|
149
|
+
logger,
|
|
150
|
+
asyncHandler,
|
|
151
|
+
authenticateMiddleware,
|
|
152
|
+
} from "@terreno/api";
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
#### modelRouter Usage
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
import {modelRouter, modelRouterOptions, Permissions} from "@terreno/api";
|
|
159
|
+
|
|
160
|
+
const router = modelRouter(YourModel, {
|
|
161
|
+
permissions: {
|
|
162
|
+
list: [Permissions.IsAuthenticated],
|
|
163
|
+
create: [Permissions.IsAuthenticated],
|
|
164
|
+
read: [Permissions.IsOwner],
|
|
165
|
+
update: [Permissions.IsOwner],
|
|
166
|
+
delete: [], // Disabled
|
|
167
|
+
},
|
|
168
|
+
sort: "-created",
|
|
169
|
+
queryFields: ["_id", "type", "name"],
|
|
170
|
+
});
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
#### Custom Routes
|
|
174
|
+
|
|
175
|
+
For non-CRUD endpoints, use the OpenAPI builder:
|
|
176
|
+
|
|
177
|
+
```typescript
|
|
178
|
+
import {asyncHandler, authenticateMiddleware, createOpenApiBuilder} from "@terreno/api";
|
|
179
|
+
|
|
180
|
+
router.get("/yourRoute/:id", [
|
|
181
|
+
authenticateMiddleware(),
|
|
182
|
+
createOpenApiBuilder(options)
|
|
183
|
+
.withTags(["yourTag"])
|
|
184
|
+
.withSummary("Brief summary")
|
|
185
|
+
.withPathParameter("id", {type: "string"})
|
|
186
|
+
.withResponse(200, {data: {type: "object"}})
|
|
187
|
+
.build(),
|
|
188
|
+
], asyncHandler(async (req, res) => {
|
|
189
|
+
return res.json({data: result});
|
|
190
|
+
}));
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
#### API Conventions
|
|
194
|
+
|
|
195
|
+
- Throw `APIError` with appropriate status codes: `throw new APIError({status: 400, title: "Message"})`
|
|
196
|
+
- Do not use `Model.findOne` - use `Model.findExactlyOne` or `Model.findOneOrThrow`
|
|
197
|
+
- Define statics/methods by direct assignment: `schema.methods = {bar() {}}`
|
|
198
|
+
- All model types live in `src/modelInterfaces.ts`
|
|
199
|
+
- In routes: `req.user` is `UserDocument | undefined`
|
|
200
|
+
- In @terreno/api callbacks: cast with `const user = u as unknown as UserDocument`
|
|
201
|
+
|
|
202
|
+
### @terreno/ui
|
|
203
|
+
|
|
204
|
+
React Native component library with 88+ components:
|
|
205
|
+
|
|
206
|
+
- **Layout**: Box, Page, SplitPage, Card
|
|
207
|
+
- **Forms**: TextField, SelectField, DateTimeField, CheckBox
|
|
208
|
+
- **Display**: Text, Heading, Badge, DataTable
|
|
209
|
+
- **Actions**: Button, IconButton, Link
|
|
210
|
+
- **Feedback**: Spinner, Modal, Toast
|
|
211
|
+
- **Theming**: TerrenoProvider, useTheme
|
|
212
|
+
|
|
213
|
+
Key imports:
|
|
214
|
+
```typescript
|
|
215
|
+
import {
|
|
216
|
+
Box,
|
|
217
|
+
Button,
|
|
218
|
+
Card,
|
|
219
|
+
Page,
|
|
220
|
+
Text,
|
|
221
|
+
TextField,
|
|
222
|
+
TerrenoProvider,
|
|
223
|
+
} from "@terreno/ui";
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
#### UI Component Examples
|
|
227
|
+
|
|
228
|
+
Layout with Box:
|
|
229
|
+
```typescript
|
|
230
|
+
<Box direction="row" padding={4} gap={2} alignItems="center">
|
|
231
|
+
<Text>Content</Text>
|
|
232
|
+
<Button text="Action" />
|
|
233
|
+
</Box>
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Buttons:
|
|
237
|
+
```typescript
|
|
238
|
+
<Button
|
|
239
|
+
text="Submit"
|
|
240
|
+
variant="primary" // 'primary' | 'secondary' | 'outline' | 'ghost'
|
|
241
|
+
onClick={handleSubmit}
|
|
242
|
+
loading={isLoading}
|
|
243
|
+
iconName="check"
|
|
244
|
+
/>
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
Forms:
|
|
248
|
+
```typescript
|
|
249
|
+
<TextField
|
|
250
|
+
label="Email"
|
|
251
|
+
value={email}
|
|
252
|
+
onChangeText={setEmail}
|
|
253
|
+
error={emailError}
|
|
254
|
+
helperText="Enter a valid email"
|
|
255
|
+
/>
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
Modals:
|
|
259
|
+
```typescript
|
|
260
|
+
<Modal
|
|
261
|
+
title="Confirm Action"
|
|
262
|
+
visible={isVisible}
|
|
263
|
+
primaryButtonText="Confirm"
|
|
264
|
+
secondaryButtonText="Cancel"
|
|
265
|
+
onDismiss={() => setIsVisible(false)}
|
|
266
|
+
onPrimaryAction={handleConfirm}
|
|
267
|
+
>
|
|
268
|
+
<Text>Are you sure?</Text>
|
|
269
|
+
</Modal>
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
#### UI Common Pitfalls
|
|
273
|
+
|
|
274
|
+
- Don't use inline styles when theme values are available
|
|
275
|
+
- Don't use raw `View`/`Text` when `Box`/@terreno/ui `Text` are available
|
|
276
|
+
- Don't forget loading and error states
|
|
277
|
+
- Don't use `style` prop when equivalent props exist (`padding`, `margin`)
|
|
278
|
+
- Never modify `openApiSdk.ts` manually
|
|
279
|
+
|
|
280
|
+
### @terreno/rtk
|
|
281
|
+
|
|
282
|
+
Redux Toolkit Query integration:
|
|
283
|
+
|
|
284
|
+
- **generateAuthSlice**: Creates auth reducer and middleware with JWT handling
|
|
285
|
+
- **emptyApi**: Base RTK Query API for code generation
|
|
286
|
+
- **Platform utilities**: Secure token storage (expo-secure-store for native, AsyncStorage for web)
|
|
287
|
+
|
|
288
|
+
Key imports:
|
|
289
|
+
```typescript
|
|
290
|
+
import {generateAuthSlice} from "@terreno/rtk";
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
Always use generated SDK hooks - never use `axios` or `request` directly:
|
|
294
|
+
|
|
295
|
+
```typescript
|
|
296
|
+
// Correct
|
|
297
|
+
import {useGetYourRouteQuery} from "@/store/openApiSdk";
|
|
298
|
+
const {data, isLoading, error} = useGetYourRouteQuery({id: "value"});
|
|
299
|
+
|
|
300
|
+
// Wrong - don't use axios directly
|
|
301
|
+
// const result = await axios.get("/api/yourRoute/value");
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
## React Best Practices (Frontend Packages)
|
|
305
|
+
|
|
306
|
+
- Use functional components with `React.FC` type
|
|
307
|
+
- Import hooks directly: `import {useEffect, useMemo} from 'react'`
|
|
308
|
+
- Always provide return types for functions
|
|
309
|
+
- Add explanatory comment above each `useEffect`
|
|
310
|
+
- Wrap callbacks in `useCallback`
|
|
311
|
+
- Prefer const arrow functions
|
|
312
|
+
- Use inline styles over `StyleSheet.create`
|
|
313
|
+
- Use Luxon for date operations
|
|
314
|
+
- Place static content and interfaces at beginning of file
|
|
315
|
+
- Minimize `use client`, `useEffect`, and `setState`
|
|
316
|
+
- Always support React-Native Web
|
|
317
|
+
|
|
318
|
+
## CI/CD Workflows
|
|
319
|
+
|
|
320
|
+
### Required Secret Validation
|
|
321
|
+
|
|
322
|
+
GitHub Actions workflows that use secrets or environment variables must validate all required variables are set before using them. Add a validation step early in the job that fails fast with a clear error message listing any missing variables.
|
|
323
|
+
|
|
324
|
+
```yaml
|
|
325
|
+
- name: Validate required secrets
|
|
326
|
+
run: |
|
|
327
|
+
missing=()
|
|
328
|
+
if [ -z "$VAR_NAME" ]; then missing+=("VAR_NAME"); fi
|
|
329
|
+
if [ ${#missing[@]} -ne 0 ]; then
|
|
330
|
+
echo "::error::Missing required secrets: ${missing[*]}"
|
|
331
|
+
exit 1
|
|
332
|
+
fi
|
|
333
|
+
```
|
|
334
|
+
|
|
335
|
+
## Dependency Management
|
|
336
|
+
|
|
337
|
+
Uses [Bun Catalogs](https://bun.sh/docs/install/catalogs) - shared versions defined in root `package.json` under `catalog`. Reference with `catalog:` in workspace packages.
|
package/biome.jsonc
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"root": true,
|
|
3
|
+
"$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
|
|
4
|
+
"extends": ["../biome.jsonc"],
|
|
5
|
+
"files": {
|
|
6
|
+
"includes": [
|
|
7
|
+
"package.json",
|
|
8
|
+
"src/**/*.ts",
|
|
9
|
+
"src/**/*.tsx",
|
|
10
|
+
"!!**/node_modules",
|
|
11
|
+
"!!node_modules",
|
|
12
|
+
"!!**/dist",
|
|
13
|
+
"!!dist",
|
|
14
|
+
"!!**/build",
|
|
15
|
+
"!!build",
|
|
16
|
+
"!!**/coverage",
|
|
17
|
+
"!!coverage"
|
|
18
|
+
]
|
|
19
|
+
}
|
|
20
|
+
}
|
package/bunfig.toml
ADDED
package/dist/aiApp.d.ts
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { TerrenoPlugin } from "@terreno/api";
|
|
2
|
+
import type { LanguageModel, Tool } from "ai";
|
|
3
|
+
import type express from "express";
|
|
4
|
+
import type { AIService } from "./service/aiService";
|
|
5
|
+
import type { FileStorageService } from "./service/fileStorage";
|
|
6
|
+
import type { MCPService } from "./service/mcpService";
|
|
7
|
+
export interface AiAppOptions {
|
|
8
|
+
/** Pre-configured AIService instance. Optional when using per-request keys or demo mode. */
|
|
9
|
+
aiService?: AIService;
|
|
10
|
+
/** Factory function to create a LanguageModel from a per-request API key (sent via x-ai-api-key header). */
|
|
11
|
+
createModelFn?: (apiKey: string) => LanguageModel;
|
|
12
|
+
/** When true and no AI service is available, routes return canned demo responses instead of failing. */
|
|
13
|
+
demoMode?: boolean;
|
|
14
|
+
/** File storage service for handling file uploads to GCS. */
|
|
15
|
+
fileStorageService?: FileStorageService;
|
|
16
|
+
/** GCS bucket name for file uploads. Required alongside fileStorageService. */
|
|
17
|
+
gcsBucket?: string;
|
|
18
|
+
/** Maximum number of tool-calling steps per chat request. Defaults to 5 when tools are present. */
|
|
19
|
+
maxSteps?: number;
|
|
20
|
+
/** MCP service for connecting to external tool servers. */
|
|
21
|
+
mcpService?: MCPService;
|
|
22
|
+
/** OpenAPI options passed through to route builders for spec generation. */
|
|
23
|
+
openApiOptions?: Record<string, unknown>;
|
|
24
|
+
/** Tool choice strategy for chat requests. Defaults to "auto" when tools are present. */
|
|
25
|
+
toolChoice?: "auto" | "none" | "required";
|
|
26
|
+
/** Tool definitions available to the AI model during chat. */
|
|
27
|
+
tools?: Record<string, Tool>;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* TerrenoPlugin that mounts all AI routes (GPT chat, history, file uploads, MCP, admin explorer).
|
|
31
|
+
*
|
|
32
|
+
* Supports three modes of operation:
|
|
33
|
+
* - **Configured**: Pass an `aiService` for server-wide AI access
|
|
34
|
+
* - **Per-request keys**: Pass a `createModelFn` so clients can supply their own API key via `x-ai-api-key` header
|
|
35
|
+
* - **Demo mode**: When neither service nor per-request key is available, returns a canned response
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```typescript
|
|
39
|
+
* import {AiApp, AIService} from "@terreno/ai";
|
|
40
|
+
* import {google} from "@ai-sdk/google";
|
|
41
|
+
*
|
|
42
|
+
* const aiService = new AIService({model: google("gemini-2.5-flash")});
|
|
43
|
+
* new AiApp({aiService, tools: myTools}).register(app);
|
|
44
|
+
* ```
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* ```typescript
|
|
48
|
+
* // Demo mode with per-request key support (no server-side API key needed)
|
|
49
|
+
* new AiApp({
|
|
50
|
+
* createModelFn: (key) => google("gemini-2.5-flash", {apiKey: key}),
|
|
51
|
+
* demoMode: true,
|
|
52
|
+
* }).register(app);
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
export declare class AiApp implements TerrenoPlugin {
|
|
56
|
+
private options;
|
|
57
|
+
constructor(options: AiAppOptions);
|
|
58
|
+
register(app: express.Application): void;
|
|
59
|
+
}
|
package/dist/aiApp.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AiApp = void 0;
|
|
4
|
+
var aiRequestsExplorer_1 = require("./routes/aiRequestsExplorer");
|
|
5
|
+
var files_1 = require("./routes/files");
|
|
6
|
+
var gpt_1 = require("./routes/gpt");
|
|
7
|
+
var gptHistories_1 = require("./routes/gptHistories");
|
|
8
|
+
var mcp_1 = require("./routes/mcp");
|
|
9
|
+
/**
|
|
10
|
+
* TerrenoPlugin that mounts all AI routes (GPT chat, history, file uploads, MCP, admin explorer).
|
|
11
|
+
*
|
|
12
|
+
* Supports three modes of operation:
|
|
13
|
+
* - **Configured**: Pass an `aiService` for server-wide AI access
|
|
14
|
+
* - **Per-request keys**: Pass a `createModelFn` so clients can supply their own API key via `x-ai-api-key` header
|
|
15
|
+
* - **Demo mode**: When neither service nor per-request key is available, returns a canned response
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```typescript
|
|
19
|
+
* import {AiApp, AIService} from "@terreno/ai";
|
|
20
|
+
* import {google} from "@ai-sdk/google";
|
|
21
|
+
*
|
|
22
|
+
* const aiService = new AIService({model: google("gemini-2.5-flash")});
|
|
23
|
+
* new AiApp({aiService, tools: myTools}).register(app);
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```typescript
|
|
28
|
+
* // Demo mode with per-request key support (no server-side API key needed)
|
|
29
|
+
* new AiApp({
|
|
30
|
+
* createModelFn: (key) => google("gemini-2.5-flash", {apiKey: key}),
|
|
31
|
+
* demoMode: true,
|
|
32
|
+
* }).register(app);
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
35
|
+
var AiApp = /** @class */ (function () {
|
|
36
|
+
function AiApp(options) {
|
|
37
|
+
this.options = options;
|
|
38
|
+
}
|
|
39
|
+
AiApp.prototype.register = function (app) {
|
|
40
|
+
var router = app;
|
|
41
|
+
var _a = this.options, aiService = _a.aiService, createModelFn = _a.createModelFn, demoMode = _a.demoMode, fileStorageService = _a.fileStorageService, gcsBucket = _a.gcsBucket, maxSteps = _a.maxSteps, mcpService = _a.mcpService, openApiOptions = _a.openApiOptions, toolChoice = _a.toolChoice, tools = _a.tools;
|
|
42
|
+
(0, gptHistories_1.addGptHistoryRoutes)(router, { openApiOptions: openApiOptions });
|
|
43
|
+
(0, gpt_1.addGptRoutes)(router, {
|
|
44
|
+
aiService: aiService,
|
|
45
|
+
createModelFn: createModelFn,
|
|
46
|
+
demoMode: demoMode,
|
|
47
|
+
maxSteps: maxSteps,
|
|
48
|
+
mcpService: mcpService,
|
|
49
|
+
openApiOptions: openApiOptions,
|
|
50
|
+
toolChoice: toolChoice,
|
|
51
|
+
tools: tools,
|
|
52
|
+
});
|
|
53
|
+
(0, aiRequestsExplorer_1.addAiRequestsExplorerRoutes)(router, { openApiOptions: openApiOptions });
|
|
54
|
+
if (fileStorageService && gcsBucket) {
|
|
55
|
+
(0, files_1.addFileRoutes)(router, {
|
|
56
|
+
fileStorageService: fileStorageService,
|
|
57
|
+
gcsBucket: gcsBucket,
|
|
58
|
+
openApiOptions: openApiOptions,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
if (mcpService) {
|
|
62
|
+
(0, mcp_1.addMcpRoutes)(router, { mcpService: mcpService, openApiOptions: openApiOptions });
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
return AiApp;
|
|
66
|
+
}());
|
|
67
|
+
exports.AiApp = AiApp;
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
exports.AiApp = void 0;
|
|
18
|
+
var aiApp_1 = require("./aiApp");
|
|
19
|
+
Object.defineProperty(exports, "AiApp", { enumerable: true, get: function () { return aiApp_1.AiApp; } });
|
|
20
|
+
__exportStar(require("./models"), exports);
|
|
21
|
+
__exportStar(require("./routes"), exports);
|
|
22
|
+
__exportStar(require("./service"), exports);
|
|
23
|
+
__exportStar(require("./types"), exports);
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
12
|
+
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);
|
|
13
|
+
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
14
|
+
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
15
|
+
function step(op) {
|
|
16
|
+
if (f) throw new TypeError("Generator is already executing.");
|
|
17
|
+
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
18
|
+
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;
|
|
19
|
+
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
20
|
+
switch (op[0]) {
|
|
21
|
+
case 0: case 1: t = op; break;
|
|
22
|
+
case 4: _.label++; return { value: op[1], done: false };
|
|
23
|
+
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
24
|
+
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
25
|
+
default:
|
|
26
|
+
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
27
|
+
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
28
|
+
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
29
|
+
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
30
|
+
if (t[2]) _.ops.pop();
|
|
31
|
+
_.trys.pop(); continue;
|
|
32
|
+
}
|
|
33
|
+
op = body.call(thisArg, _);
|
|
34
|
+
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
35
|
+
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
39
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
40
|
+
};
|
|
41
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
42
|
+
exports.AIRequest = void 0;
|
|
43
|
+
var api_1 = require("@terreno/api");
|
|
44
|
+
var mongoose_1 = __importDefault(require("mongoose"));
|
|
45
|
+
var aiRequestSchema = new mongoose_1.default.Schema({
|
|
46
|
+
aiModel: { required: true, type: String },
|
|
47
|
+
error: { type: String },
|
|
48
|
+
metadata: { type: mongoose_1.default.Schema.Types.Mixed },
|
|
49
|
+
prompt: { required: true, type: String },
|
|
50
|
+
requestType: {
|
|
51
|
+
enum: ["general", "remix", "summarization", "translation"],
|
|
52
|
+
required: true,
|
|
53
|
+
type: String,
|
|
54
|
+
},
|
|
55
|
+
response: { type: String },
|
|
56
|
+
responseTime: { type: Number },
|
|
57
|
+
tokensUsed: { type: Number },
|
|
58
|
+
userId: { ref: "User", type: mongoose_1.default.Schema.Types.ObjectId },
|
|
59
|
+
}, { strict: "throw", toJSON: { virtuals: true }, toObject: { virtuals: true } });
|
|
60
|
+
aiRequestSchema.plugin(api_1.createdUpdatedPlugin);
|
|
61
|
+
aiRequestSchema.plugin(api_1.isDeletedPlugin);
|
|
62
|
+
aiRequestSchema.plugin(api_1.findOneOrNone);
|
|
63
|
+
aiRequestSchema.plugin(api_1.findExactlyOne);
|
|
64
|
+
aiRequestSchema.index({ created: -1, userId: 1 });
|
|
65
|
+
aiRequestSchema.index({ aiModel: 1, created: -1 });
|
|
66
|
+
aiRequestSchema.index({ created: -1, requestType: 1 });
|
|
67
|
+
aiRequestSchema.statics.logRequest = function (params) {
|
|
68
|
+
return __awaiter(this, void 0, void 0, function () {
|
|
69
|
+
var request;
|
|
70
|
+
return __generator(this, function (_a) {
|
|
71
|
+
request = new this(params);
|
|
72
|
+
return [2 /*return*/, request.save()];
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
};
|
|
76
|
+
exports.AIRequest = mongoose_1.default.model("AIRequest", aiRequestSchema);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|