Repository Public
1#!/usr/bin/env node2// Author: Simon-Pierre Boucher — contact@spboucher.ai3// File: Scripts/dev-ai-stub.mjs4// Description: Development-only scripted stand-in for the local AI provider of the dev backend (OpenAI-compatible `/chat/completions` and5// `/embeddings`). It never calls a model: each task of the backend's prompts (summary, replies, triage, write) gets a fixed, schema-valid6// answer, so the apps' self-test exercises the intelligence surfaces deterministically and at no cost.7//8// Usage: node Scripts/dev-ai-stub.mjs (listens on SPMAIL_AI_STUB_PORT, default 8853)9// Point the dev backend at it: SPMAIL_AI_LOCAL_URL=http://127.0.0.1:8853/v1 SPMAIL_AI_LOCAL_MODEL=stub-scripted10// SPMAIL_AI_STUB_MODE=ok (default) | down (every call answers 503) | slow (answers after 4 s)11import http from "node:http"1213const PORT = Number(process.env.SPMAIL_AI_STUB_PORT ?? 8853)14const MODE = process.env.SPMAIL_AI_STUB_MODE ?? "ok"15const MODEL = "stub-scripted"16const sleep = (ms) => new Promise((r) => setTimeout(r, ms))1718function answer(system, user) {19 if (system.includes('"suggestions"')) {20 const tone = /Tone: (\w+)/.exec(system)?.[1] ?? "professional"21 const fr = system.includes("French")22 const texts = fr23 ? [`Bonjour,\n\nC’est entendu, je confirme (ton ${tone}).\n\nCordialement`, `Bonjour,\n\nMalheureusement, ce ne sera pas possible avant le [date].\n\nCordialement`, `Bonjour,\n\nPourriez-vous préciser le contexte avant que je réponde ?\n\nMerci`]24 : [`Hello,\n\nUnderstood, I confirm (${tone} tone).\n\nBest regards`, `Hello,\n\nUnfortunately this will not be possible before [date].\n\nBest regards`, `Hello,\n\nCould you give me more context before I answer?\n\nThanks`]25 return JSON.stringify({ suggestions: texts.map((text) => ({ subject: null, text })) })26 }27 if (system.includes('"action_items"')) {28 const fr = system.includes("French")29 return JSON.stringify({30 summary: fr ? "Résumé scripté : l’expéditeur propose une rencontre et demande une confirmation. Aucune décision ferme n’est prise." : "Scripted summary: the sender proposes a meeting and asks for a confirmation. No firm decision is made.",31 decisions: [fr ? "Tenir la rencontre par visioconférence" : "Hold the meeting by video call"],32 action_items: [{ text: fr ? "Confirmer la date de la rencontre" : "Confirm the meeting date", owner: null, due: fr ? "vendredi" : "Friday" }, { text: fr ? "Envoyer l’ordre du jour" : "Send the agenda", owner: null, due: null }],33 deadlines: [{ text: fr ? "Réponse attendue" : "Answer expected", date: fr ? "vendredi" : "Friday" }],34 timeline: [{ at: null, who: "Essai", what: fr ? "Propose une rencontre." : "Proposes a meeting." }],35 })36 }37 if (system.includes('"items"')) {38 const n = Number(/classify each of the (\d+) e-mails/.exec(system)?.[1] ?? (user.match(/E-mail \d+:/g) ?? []).length)39 const items = Array.from({ length: n }, (_, i) => ({ n: i + 1, category: i % 2 === 0 ? "work" : "newsletter", needs_action: i % 2 === 0, important: i === 0, reason: "Classement scripté." }))40 return JSON.stringify({ items })41 }42 if (system.includes('"subjects"')) return JSON.stringify({ subjects: ["Objet scripté 1", "Objet scripté 2", "Objet scripté 3", "Objet scripté 4"] })43 return "Texte scripté."44}4546// deterministic bag-of-words vector (the backend only needs a stable, non-empty embedding)47function embed(text) {48 const v = new Array(64).fill(0)49 for (const w of String(text).toLowerCase().split(/[^\p{L}\p{N}]+/u)) {50 if (!w) continue51 let h = 216613626152 for (const c of Buffer.from(w)) h = Math.imul(h ^ c, 16777619) >>> 053 v[h % 64] += 154 }55 const norm = Math.hypot(...v) || 156 return v.map((x) => x / norm)57}5859http.createServer(async (req, res) => {60 let raw = ""61 for await (const c of req) raw += c62 const send = (status, body) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(body)) }63 if (MODE === "down") return send(503, { error: "stub down" })64 if (MODE === "slow") await sleep(4000)65 let body = {}66 try { body = JSON.parse(raw || "{}") } catch { return send(400, { error: "bad json" }) }67 if (req.method === "POST" && req.url?.endsWith("/chat/completions")) {68 const system = body.messages?.find((m) => m.role === "system")?.content ?? ""69 const user = body.messages?.filter((m) => m.role === "user").map((m) => m.content).join("\n") ?? ""70 console.log(new Date().toISOString(), "chat", system.length, user.length)71 return send(200, { model: MODEL, choices: [{ message: { role: "assistant", content: answer(system, user) }, finish_reason: "stop" }], usage: { prompt_tokens: 10, completion_tokens: 10 } })72 }73 if (req.method === "POST" && req.url?.endsWith("/embeddings")) {74 const input = Array.isArray(body.input) ? body.input : [body.input]75 return send(200, { model: MODEL, data: input.map((t, index) => ({ index, embedding: embed(t) })) })76 }77 if (req.url?.endsWith("/models")) return send(200, { data: [{ id: MODEL }] })78 send(404, { error: "not found" })79}).listen(PORT, "127.0.0.1", () => console.log(`ai stub on 127.0.0.1:${PORT} (${MODE})`))80