feat(backend): add authenticated API for projects and Jarvis chat
Introduce the user/project/message model, JWT authentication and an Ollama relay that streams answers chunk by chunk over SSE.
This commit is contained in:
1 parent
7c0156fbae
commit
32dd462be5
17 files changed
+1214
No files matched your search
@@ -0,0 +1,27 @@
|
||||
# Copier ce fichier en `.env` puis adapter les valeurs.
|
||||
|
||||
# Environnement : development | production | test
|
||||
NODE_ENV=development
|
||||
|
||||
# Serveur HTTP
|
||||
PORT=3000
|
||||
HOST=0.0.0.0
|
||||
|
||||
# Secret de signature des JWT (OBLIGATOIRE : mets une longue chaîne aléatoire)
|
||||
JWT_SECRET=change-moi-par-un-secret-long-et-aleatoire
|
||||
JWT_EXPIRES_IN=7d
|
||||
|
||||
# Base de données SQLite (chemin relatif au dossier backend)
|
||||
DB_PATH=./data/jarvise.db
|
||||
|
||||
# CORS : origine(s) autorisée(s). "*" pour tout, ou une liste séparée par des virgules.
|
||||
CORS_ORIGIN=*
|
||||
|
||||
# Limitation de débit (par IP) : requêtes max sur une fenêtre en ms (60000 = 1 min)
|
||||
RATE_LIMIT_MAX=300
|
||||
RATE_LIMIT_WINDOW=60000
|
||||
|
||||
# Ollama (le moteur qui fait tourner Jarvis)
|
||||
OLLAMA_URL=http://localhost:11434
|
||||
OLLAMA_MODEL=llama3.2
|
||||
# JARVIS_SYSTEM_PROMPT=Tu es Jarvis...
|
||||
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
data/
|
||||
.env
|
||||
*.log
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "jarvise-backend",
|
||||
"version": "0.2.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "API backend pour Jarvis : utilisateurs, projets, contexte de conversation et streaming Ollama.",
|
||||
"engines": {
|
||||
"node": ">=22"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node src/server.js",
|
||||
"dev": "node --watch src/server.js",
|
||||
"test": "node --test test/"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^10.0.0",
|
||||
"@fastify/helmet": "^13.0.0",
|
||||
"@fastify/jwt": "^9.0.0",
|
||||
"@fastify/rate-limit": "^10.0.0",
|
||||
"bcryptjs": "^2.4.3",
|
||||
"fastify": "^5.0.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import cors from '@fastify/cors';
|
||||
import helmet from '@fastify/helmet';
|
||||
import rateLimit from '@fastify/rate-limit';
|
||||
import Fastify from 'fastify';
|
||||
|
||||
import { registerAuth } from './plugins/auth.js';
|
||||
import { registerErrorHandling } from './plugins/errors.js';
|
||||
import { authRoutes } from './routes/auth.js';
|
||||
import { chatRoutes } from './routes/chat.js';
|
||||
import { healthRoutes } from './routes/health.js';
|
||||
import { projectRoutes } from './routes/projects.js';
|
||||
|
||||
/**
|
||||
* Builds the full Fastify application without listening, which is convenient
|
||||
* for tests and for embedding.
|
||||
*
|
||||
* @param {object} options
|
||||
* @param {ReturnType<import('./config.js').loadConfig>} options.config
|
||||
* @param {ReturnType<import('./db/index.js').createDatabase>} options.db
|
||||
* @param {ReturnType<import('./services/ollama.js').createOllama>} options.ollama
|
||||
*/
|
||||
export async function buildApp({ config, db, ollama }) {
|
||||
const app = Fastify({
|
||||
logger: config.isTest ? false : { level: process.env.LOG_LEVEL ?? 'info' },
|
||||
trustProxy: true,
|
||||
});
|
||||
|
||||
// Dependency injection: reachable everywhere via fastify.<name>.
|
||||
app.decorate('config', config);
|
||||
app.decorate('db', db);
|
||||
app.decorate('ollama', ollama);
|
||||
|
||||
// HTTP security: headers (helmet) + CORS.
|
||||
await app.register(helmet, {
|
||||
contentSecurityPolicy: false,
|
||||
crossOriginResourcePolicy: { policy: 'cross-origin' },
|
||||
});
|
||||
await app.register(cors, { origin: config.cors.origin });
|
||||
|
||||
if (config.rateLimit.enabled) {
|
||||
await app.register(rateLimit, {
|
||||
max: config.rateLimit.max,
|
||||
timeWindow: config.rateLimit.window,
|
||||
});
|
||||
}
|
||||
|
||||
// These two must apply to the root context, not an encapsulated one.
|
||||
registerErrorHandling(app);
|
||||
await registerAuth(app);
|
||||
|
||||
await app.register(healthRoutes);
|
||||
await app.register(authRoutes);
|
||||
await app.register(chatRoutes);
|
||||
await app.register(projectRoutes);
|
||||
|
||||
// Close the database along with the server.
|
||||
app.addHook('onClose', async () => {
|
||||
db.close?.();
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
export const rootDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
||||
// Load the .env file if present (native since Node 20.12, no need for dotenv).
|
||||
try {
|
||||
process.loadEnvFile(path.join(rootDir, '.env'));
|
||||
} catch {
|
||||
// No .env file: fall back to the real environment variables.
|
||||
}
|
||||
|
||||
function resolveFromRoot(value, fallback) {
|
||||
const raw = value ?? fallback;
|
||||
if (raw === ':memory:') return raw;
|
||||
return path.isAbsolute(raw) ? raw : path.resolve(rootDir, raw);
|
||||
}
|
||||
|
||||
function parseOrigin(value) {
|
||||
if (!value || value === '*') return '*';
|
||||
return value
|
||||
.split(',')
|
||||
.map((s) => s.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the application configuration. The `overrides` let tests inject a
|
||||
* temporary database, a mock Ollama, etc. without touching env variables.
|
||||
*/
|
||||
export function loadConfig(overrides = {}) {
|
||||
const env = overrides.env ?? process.env.NODE_ENV ?? 'development';
|
||||
const isTest = env === 'test';
|
||||
|
||||
const jwtSecret = overrides.jwtSecret ?? process.env.JWT_SECRET ?? 'dev-secret-change-me';
|
||||
if (jwtSecret === 'dev-secret-change-me' && !isTest) {
|
||||
console.warn(
|
||||
'[config] JWT_SECRET is not set: falling back to a development secret. ' +
|
||||
'Set JWT_SECRET before any production deployment.',
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
rootDir,
|
||||
env,
|
||||
isTest,
|
||||
port: Number(overrides.port ?? process.env.PORT ?? 3000),
|
||||
host: overrides.host ?? process.env.HOST ?? '0.0.0.0',
|
||||
dbPath: resolveFromRoot(overrides.dbPath ?? process.env.DB_PATH, 'data/jarvise.db'),
|
||||
cors: {
|
||||
origin: overrides.corsOrigin ?? parseOrigin(process.env.CORS_ORIGIN),
|
||||
},
|
||||
rateLimit: {
|
||||
// Disabled in tests so the suite is not throttled.
|
||||
enabled: overrides.rateLimitEnabled ?? !isTest,
|
||||
max: Number(overrides.rateLimitMax ?? process.env.RATE_LIMIT_MAX ?? 300),
|
||||
window: Number(overrides.rateLimitWindow ?? process.env.RATE_LIMIT_WINDOW ?? 60000),
|
||||
},
|
||||
jwt: {
|
||||
secret: jwtSecret,
|
||||
expiresIn: overrides.jwtExpiresIn ?? process.env.JWT_EXPIRES_IN ?? '7d',
|
||||
},
|
||||
ollama: {
|
||||
url: (overrides.ollamaUrl ?? process.env.OLLAMA_URL ?? 'http://localhost:11434').replace(/\/+$/, ''),
|
||||
model: overrides.ollamaModel ?? process.env.OLLAMA_MODEL ?? 'llama3.2',
|
||||
systemPrompt:
|
||||
overrides.systemPrompt ??
|
||||
process.env.JARVIS_SYSTEM_PROMPT ??
|
||||
"Tu es Jarvis, l'assistant personnel de l'utilisateur. Réponds de façon claire, concise et utile, en français sauf si on te demande une autre langue.",
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { DatabaseSync } from 'node:sqlite';
|
||||
|
||||
const SCHEMA = `
|
||||
PRAGMA journal_mode = WAL;
|
||||
PRAGMA foreign_keys = ON;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
||||
password_hash TEXT NOT NULL,
|
||||
name TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
-- A project belongs to a single user.
|
||||
CREATE TABLE IF NOT EXISTS projects (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL,
|
||||
description TEXT,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_projects_user ON projects(user_id);
|
||||
|
||||
-- Messages form a project's context (conversation history).
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||
role TEXT NOT NULL CHECK (role IN ('system', 'user', 'assistant')),
|
||||
content TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_project ON messages(project_id, id);
|
||||
`;
|
||||
|
||||
/**
|
||||
* Opens (and initialises) the SQLite database and returns every query helper.
|
||||
* Each call creates an independent database, which is convenient for tests.
|
||||
*/
|
||||
export function createDatabase(dbPath) {
|
||||
if (dbPath !== ':memory:') {
|
||||
fs.mkdirSync(path.dirname(dbPath), { recursive: true });
|
||||
}
|
||||
|
||||
const db = new DatabaseSync(dbPath);
|
||||
db.exec(SCHEMA);
|
||||
|
||||
/* -------------------------------------------------------------- users */
|
||||
|
||||
const findUserByEmail = (email) =>
|
||||
db
|
||||
.prepare('SELECT id, email, password_hash, name, created_at FROM users WHERE email = ?')
|
||||
.get(email);
|
||||
|
||||
const findUserById = (id) =>
|
||||
db.prepare('SELECT id, email, name, created_at FROM users WHERE id = ?').get(id);
|
||||
|
||||
const createUser = ({ email, passwordHash, name = null }) => {
|
||||
const result = db
|
||||
.prepare('INSERT INTO users (email, password_hash, name) VALUES (?, ?, ?)')
|
||||
.run(email, passwordHash, name);
|
||||
return findUserById(Number(result.lastInsertRowid));
|
||||
};
|
||||
|
||||
const updateUserName = (id, name) => {
|
||||
db.prepare('UPDATE users SET name = ? WHERE id = ?').run(name, id);
|
||||
return findUserById(id);
|
||||
};
|
||||
|
||||
const updateUserPassword = (id, passwordHash) => {
|
||||
db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run(passwordHash, id);
|
||||
};
|
||||
|
||||
const countUsers = () => db.prepare('SELECT COUNT(*) AS n FROM users').get().n;
|
||||
|
||||
/* ----------------------------------------------------------- projects */
|
||||
|
||||
const getProjectForUser = (id, userId) =>
|
||||
db
|
||||
.prepare(
|
||||
`SELECT p.*, (SELECT COUNT(*) FROM messages m WHERE m.project_id = p.id) AS message_count
|
||||
FROM projects p
|
||||
WHERE p.id = ? AND p.user_id = ?`,
|
||||
)
|
||||
.get(id, userId);
|
||||
|
||||
const createProject = ({ userId, name, description = null }) => {
|
||||
const result = db
|
||||
.prepare('INSERT INTO projects (user_id, name, description) VALUES (?, ?, ?)')
|
||||
.run(userId, name, description);
|
||||
return getProjectForUser(Number(result.lastInsertRowid), userId);
|
||||
};
|
||||
|
||||
const listProjects = (userId) =>
|
||||
db
|
||||
.prepare(
|
||||
`SELECT p.*, (SELECT COUNT(*) FROM messages m WHERE m.project_id = p.id) AS message_count
|
||||
FROM projects p
|
||||
WHERE p.user_id = ?
|
||||
ORDER BY p.updated_at DESC, p.id DESC`,
|
||||
)
|
||||
.all(userId);
|
||||
|
||||
const updateProject = (id, userId, { name, description }) => {
|
||||
db.prepare(
|
||||
`UPDATE projects
|
||||
SET name = COALESCE(?, name),
|
||||
description = COALESCE(?, description),
|
||||
updated_at = datetime('now')
|
||||
WHERE id = ? AND user_id = ?`,
|
||||
).run(name ?? null, description ?? null, id, userId);
|
||||
return getProjectForUser(id, userId);
|
||||
};
|
||||
|
||||
const deleteProject = (id, userId) =>
|
||||
db.prepare('DELETE FROM projects WHERE id = ? AND user_id = ?').run(id, userId).changes > 0;
|
||||
|
||||
const touchProject = (id) =>
|
||||
db.prepare("UPDATE projects SET updated_at = datetime('now') WHERE id = ?").run(id);
|
||||
|
||||
const projectStats = (projectId) =>
|
||||
db
|
||||
.prepare(
|
||||
`SELECT COUNT(*) AS messageCount,
|
||||
COALESCE(SUM(LENGTH(content)), 0) AS totalChars,
|
||||
MAX(created_at) AS lastMessageAt
|
||||
FROM messages WHERE project_id = ?`,
|
||||
)
|
||||
.get(projectId);
|
||||
|
||||
/* ----------------------------------------------------------- messages */
|
||||
|
||||
/**
|
||||
* A project's history, from oldest to newest, bounded by `limit`.
|
||||
* Passing `before` (a message id) returns the page just older than it.
|
||||
*/
|
||||
const listMessages = (projectId, { limit = 50, before = null } = {}) => {
|
||||
const sql = before
|
||||
? `SELECT * FROM (
|
||||
SELECT id, project_id, role, content, created_at FROM messages
|
||||
WHERE project_id = ? AND id < ? ORDER BY id DESC LIMIT ?
|
||||
) ORDER BY id ASC`
|
||||
: `SELECT * FROM (
|
||||
SELECT id, project_id, role, content, created_at FROM messages
|
||||
WHERE project_id = ? ORDER BY id DESC LIMIT ?
|
||||
) ORDER BY id ASC`;
|
||||
|
||||
return before
|
||||
? db.prepare(sql).all(projectId, before, limit)
|
||||
: db.prepare(sql).all(projectId, limit);
|
||||
};
|
||||
|
||||
const hasOlderMessages = (projectId, oldestId) =>
|
||||
!!db
|
||||
.prepare('SELECT 1 FROM messages WHERE project_id = ? AND id < ? LIMIT 1')
|
||||
.get(projectId, oldestId);
|
||||
|
||||
const addMessage = (projectId, { role, content }) => {
|
||||
const result = db
|
||||
.prepare('INSERT INTO messages (project_id, role, content) VALUES (?, ?, ?)')
|
||||
.run(projectId, role, content);
|
||||
return db.prepare('SELECT * FROM messages WHERE id = ?').get(Number(result.lastInsertRowid));
|
||||
};
|
||||
|
||||
const deleteMessages = (projectId) =>
|
||||
db.prepare('DELETE FROM messages WHERE project_id = ?').run(projectId).changes;
|
||||
|
||||
return {
|
||||
db,
|
||||
close: () => db.close(),
|
||||
|
||||
findUserByEmail,
|
||||
findUserById,
|
||||
createUser,
|
||||
updateUserName,
|
||||
updateUserPassword,
|
||||
countUsers,
|
||||
|
||||
getProjectForUser,
|
||||
createProject,
|
||||
listProjects,
|
||||
updateProject,
|
||||
deleteProject,
|
||||
touchProject,
|
||||
projectStats,
|
||||
|
||||
listMessages,
|
||||
hasOlderMessages,
|
||||
addMessage,
|
||||
deleteMessages,
|
||||
};
|
||||
}
|
||||
|
||||
/* ------------------------------------------------- public serialisation */
|
||||
|
||||
export function toPublicUser(user) {
|
||||
if (!user) return null;
|
||||
return { id: user.id, email: user.email, name: user.name, createdAt: user.created_at };
|
||||
}
|
||||
|
||||
export function toPublicProject(project) {
|
||||
if (!project) return null;
|
||||
return {
|
||||
id: project.id,
|
||||
userId: project.user_id,
|
||||
name: project.name,
|
||||
description: project.description,
|
||||
messageCount: project.message_count ?? 0,
|
||||
createdAt: project.created_at,
|
||||
updatedAt: project.updated_at,
|
||||
};
|
||||
}
|
||||
|
||||
export function toPublicMessage(message) {
|
||||
if (!message) return null;
|
||||
return {
|
||||
id: message.id,
|
||||
projectId: message.project_id,
|
||||
role: message.role,
|
||||
content: message.content,
|
||||
createdAt: message.created_at,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/** Business error carrying an HTTP status, handled by the global error handler. */
|
||||
export class HttpError extends Error {
|
||||
constructor(status, message, code = undefined) {
|
||||
super(message);
|
||||
this.name = 'HttpError';
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export const badRequest = (message) => new HttpError(400, message);
|
||||
export const unauthorized = (message = 'Authentication required.') => new HttpError(401, message);
|
||||
export const forbidden = (message = 'Access denied.') => new HttpError(403, message);
|
||||
export const notFound = (message = 'Resource not found.') => new HttpError(404, message);
|
||||
export const conflict = (message) => new HttpError(409, message);
|
||||
|
||||
/** Raised when Ollama is unreachable or answers with an error. */
|
||||
export class OllamaError extends Error {
|
||||
constructor(message, status = 502) {
|
||||
super(message);
|
||||
this.name = 'OllamaError';
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import bcrypt from 'bcryptjs';
|
||||
|
||||
const ROUNDS = 10;
|
||||
|
||||
// Dummy hash used to keep the response time constant when the user does not
|
||||
// exist, so we never reveal whether an account exists.
|
||||
const DUMMY_HASH = bcrypt.hashSync('non-existent-password', ROUNDS);
|
||||
|
||||
export function hashPassword(password) {
|
||||
return bcrypt.hash(password, ROUNDS);
|
||||
}
|
||||
|
||||
export async function verifyPassword(password, hash) {
|
||||
if (!hash) {
|
||||
await bcrypt.compare(password, DUMMY_HASH);
|
||||
return false;
|
||||
}
|
||||
return bcrypt.compare(password, hash);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import fastifyJwt from '@fastify/jwt';
|
||||
|
||||
import { unauthorized } from '../lib/errors.js';
|
||||
|
||||
/**
|
||||
* Registers JWT support and the reusable `fastify.authenticate` guard on the
|
||||
* root instance. Usage on a route:
|
||||
* { onRequest: [fastify.authenticate] }
|
||||
*/
|
||||
export async function registerAuth(app) {
|
||||
await app.register(fastifyJwt, {
|
||||
secret: app.config.jwt.secret,
|
||||
sign: { expiresIn: app.config.jwt.expiresIn },
|
||||
});
|
||||
|
||||
app.decorate('authenticate', async function authenticate(request) {
|
||||
try {
|
||||
await request.jwtVerify();
|
||||
} catch {
|
||||
throw unauthorized();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { HttpError } from '../lib/errors.js';
|
||||
|
||||
/**
|
||||
* Global error handling. Must be applied on the root instance (not through
|
||||
* `register`) so it covers every route. All routes answer with a consistent
|
||||
* JSON body `{ error, ... }`.
|
||||
*/
|
||||
export function registerErrorHandling(app) {
|
||||
app.setErrorHandler((error, request, reply) => {
|
||||
if (error instanceof HttpError) {
|
||||
return reply
|
||||
.code(error.status)
|
||||
.send({ error: error.message, ...(error.code ? { code: error.code } : {}) });
|
||||
}
|
||||
|
||||
// Schema validation errors (Fastify/ajv).
|
||||
if (error.validation) {
|
||||
return reply.code(400).send({
|
||||
error: 'Invalid request.',
|
||||
details: error.validation.map((v) => ({
|
||||
path: v.instancePath || v.params?.missingProperty || '',
|
||||
message: v.message,
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
// Known Fastify errors (payload too large, malformed JSON, ...).
|
||||
if (error.statusCode && error.statusCode < 500) {
|
||||
return reply.code(error.statusCode).send({ error: error.message });
|
||||
}
|
||||
|
||||
request.log.error(error);
|
||||
return reply.code(500).send({ error: 'Internal server error.' });
|
||||
});
|
||||
|
||||
app.setNotFoundHandler((request, reply) => {
|
||||
reply.code(404).send({ error: 'Route not found.' });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { conflict, notFound, unauthorized } from '../lib/errors.js';
|
||||
import { toPublicUser } from '../db/index.js';
|
||||
import { hashPassword, verifyPassword } from '../lib/passwords.js';
|
||||
|
||||
const registerSchema = {
|
||||
type: 'object',
|
||||
required: ['email', 'password'],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
email: { type: 'string', format: 'email', maxLength: 254 },
|
||||
password: { type: 'string', minLength: 8, maxLength: 200 },
|
||||
name: { type: 'string', minLength: 1, maxLength: 80 },
|
||||
},
|
||||
};
|
||||
|
||||
const loginSchema = {
|
||||
type: 'object',
|
||||
required: ['email', 'password'],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
email: { type: 'string', format: 'email', maxLength: 254 },
|
||||
password: { type: 'string', minLength: 1, maxLength: 200 },
|
||||
},
|
||||
};
|
||||
|
||||
const updateProfileSchema = {
|
||||
type: 'object',
|
||||
required: ['name'],
|
||||
additionalProperties: false,
|
||||
properties: { name: { type: 'string', minLength: 1, maxLength: 80 } },
|
||||
};
|
||||
|
||||
const changePasswordSchema = {
|
||||
type: 'object',
|
||||
required: ['currentPassword', 'newPassword'],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
currentPassword: { type: 'string', minLength: 1, maxLength: 200 },
|
||||
newPassword: { type: 'string', minLength: 8, maxLength: 200 },
|
||||
},
|
||||
};
|
||||
|
||||
/** Tighter limit on authentication routes (brute-force protection). */
|
||||
const authRateLimit = { rateLimit: { max: 20, timeWindow: '1 minute' } };
|
||||
|
||||
/**
|
||||
* Authentication routes (JWT).
|
||||
* @param {import('fastify').FastifyInstance} fastify
|
||||
*/
|
||||
export async function authRoutes(fastify) {
|
||||
const { db } = fastify;
|
||||
|
||||
const issueToken = (user) => fastify.jwt.sign({ sub: user.id, email: user.email });
|
||||
|
||||
fastify.post(
|
||||
'/api/auth/register',
|
||||
{ config: authRateLimit, schema: { body: registerSchema } },
|
||||
async (request, reply) => {
|
||||
const { email, password, name } = request.body;
|
||||
|
||||
if (db.findUserByEmail(email)) {
|
||||
throw conflict('An account already exists with this email.');
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(password);
|
||||
const user = db.createUser({ email, passwordHash, name: name ?? null });
|
||||
|
||||
return reply.code(201).send({ token: issueToken(user), user: toPublicUser(user) });
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
'/api/auth/login',
|
||||
{ config: authRateLimit, schema: { body: loginSchema } },
|
||||
async (request, reply) => {
|
||||
const { email, password } = request.body;
|
||||
|
||||
const user = db.findUserByEmail(email);
|
||||
// Verify even when the user is missing to keep the response time constant.
|
||||
const valid = await verifyPassword(password, user?.password_hash);
|
||||
if (!user || !valid) {
|
||||
throw unauthorized('Incorrect email or password.');
|
||||
}
|
||||
|
||||
return reply.send({ token: issueToken(user), user: toPublicUser(user) });
|
||||
},
|
||||
);
|
||||
|
||||
// The JWT is stateless: logging out means forgetting it on the client side.
|
||||
fastify.post('/api/auth/logout', { onRequest: [fastify.authenticate] }, async (_request, reply) => {
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
fastify.get('/api/auth/me', { onRequest: [fastify.authenticate] }, async (request) => {
|
||||
const user = db.findUserById(request.user.sub);
|
||||
if (!user) throw notFound('User not found.');
|
||||
return { user: toPublicUser(user) };
|
||||
});
|
||||
|
||||
fastify.patch(
|
||||
'/api/auth/me',
|
||||
{ onRequest: [fastify.authenticate], schema: { body: updateProfileSchema } },
|
||||
async (request) => {
|
||||
const user = db.updateUserName(request.user.sub, request.body.name);
|
||||
if (!user) throw notFound('User not found.');
|
||||
return { user: toPublicUser(user) };
|
||||
},
|
||||
);
|
||||
|
||||
fastify.post(
|
||||
'/api/auth/password',
|
||||
{ onRequest: [fastify.authenticate], schema: { body: changePasswordSchema } },
|
||||
async (request, reply) => {
|
||||
const { currentPassword, newPassword } = request.body;
|
||||
|
||||
const user = db.findUserByEmail(request.user.email);
|
||||
if (!user || !(await verifyPassword(currentPassword, user.password_hash))) {
|
||||
throw unauthorized('Incorrect current password.');
|
||||
}
|
||||
|
||||
db.updateUserPassword(user.id, await hashPassword(newPassword));
|
||||
return reply.code(204).send();
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { streamChatToClient } from '../services/chat-stream.js';
|
||||
import { OllamaError } from '../lib/errors.js';
|
||||
|
||||
const chatSchema = {
|
||||
type: 'object',
|
||||
required: ['message'],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
message: { type: 'string', minLength: 1, maxLength: 32000 },
|
||||
model: { type: 'string', maxLength: 120 },
|
||||
history: {
|
||||
type: 'array',
|
||||
maxItems: 50,
|
||||
items: {
|
||||
type: 'object',
|
||||
required: ['role', 'content'],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
role: { type: 'string', enum: ['user', 'assistant'] },
|
||||
content: { type: 'string', minLength: 1, maxLength: 32000 },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Stateless conversation routes: the authenticated user sends a prompt, the
|
||||
* backend relays it to Ollama and returns the answer.
|
||||
* @param {import('fastify').FastifyInstance} fastify
|
||||
*/
|
||||
export async function chatRoutes(fastify) {
|
||||
fastify.post(
|
||||
'/api/chat',
|
||||
{ onRequest: [fastify.authenticate], schema: { body: chatSchema } },
|
||||
async (request, reply) => {
|
||||
const { message, model, history = [] } = request.body;
|
||||
const messages = [...history, { role: 'user', content: message }];
|
||||
|
||||
try {
|
||||
const result = await fastify.ollama.chat({ messages, model });
|
||||
return reply.send({ reply: result.reply, model: result.model, user: { id: request.user.sub } });
|
||||
} catch (error) {
|
||||
if (error instanceof OllamaError) {
|
||||
return reply.code(error.status).send({ error: error.message });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// Streamed variant: the answer arrives chunk by chunk over SSE.
|
||||
fastify.post(
|
||||
'/api/chat/stream',
|
||||
{ onRequest: [fastify.authenticate], schema: { body: chatSchema } },
|
||||
async (request, reply) => {
|
||||
const { message, model, history = [] } = request.body;
|
||||
const messages = [...history, { role: 'user', content: message }];
|
||||
|
||||
return streamChatToClient({ ollama: fastify.ollama, reply, request, messages, model });
|
||||
},
|
||||
);
|
||||
|
||||
fastify.get('/api/chat/models', { onRequest: [fastify.authenticate] }, async () => {
|
||||
return fastify.ollama.listModels();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/**
|
||||
* Service health (public): database state and Ollama connectivity.
|
||||
* @param {import('fastify').FastifyInstance} fastify
|
||||
*/
|
||||
export async function healthRoutes(fastify) {
|
||||
fastify.get('/health', async () => {
|
||||
let database = 'ok';
|
||||
try {
|
||||
fastify.db.countUsers();
|
||||
} catch {
|
||||
database = 'error';
|
||||
}
|
||||
|
||||
const ollama = await fastify.ollama.listModels();
|
||||
|
||||
return {
|
||||
status: database === 'ok' ? 'ok' : 'degraded',
|
||||
database,
|
||||
ollama,
|
||||
uptime: Math.round(process.uptime()),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import { notFound, OllamaError } from '../lib/errors.js';
|
||||
import { toPublicMessage, toPublicProject } from '../db/index.js';
|
||||
import { streamChatToClient } from '../services/chat-stream.js';
|
||||
|
||||
const paramsSchema = {
|
||||
type: 'object',
|
||||
required: ['id'],
|
||||
properties: { id: { type: 'integer', minimum: 1 } },
|
||||
};
|
||||
|
||||
const createSchema = {
|
||||
type: 'object',
|
||||
required: ['name'],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
name: { type: 'string', minLength: 1, maxLength: 120 },
|
||||
description: { type: 'string', maxLength: 2000 },
|
||||
},
|
||||
};
|
||||
|
||||
const updateSchema = {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
minProperties: 1,
|
||||
properties: {
|
||||
name: { type: 'string', minLength: 1, maxLength: 120 },
|
||||
description: { type: 'string', maxLength: 2000 },
|
||||
},
|
||||
};
|
||||
|
||||
const listMessagesSchema = {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
limit: { type: 'integer', minimum: 1, maximum: 200, default: 50 },
|
||||
before: { type: 'integer', minimum: 1 },
|
||||
},
|
||||
};
|
||||
|
||||
const messageSchema = {
|
||||
type: 'object',
|
||||
required: ['content'],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
role: { type: 'string', enum: ['system', 'user', 'assistant'], default: 'user' },
|
||||
content: { type: 'string', minLength: 1, maxLength: 32000 },
|
||||
},
|
||||
};
|
||||
|
||||
const projectChatSchema = {
|
||||
type: 'object',
|
||||
required: ['message'],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
message: { type: 'string', minLength: 1, maxLength: 32000 },
|
||||
model: { type: 'string', maxLength: 120 },
|
||||
},
|
||||
};
|
||||
|
||||
/** Max number of project messages fed back to Ollama as context. */
|
||||
const CONTEXT_LIMIT = 40;
|
||||
|
||||
/**
|
||||
* Project routes: each project belongs to the authenticated user and its
|
||||
* messages form the context sent to Jarvis.
|
||||
* @param {import('fastify').FastifyInstance} fastify
|
||||
*/
|
||||
export async function projectRoutes(fastify) {
|
||||
const { db } = fastify;
|
||||
const auth = { onRequest: [fastify.authenticate] };
|
||||
|
||||
// Returns the current user's project or throws a 404.
|
||||
function requireProject(request) {
|
||||
const project = db.getProjectForUser(request.params.id, request.user.sub);
|
||||
if (!project) throw notFound('Project not found.');
|
||||
return project;
|
||||
}
|
||||
|
||||
/** Context sent to Ollama: project history + the new prompt. */
|
||||
function buildMessages(projectId, message) {
|
||||
const history = db
|
||||
.listMessages(projectId, { limit: CONTEXT_LIMIT })
|
||||
.map((m) => ({ role: m.role, content: m.content }));
|
||||
return [...history, { role: 'user', content: message }];
|
||||
}
|
||||
|
||||
fastify.post('/api/projects', { ...auth, schema: { body: createSchema } }, async (request, reply) => {
|
||||
const project = db.createProject({
|
||||
userId: request.user.sub,
|
||||
name: request.body.name,
|
||||
description: request.body.description ?? null,
|
||||
});
|
||||
return reply.code(201).send({ project: toPublicProject(project) });
|
||||
});
|
||||
|
||||
fastify.get('/api/projects', auth, async (request) => {
|
||||
return { projects: db.listProjects(request.user.sub).map(toPublicProject) };
|
||||
});
|
||||
|
||||
fastify.get('/api/projects/:id', { ...auth, schema: { params: paramsSchema } }, async (request) => {
|
||||
return { project: toPublicProject(requireProject(request)) };
|
||||
});
|
||||
|
||||
fastify.get('/api/projects/:id/stats', { ...auth, schema: { params: paramsSchema } }, async (request) => {
|
||||
const project = requireProject(request);
|
||||
return { projectId: project.id, stats: db.projectStats(project.id) };
|
||||
});
|
||||
|
||||
fastify.patch(
|
||||
'/api/projects/:id',
|
||||
{ ...auth, schema: { params: paramsSchema, body: updateSchema } },
|
||||
async (request) => {
|
||||
const project = requireProject(request);
|
||||
const updated = db.updateProject(project.id, request.user.sub, request.body);
|
||||
return { project: toPublicProject(updated) };
|
||||
},
|
||||
);
|
||||
|
||||
fastify.delete('/api/projects/:id', { ...auth, schema: { params: paramsSchema } }, async (request, reply) => {
|
||||
const project = requireProject(request);
|
||||
db.deleteProject(project.id, request.user.sub);
|
||||
return reply.code(204).send();
|
||||
});
|
||||
|
||||
// Project context, paginated (newest page computed from the most recent message).
|
||||
fastify.get(
|
||||
'/api/projects/:id/messages',
|
||||
{ ...auth, schema: { params: paramsSchema, querystring: listMessagesSchema } },
|
||||
async (request) => {
|
||||
const project = requireProject(request);
|
||||
const { limit = 50, before = null } = request.query;
|
||||
|
||||
const rows = db.listMessages(project.id, { limit, before });
|
||||
const oldestId = rows[0]?.id ?? null;
|
||||
const hasMore = oldestId != null && db.hasOlderMessages(project.id, oldestId);
|
||||
|
||||
return {
|
||||
projectId: project.id,
|
||||
messages: rows.map(toPublicMessage),
|
||||
hasMore,
|
||||
oldestId,
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
// Manually append a message to the context (e.g. a system note).
|
||||
fastify.post(
|
||||
'/api/projects/:id/messages',
|
||||
{ ...auth, schema: { params: paramsSchema, body: messageSchema } },
|
||||
async (request, reply) => {
|
||||
const project = requireProject(request);
|
||||
const message = db.addMessage(project.id, {
|
||||
role: request.body.role ?? 'user',
|
||||
content: request.body.content,
|
||||
});
|
||||
db.touchProject(project.id);
|
||||
return reply.code(201).send({ message: toPublicMessage(message) });
|
||||
},
|
||||
);
|
||||
|
||||
// Clears the context (removes every message of the project).
|
||||
fastify.delete(
|
||||
'/api/projects/:id/messages',
|
||||
{ ...auth, schema: { params: paramsSchema } },
|
||||
async (request) => {
|
||||
const project = requireProject(request);
|
||||
return { deleted: db.deleteMessages(project.id) };
|
||||
},
|
||||
);
|
||||
|
||||
// Chat within the project context: the project history is sent to Ollama.
|
||||
fastify.post(
|
||||
'/api/projects/:id/chat',
|
||||
{ ...auth, schema: { params: paramsSchema, body: projectChatSchema } },
|
||||
async (request, reply) => {
|
||||
const project = requireProject(request);
|
||||
const { message, model } = request.body;
|
||||
const messages = buildMessages(project.id, message);
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = await fastify.ollama.chat({ messages, model });
|
||||
} catch (error) {
|
||||
if (error instanceof OllamaError) {
|
||||
return reply.code(error.status).send({ error: error.message });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Persist only after success to avoid orphan messages.
|
||||
const userMessage = db.addMessage(project.id, { role: 'user', content: message });
|
||||
const assistantMessage = db.addMessage(project.id, { role: 'assistant', content: result.reply });
|
||||
db.touchProject(project.id);
|
||||
|
||||
return reply.send({
|
||||
reply: result.reply,
|
||||
model: result.model,
|
||||
projectId: project.id,
|
||||
messages: [toPublicMessage(userMessage), toPublicMessage(assistantMessage)],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Same, but streamed: each chunk is sent as soon as Ollama produces it.
|
||||
fastify.post(
|
||||
'/api/projects/:id/chat/stream',
|
||||
{ ...auth, schema: { params: paramsSchema, body: projectChatSchema } },
|
||||
async (request, reply) => {
|
||||
const project = requireProject(request);
|
||||
const { message, model } = request.body;
|
||||
const messages = buildMessages(project.id, message);
|
||||
|
||||
return streamChatToClient({
|
||||
ollama: fastify.ollama,
|
||||
reply,
|
||||
request,
|
||||
messages,
|
||||
model,
|
||||
// Persisted only once the stream completed successfully.
|
||||
onComplete: (fullText) => {
|
||||
const userMessage = db.addMessage(project.id, { role: 'user', content: message });
|
||||
const assistantMessage = db.addMessage(project.id, { role: 'assistant', content: fullText });
|
||||
db.touchProject(project.id);
|
||||
return {
|
||||
projectId: project.id,
|
||||
messages: [toPublicMessage(userMessage), toPublicMessage(assistantMessage)],
|
||||
};
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { buildApp } from './app.js';
|
||||
import { loadConfig } from './config.js';
|
||||
import { createDatabase } from './db/index.js';
|
||||
import { createOllama } from './services/ollama.js';
|
||||
|
||||
const config = loadConfig();
|
||||
const db = createDatabase(config.dbPath);
|
||||
const ollama = createOllama(config);
|
||||
|
||||
const app = await buildApp({ config, db, ollama });
|
||||
|
||||
// Graceful shutdown: let in-flight requests finish first.
|
||||
let shuttingDown = false;
|
||||
for (const signal of ['SIGINT', 'SIGTERM']) {
|
||||
process.on(signal, async () => {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
app.log.info(`${signal} received, shutting down…`);
|
||||
try {
|
||||
await app.close();
|
||||
process.exit(0);
|
||||
} catch (error) {
|
||||
app.log.error(error);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
await app.listen({ port: config.port, host: config.host });
|
||||
} catch (error) {
|
||||
app.log.error(error);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { OllamaError } from '../lib/errors.js';
|
||||
|
||||
/**
|
||||
* Streams Jarvis' answer to the client as SSE (Server-Sent Events), chunk by
|
||||
* chunk, then closes the stream. Aborts the Ollama request if the client
|
||||
* disconnects before we are done.
|
||||
*
|
||||
* Events:
|
||||
* event: delta data: { "content": "text chunk" }
|
||||
* event: done data: { ...result of onComplete() }
|
||||
* event: error data: { "error": "...", "partial": "..." }
|
||||
*
|
||||
* @param {object} options
|
||||
* @param {{ openChatStream: Function, readStream: Function }} options.ollama
|
||||
* @param {import('fastify').FastifyReply} options.reply
|
||||
* @param {import('fastify').FastifyRequest} options.request
|
||||
* @param {Array<{role: string, content: string}>} options.messages
|
||||
* @param {string} [options.model]
|
||||
* @param {(fullText: string) => Promise<object>|object} [options.onComplete]
|
||||
*/
|
||||
export async function streamChatToClient({ ollama, reply, request, messages, model, onComplete }) {
|
||||
const controller = new AbortController();
|
||||
|
||||
// Open the Ollama stream before switching to SSE: if Ollama is unreachable we
|
||||
// can still answer with a real HTTP error code.
|
||||
let opened;
|
||||
try {
|
||||
opened = await ollama.openChatStream({ messages, model, signal: controller.signal });
|
||||
} catch (error) {
|
||||
const status = error instanceof OllamaError ? error.status : 500;
|
||||
const message = error instanceof Error ? error.message : 'Internal server error.';
|
||||
return reply.code(status).send({ error: message });
|
||||
}
|
||||
|
||||
const raw = reply.raw;
|
||||
reply.hijack();
|
||||
|
||||
raw.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream; charset=utf-8',
|
||||
'Cache-Control': 'no-cache, no-transform',
|
||||
Connection: 'keep-alive',
|
||||
'X-Accel-Buffering': 'no', // disable buffering on reverse proxies (nginx)
|
||||
});
|
||||
|
||||
// Only a close before we finish means the client went away; a close triggered
|
||||
// by our own raw.end() must not abort anything.
|
||||
const onClientClose = () => {
|
||||
if (!raw.writableEnded) controller.abort();
|
||||
};
|
||||
raw.on('close', onClientClose);
|
||||
|
||||
const send = (event, data) => {
|
||||
if (raw.writableEnded) return false;
|
||||
return raw.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
|
||||
};
|
||||
|
||||
// Opening comment: the client receives the headers immediately.
|
||||
raw.write(': stream open\n\n');
|
||||
|
||||
let fullText = '';
|
||||
try {
|
||||
for await (const chunk of ollama.readStream(opened.response)) {
|
||||
if (raw.writableEnded || controller.signal.aborted) break;
|
||||
|
||||
const delta = chunk?.message?.content ?? '';
|
||||
if (delta) {
|
||||
fullText += delta;
|
||||
send('delta', { content: delta });
|
||||
}
|
||||
|
||||
if (chunk?.done) break;
|
||||
}
|
||||
|
||||
if (controller.signal.aborted || raw.writableEnded) return;
|
||||
|
||||
const extra = onComplete ? await onComplete(fullText) : {};
|
||||
send('done', { reply: fullText, model: opened.model, ...extra });
|
||||
} catch (error) {
|
||||
if (!controller.signal.aborted) {
|
||||
request.log.error(error);
|
||||
send('error', {
|
||||
error: error instanceof Error ? error.message : 'Error while streaming.',
|
||||
partial: fullText,
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
raw.off('close', onClientClose);
|
||||
if (!raw.writableEnded) raw.end();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { OllamaError } from '../lib/errors.js';
|
||||
|
||||
function safeParse(line) {
|
||||
try {
|
||||
return JSON.parse(line);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ollama client. Built from the config so it can point at a mock during tests.
|
||||
*/
|
||||
export function createOllama(config) {
|
||||
const baseUrl = config.ollama.url.replace(/\/+$/, '');
|
||||
|
||||
function buildPayload(messages, model, stream) {
|
||||
return {
|
||||
model: model ?? config.ollama.model,
|
||||
stream,
|
||||
messages: [{ role: 'system', content: config.ollama.systemPrompt }, ...messages],
|
||||
};
|
||||
}
|
||||
|
||||
async function fetchChat(payload, signal) {
|
||||
let response;
|
||||
try {
|
||||
response = await fetch(`${baseUrl}/api/chat`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(payload),
|
||||
signal,
|
||||
});
|
||||
} catch (cause) {
|
||||
// A client-side abort is not an Ollama failure: let it bubble up.
|
||||
if (cause?.name === 'AbortError') throw cause;
|
||||
throw new OllamaError(`Cannot reach Ollama (${baseUrl}).`, 502);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const detail = await response.text().catch(() => '');
|
||||
throw new OllamaError(
|
||||
`Ollama answered ${response.status}${detail ? `: ${detail}` : ''}.`,
|
||||
response.status === 404 ? 404 : 502,
|
||||
);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/** Full answer (blocking, non-streamed). */
|
||||
async function chat({ messages, model, signal }) {
|
||||
const payload = buildPayload(messages, model, false);
|
||||
const response = await fetchChat(payload, signal);
|
||||
const raw = await response.json();
|
||||
return { reply: raw?.message?.content ?? '', model: raw?.model ?? payload.model, raw };
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens Ollama's streamed response. Only the headers are awaited, so a clean
|
||||
* HTTP error can still be returned when Ollama is unreachable; chunks are then
|
||||
* produced with `readStream`.
|
||||
*/
|
||||
async function openChatStream({ messages, model, signal }) {
|
||||
const payload = buildPayload(messages, model, true);
|
||||
const response = await fetchChat(payload, signal);
|
||||
return { model: payload.model, response };
|
||||
}
|
||||
|
||||
/** Checks that Ollama answers and lists the available models. */
|
||||
async function listModels() {
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}/api/tags`);
|
||||
if (!response.ok) return { reachable: false, models: [] };
|
||||
const data = await response.json();
|
||||
return { reachable: true, models: (data?.models ?? []).map((m) => m.name) };
|
||||
} catch {
|
||||
return { reachable: false, models: [] };
|
||||
}
|
||||
}
|
||||
|
||||
return { chat, openChatStream, readStream, listModels };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads Ollama's NDJSON stream and yields each JSON object as it arrives.
|
||||
* Every chunk looks like:
|
||||
* { message: { role: 'assistant', content: 'Bon' }, done: false }
|
||||
* ...
|
||||
* { done: true, ... }
|
||||
*/
|
||||
export async function* readStream(response) {
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
try {
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
|
||||
let newline;
|
||||
while ((newline = buffer.indexOf('\n')) !== -1) {
|
||||
const line = buffer.slice(0, newline).trim();
|
||||
buffer = buffer.slice(newline + 1);
|
||||
if (!line) continue;
|
||||
const parsed = safeParse(line);
|
||||
if (parsed) yield parsed;
|
||||
}
|
||||
}
|
||||
|
||||
const tail = buffer.trim();
|
||||
if (tail) {
|
||||
const parsed = safeParse(tail);
|
||||
if (parsed) yield parsed;
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock?.();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user