Bauauftrag Abschnitt 4. Link und/oder bis zu drei Screenshots rein, ein Druck auf „Mit KI ausfuellen": - Claude Haiku 5.5 (offizielles SDK @anthropic-ai/sdk 1.3.0) mit fester Antwortform (json_schema): Titel, drei Textvarianten (seriös/Hype/kurz), Preis, Waehrung, MwSt-Angabe, Kategorie, Kartenform, Framework, Abo, Escrow, Produktbild (Screenshot-Bereich oder Shop-Kandidat), Unsicherheiten - bleiben Titel/Preis/Bild unsicher: einmal Sonnet 5.5 (mit serverseitiger Rueckfall-Absicherung), uebernommen nur bei weniger Unsicherheit - Pruefungen warnen, entscheiden nicht: Qbox, Abo, Budget, MwSt, Fremd- waehrung (EZB-Tageskurs, ohne Kurs: kein geratener Betrag), doppelt - „Preis geprueft" ist Pflicht, bevor ein KI-Preis live geht - ohne Schluessel: Link-Daten (JSON-LD/OG/Bilder) im Handbetrieb Sicherer Abruf fremder Seiten: nur http/https auf 80/443, keine Zugangs- daten in der Adresse, innere Netze gesperrt -- geprueft BEIM VERBINDEN (gegen DNS-Rebinding) und bei jeder Weiterleitung; Gesamtfrist, Groessen- grenze. Gemessen: 10 Angriffslinks abgewiesen, 127.0.0.1.nip.io auch. Nebenbei: express 4.22.3 / body-parser 1.20.9 -- die Luecke GHSA-27r3- jxmh-p828 (DoS ueber komprimierte Anfragen) war auf dem Server erreichbar (express.json entpackt standardmaessig). npm audit: 0. Der allgemeine JSON-Leser (1 MB) laesst genau den KI-Weg aus (12 MB fuer drei Screenshots); jeder andere Weg bleibt bei 1 MB (mit Gegenprobe). Pruefungen: pruef-serverziele-ki 62/0 (Sabotagen: ohne Pruefung beim Verbinden und ohne JSON-Ausnahme je rot), pruef-serverziele 84/0, mess-serverziele 51/0, pruef-reaktion 638/0 (fand eine waagerecht rollende Galerie -- jetzt umbrechend), -schmal 56/0, -stil 46/0, pruef-spenden 218/0, css-klassen 0, portnummern 41/0. Co-Authored-By: Claude Opus 5.5 <[email protected]>
628 lines
31 KiB
JavaScript
628 lines
31 KiB
JavaScript
/* =====================================================================
|
|
SERVER-ZIELE — die KI (27.10.2026, Stufe 2)
|
|
|
|
Filipe: „fang mit der ki an." Grundlage ist Abschnitt 4 seines
|
|
Bauauftrags „BLUE MOON · Server-Ziele": Link oder Screenshot rein,
|
|
die KI schreibt Titel und drei Texte, findet Preis, Kategorie und
|
|
Framework, sucht das Produktbild aus -- und die Pruefungen warnen,
|
|
ohne zu entscheiden.
|
|
|
|
Drei Teile, und jeder ist fuer sich pruefbar:
|
|
1. DER SICHERE ABRUF einer fremden Seite (Abschnitt 4e)
|
|
2. DAS LESEN der Seite: JSON-LD, Open Graph, Bilder, Text
|
|
3. DER KI-AUFRUF mit fester Antwortform -- und die Pruefungen
|
|
|
|
---------------------------------------------------------------------
|
|
OHNE SCHLUESSEL GEHT ES TROTZDEM (Abschnitt 4e: „darf nie komplett
|
|
ausfallen"). Steht kein ANTHROPIC_API_KEY in der Umgebung, liefert der
|
|
Link-Weg, was die Seite selbst sagt (Titel, Beschreibung, Bilder,
|
|
Preis aus den Daten), und die Regie sagt, dass die KI fehlt. Ein
|
|
Screenshot ohne KI ist dagegen nur ein Bild -- das wird gesagt, nicht
|
|
geraten.
|
|
===================================================================== */
|
|
import { request as httpRequest } from "node:http";
|
|
import { request as httpsRequest } from "node:https";
|
|
import { lookup as dnsLookup } from "node:dns";
|
|
import { isIP } from "node:net";
|
|
import { createGunzip, createInflate, createBrotliDecompress } from "node:zlib";
|
|
import Anthropic from "@anthropic-ai/sdk";
|
|
|
|
/* =====================================================================
|
|
1. DER SICHERE ABRUF
|
|
=====================================================================
|
|
|
|
Ein Server, der auf Zuruf fremde Adressen abruft, ist eine Tuer nach
|
|
innen: „http://127.0.0.1:4100/workspace/api/…" oder die
|
|
Metadaten-Adresse eines Rechenzentrums (169.254.169.254) waeren von
|
|
aussen nicht erreichbar -- ueber diesen Abruf schon.
|
|
|
|
GEPRUEFT WIRD BEIM VERBINDEN, NICHT VORHER. Eine Pruefung des Namens
|
|
und danach ein Abruf, der den Namen NOCH EINMAL aufloest, laesst eine
|
|
Luecke: Der Name kann beim zweiten Mal woandershin zeigen (DNS-
|
|
Rebinding). Deshalb sitzt die Pruefung im `lookup` der Verbindung
|
|
selbst -- dieselbe Aufloesung, die verbunden wird, wird geprueft.
|
|
Und JEDE Weiterleitung geht wieder durch dieselbe Tuer. */
|
|
|
|
/** Liegt diese Adresse in einem Netz, das von aussen nie gemeint sein kann? */
|
|
export function adresseGesperrt(ip) {
|
|
const f = isIP(ip);
|
|
if (f === 4) {
|
|
const t = ip.split(".").map(Number);
|
|
const [a, b] = t;
|
|
return a === 0 || a === 10 || a === 127 || a >= 224
|
|
|| (a === 100 && b >= 64 && b <= 127) // CGNAT
|
|
|| (a === 169 && b === 254) // Link-lokal, Metadaten
|
|
|| (a === 172 && b >= 16 && b <= 31)
|
|
|| (a === 192 && b === 168)
|
|
|| (a === 192 && b === 0 && (t[2] === 0 || t[2] === 2))
|
|
|| (a === 198 && (b === 18 || b === 19))
|
|
|| (a === 198 && b === 51 && t[2] === 100)
|
|
|| (a === 203 && b === 0 && t[2] === 113);
|
|
}
|
|
if (f === 6) {
|
|
const x = ip.toLowerCase();
|
|
/* IPv4 IM IPv6-GEWAND: ::ffff:127.0.0.1 ist 127.0.0.1. */
|
|
const v4 = x.match(/^(?:::ffff:|::|64:ff9b::)(\d+\.\d+\.\d+\.\d+)$/);
|
|
if (v4) return adresseGesperrt(v4[1]);
|
|
const hex = x.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
|
|
if (hex) {
|
|
const n1 = parseInt(hex[1], 16), n2 = parseInt(hex[2], 16);
|
|
return adresseGesperrt(`${n1 >> 8}.${n1 & 255}.${n2 >> 8}.${n2 & 255}`);
|
|
}
|
|
return x === "::" || x === "::1" || /^f[cd]/.test(x) || /^fe[89ab]/.test(x)
|
|
|| /^ff/.test(x) || /^2001:0?db8:/.test(x) || /^::ffff:/.test(x);
|
|
}
|
|
return true; // keine Adresse: gesperrt -- im Zweifel nie
|
|
}
|
|
|
|
/** Der `lookup` fuer die Verbindung: loest auf und weist gesperrte Ziele ab. */
|
|
function sichererLookup(name, opt, fertig) {
|
|
const o = typeof opt === "object" ? opt : {};
|
|
dnsLookup(name, { all: true, family: o.family || 0 }, (f, liste) => {
|
|
if (f) return fertig(f);
|
|
const gut = (liste || []).filter((z) => !adresseGesperrt(z.address));
|
|
/* ALLE ODER KEINE. Gibt ein Name eine erlaubte und eine gesperrte
|
|
Adresse zurueck, ist das kein Versehen, sondern ein Versuch. */
|
|
if (!gut.length || gut.length !== liste.length) {
|
|
const e = new Error("adresse_gesperrt");
|
|
e.code = "ADRESSE_GESPERRT";
|
|
return fertig(e);
|
|
}
|
|
if (o.all) return fertig(null, gut);
|
|
return fertig(null, gut[0].address, gut[0].family);
|
|
});
|
|
}
|
|
|
|
export class AbrufFehler extends Error {
|
|
constructor(code, text) { super(text || code); this.code = code; }
|
|
}
|
|
|
|
/** Darf diese Adresse ueberhaupt angefragt werden (vor jeder Verbindung)? */
|
|
export function adressePruefen(roh) {
|
|
let u;
|
|
try { u = new URL(String(roh || "").trim()); } catch { throw new AbrufFehler("link_unklar"); }
|
|
if (!["http:", "https:"].includes(u.protocol)) throw new AbrufFehler("link_unklar");
|
|
if (u.username || u.password) throw new AbrufFehler("link_unklar");
|
|
if (u.port && !["80", "443"].includes(u.port)) throw new AbrufFehler("adresse_gesperrt");
|
|
const host = u.hostname.replace(/^\[|\]$/g, "");
|
|
/* Eine Zahl als Name („2130706433", „0x7f.1") loest der Browser zu
|
|
127.0.0.1 auf. Wer so schreibt, meint keinen Shop. */
|
|
if (isIP(host)) { if (adresseGesperrt(host)) throw new AbrufFehler("adresse_gesperrt"); }
|
|
else if (/^[\d.x]+$/i.test(host) || !host.includes(".") || /\.(local|internal|localhost)$/i.test(host)
|
|
|| host === "localhost") throw new AbrufFehler("adresse_gesperrt");
|
|
return u;
|
|
}
|
|
|
|
const BROWSER = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
|
+ "(KHTML, like Gecko) Chrome/131.0 Safari/537.36";
|
|
|
|
/** Eine fremde Adresse holen -- mit Grenzen fuer Groesse, Zeit und Wege. */
|
|
export async function holen(roh, { max = 3 * 1024 * 1024, frist = 12_000, annehmen = "text/html,*/*;q=0.8" } = {}) {
|
|
let u = adressePruefen(roh);
|
|
const ende = Date.now() + frist;
|
|
for (let weg = 0; weg < 5; weg++) {
|
|
const a = await new Promise((fertig, schief) => {
|
|
const anf = (u.protocol === "https:" ? httpsRequest : httpRequest)(u, {
|
|
method: "GET",
|
|
lookup: sichererLookup,
|
|
headers: {
|
|
"User-Agent": BROWSER,
|
|
Accept: annehmen,
|
|
"Accept-Language": "de-DE,de;q=0.9,en;q=0.8",
|
|
"Accept-Encoding": "gzip, deflate, br",
|
|
},
|
|
timeout: Math.max(1000, ende - Date.now()),
|
|
}, (antwort) => {
|
|
const status = antwort.statusCode || 0;
|
|
if (status >= 300 && status < 400 && antwort.headers.location) {
|
|
antwort.resume();
|
|
return fertig({ weiter: antwort.headers.location });
|
|
}
|
|
const art = String(antwort.headers["content-encoding"] || "").toLowerCase();
|
|
let strom = antwort;
|
|
if (art === "gzip") strom = antwort.pipe(createGunzip());
|
|
else if (art === "deflate") strom = antwort.pipe(createInflate());
|
|
else if (art === "br") strom = antwort.pipe(createBrotliDecompress());
|
|
const teile = [];
|
|
let groesse = 0;
|
|
strom.on("data", (t) => {
|
|
groesse += t.length;
|
|
if (groesse > max) { anf.destroy(); schief(new AbrufFehler("zu_gross")); return; }
|
|
teile.push(t);
|
|
});
|
|
strom.on("end", () => fertig({ status, kopf: antwort.headers, inhalt: Buffer.concat(teile) }));
|
|
strom.on("error", () => schief(new AbrufFehler("abruf_kaputt")));
|
|
});
|
|
/* EINE GESAMTFRIST, nicht nur eine Leerlauf-Frist: Ein Server, der
|
|
jede Sekunde ein Byte schickt, waere nie „im Leerlauf" und hielte
|
|
den Abruf unbegrenzt offen. */
|
|
const uhr = setTimeout(() => { anf.destroy(); schief(new AbrufFehler("zu_langsam")); },
|
|
Math.max(1000, ende - Date.now()));
|
|
anf.on("close", () => clearTimeout(uhr));
|
|
anf.on("timeout", () => { anf.destroy(); schief(new AbrufFehler("zu_langsam")); });
|
|
anf.on("error", (f) => schief(f?.code === "ADRESSE_GESPERRT" ? new AbrufFehler("adresse_gesperrt")
|
|
: f instanceof AbrufFehler ? f : new AbrufFehler("nicht_erreichbar", f?.message)));
|
|
anf.end();
|
|
});
|
|
if (a.weiter) {
|
|
/* JEDE WEITERLEITUNG GEHT WIEDER DURCH DIE TUER. Ein Shop, der auf
|
|
„http://127.0.0.1/" weiterleitet, wird genau dort abgewiesen. */
|
|
u = adressePruefen(new URL(a.weiter, u).href);
|
|
continue;
|
|
}
|
|
return { ...a, url: u.href };
|
|
}
|
|
throw new AbrufFehler("zu_viele_weiterleitungen");
|
|
}
|
|
|
|
/* =====================================================================
|
|
2. DAS LESEN DER SEITE
|
|
===================================================================== */
|
|
const ent = (s) => String(s || "")
|
|
.replace(/&/g, "&").replace(/"/g, '"').replace(/�?39;|'/g, "'")
|
|
.replace(/</g, "<").replace(/>/g, ">").replace(/ /g, " ")
|
|
.replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)));
|
|
|
|
function absolut(src, basis) {
|
|
try {
|
|
const u = new URL(ent(src).trim(), basis);
|
|
return ["http:", "https:"].includes(u.protocol) ? u.href : "";
|
|
} catch { return ""; }
|
|
}
|
|
|
|
/** Eine geblockte Seite erkennen (Cloudflare & Co.). Dann ist der
|
|
* Inhalt eine Wartesaal-Seite und nichts daraus darf gelesen werden. */
|
|
export function seiteBlockt(status, html) {
|
|
return (status === 403 || status === 429 || status === 503)
|
|
&& /cf-chl|challenge-platform|Just a moment|Attention Required|captcha/i.test(html);
|
|
}
|
|
|
|
/** Was eine Produktseite ueber sich selbst sagt -- ohne KI. */
|
|
export function seiteAuswerten(html, basis) {
|
|
const h = String(html || "");
|
|
const meta = {};
|
|
for (const m of h.matchAll(/<meta\b[^>]*>/gi)) {
|
|
const t = m[0];
|
|
const name = (t.match(/\b(?:property|name|itemprop)\s*=\s*["']([^"']+)["']/i) || [])[1];
|
|
const inhalt = (t.match(/\bcontent\s*=\s*["']([^"']*)["']/i) || [])[1];
|
|
if (name && inhalt !== undefined && !(name.toLowerCase() in meta)) meta[name.toLowerCase()] = ent(inhalt);
|
|
}
|
|
/* JSON-LD: der verlaesslichste Teil, wenn es ihn gibt -- er ist fuer
|
|
Suchmaschinen geschrieben und deshalb meist vollstaendig. */
|
|
let produkt = null;
|
|
const besuchen = (x) => {
|
|
if (!x || typeof x !== "object" || produkt) return;
|
|
if (Array.isArray(x)) { x.forEach(besuchen); return; }
|
|
const typ = [].concat(x["@type"] || []).map(String);
|
|
if (typ.includes("Product")) { produkt = x; return; }
|
|
if (x["@graph"]) besuchen(x["@graph"]);
|
|
};
|
|
for (const m of h.matchAll(/<script\b[^>]*type\s*=\s*["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi)) {
|
|
try { besuchen(JSON.parse(m[1].trim())); } catch { /* kaputtes JSON-LD ist kein Grund aufzugeben */ }
|
|
}
|
|
const angebot = produkt ? [].concat(produkt.offers || [])[0] || null : null;
|
|
const preisRoh = angebot?.price ?? angebot?.lowPrice ?? meta["product:price:amount"] ?? meta["og:price:amount"];
|
|
let preis = preisRoh !== undefined && preisRoh !== null && preisRoh !== "" ? Number(String(preisRoh).replace(",", ".")) : null;
|
|
let waehrung = angebot?.priceCurrency || meta["product:price:currency"] || meta["og:price:currency"] || null;
|
|
const titel = ent(produkt?.name || meta["og:title"] || (h.match(/<title[^>]*>([\s\S]*?)<\/title>/i) || [])[1] || "")
|
|
.replace(/\s+/g, " ").trim();
|
|
const beschreibung = ent(produkt?.description || meta["og:description"] || meta.description || "")
|
|
.replace(/\s+/g, " ").trim();
|
|
|
|
/* DIE BILDER, in der Reihenfolge ihrer Verlaesslichkeit: was die Seite
|
|
als ihr Bild ausgibt (og:image, JSON-LD), dann die grossen im Inhalt,
|
|
dann das Vorschaubild eines Showcase-Videos. Logos und Symbole fallen
|
|
heraus -- die waeren auf der Karte genau das Falsche. */
|
|
const bilder = [];
|
|
const nimm = (src) => {
|
|
/* EIN LEERES `src` ERGIBT DIE SEITE SELBST -- aufgeloest gegen ihre
|
|
eigene Adresse. Gemessen an Quasar: Die Produktseite stand als
|
|
Bildkandidat Nummer 2 in der Liste. */
|
|
if (!src || !String(src).trim()) return;
|
|
const a = absolut(src, basis);
|
|
if (!a || a === basis || bilder.includes(a)) return;
|
|
/* GEPRUEFT WIRD DIE ENTSCHLUESSELTE ADRESSE: Bei Next.js steht der
|
|
Dateiname kodiert im Parameter („…?url=%2Flogo.png"), und dort sah
|
|
der Filter das Logo nicht. */
|
|
let lesbar = a;
|
|
try { lesbar = decodeURIComponent(a); } catch { /* bleibt kodiert */ }
|
|
if (/\.svg(\?|&|$)|\b(logo|icon|favicon|avatar|sprite|badge|flag|emoji|pixel|tracking)\b/i.test(lesbar)) return;
|
|
bilder.push(a);
|
|
};
|
|
/* Aus `srcset` die breiteste Fassung -- die erste ist meist die kleinste. */
|
|
const breitestes = (srcset) => String(srcset || "").split(/,\s+/)
|
|
.map((x) => x.trim().split(/\s+/))
|
|
.map(([u, w]) => ({ u, w: Number(String(w || "").replace(/\D/g, "")) || 0 }))
|
|
.filter((x) => x.u).sort((a, b) => b.w - a.w)[0]?.u || "";
|
|
nimm(meta["og:image"]); nimm(meta["og:image:secure_url"]); nimm(meta["twitter:image"]);
|
|
for (const b of [].concat(produkt?.image || [])) nimm(typeof b === "string" ? b : b?.url);
|
|
for (const m of h.matchAll(/<img\b[^>]*>/gi)) {
|
|
const t = m[0];
|
|
const alt = (t.match(/\balt\s*=\s*["']([^"']*)["']/i) || [])[1] || "";
|
|
if (/\blogo\b/i.test(alt)) continue;
|
|
const satz = (t.match(/\bsrcset\s*=\s*["']([^"']+)["']/i) || [])[1];
|
|
const src = breitestes(ent(satz)) || (t.match(/\b(?:data-src|src)\s*=\s*["']([^"']*)["']/i) || [])[1];
|
|
const breite = Number((t.match(/\bwidth\s*=\s*["']?(\d+)/i) || [])[1] || 0);
|
|
if (src && !/^data:/i.test(src) && (breite === 0 || breite >= 300)) nimm(src);
|
|
}
|
|
for (const m of h.matchAll(/(?:youtube\.com\/(?:embed\/|watch\?v=)|youtu\.be\/)([\w-]{11})/g)) {
|
|
nimm(`https://i.ytimg.com/vi/${m[1]}/maxresdefault.jpg`);
|
|
}
|
|
|
|
/* DER SICHTBARE TEXT, fuer die KI -- und fuer einen Preis, den die
|
|
Daten nicht nennen (Quasar schreibt ihn nur ins Bild der Seite). */
|
|
const text = ent(h.replace(/<script[\s\S]*?<\/script>/gi, " ").replace(/<style[\s\S]*?<\/style>/gi, " ")
|
|
.replace(/<noscript[\s\S]*?<\/noscript>/gi, " ").replace(/<[^>]+>/g, " "))
|
|
.replace(/\s+/g, " ").trim().slice(0, 6000);
|
|
if (preis === null || !Number.isFinite(preis)) {
|
|
const p = text.match(/(\d{1,4}(?:[.,]\d{2}))\s?(EUR|€|USD|\$|GBP|£)/i)
|
|
|| text.match(/(€|\$|£)\s?(\d{1,4}(?:[.,]\d{2}))/);
|
|
if (p) {
|
|
const zahl = /\d/.test(p[1]) ? p[1] : p[2];
|
|
const zeichen = /\d/.test(p[1]) ? p[2] : p[1];
|
|
preis = Number(zahl.replace(",", "."));
|
|
waehrung = { "€": "EUR", "$": "USD", "£": "GBP" }[zeichen] || zeichen.toUpperCase();
|
|
} else preis = null;
|
|
}
|
|
let shop = "";
|
|
try { shop = new URL(basis).hostname.replace(/^www\./, ""); } catch { /* egal */ }
|
|
return {
|
|
titel, beschreibung, preis, waehrung: waehrung ? String(waehrung).toUpperCase() : null,
|
|
bilder: bilder.slice(0, 12), text, shop,
|
|
};
|
|
}
|
|
|
|
/** Eine Produktseite holen und lesen. Austauschbar fuer Pruefungen --
|
|
* der echte Abruf geht nur ins Netz, und eine Pruefung darf das nicht. */
|
|
let seiteHolen = (url) => holen(url);
|
|
export function seiteHolenSetzen(f) { seiteHolen = f; }
|
|
export async function seiteLesen(url) {
|
|
const a = await seiteHolen(url);
|
|
const html = a.inhalt.toString("utf8");
|
|
if (seiteBlockt(a.status, html)) throw new AbrufFehler("seite_blockt");
|
|
if (a.status >= 400) throw new AbrufFehler("seite_fehlt", String(a.status));
|
|
return seiteAuswerten(html, a.url || url);
|
|
}
|
|
|
|
/* =====================================================================
|
|
3. DIE KI
|
|
===================================================================== */
|
|
export const KI_MODELL = "claude-haiku-5-5";
|
|
/* Laut Bauauftrag: „bei schwierigen Screenshots automatisch einmal mit
|
|
staerkerem Modell wiederholen (z. B. Sonnet 5.5), wenn Felder
|
|
unsicher bleiben". */
|
|
export const KI_MODELL_STARK = "claude-sonnet-5-5";
|
|
|
|
let klient = null;
|
|
/** Nur fuer Pruefungen: einen Ersatz einsetzen, der nichts kostet. */
|
|
export function kiKlientSetzen(k) { klient = k; }
|
|
function kiKlient() {
|
|
if (klient) return klient;
|
|
if (!process.env.ANTHROPIC_API_KEY) return null;
|
|
/* Der Schluessel kommt aus der Umgebung (server/.env), nie aus dem
|
|
Quelltext und nie in eine Ausgabe. */
|
|
klient = new Anthropic({ maxRetries: 2, timeout: 60_000 });
|
|
return klient;
|
|
}
|
|
export function kiBereit() { return !!(klient || process.env.ANTHROPIC_API_KEY); }
|
|
|
|
const KATEGORIEN = ["mlo", "script", "map", "fahrzeug"];
|
|
const FRAMEWORKS = ["qbox", "qbcore", "esx", "standalone", "vrp", "unbekannt"];
|
|
const zahlOderNull = { anyOf: [{ type: "number" }, { type: "null" }] };
|
|
const wahrOderNull = { anyOf: [{ type: "boolean" }, { type: "null" }] };
|
|
const textOderNull = { anyOf: [{ type: "string" }, { type: "null" }] };
|
|
|
|
/* DIE ANTWORTFORM. Jedes Objekt mit `additionalProperties: false` und
|
|
allen Feldern als Pflicht -- das verlangt die Schnittstelle. Laengen
|
|
kann sie nicht erzwingen; die werden unten nachgeschnitten. */
|
|
export const KI_SCHEMA = {
|
|
type: "object",
|
|
additionalProperties: false,
|
|
required: ["titel", "texte", "preis", "waehrung", "preis_inkl_steuer", "kategorie", "format",
|
|
"framework", "abo", "escrow", "bild", "unsicher"],
|
|
properties: {
|
|
titel: { type: "string", description: "Produktname, hoechstens 30 Zeichen, Deutsch wenn sinnvoll" },
|
|
texte: {
|
|
type: "object",
|
|
additionalProperties: false,
|
|
required: ["serioes", "hype", "kurz"],
|
|
properties: {
|
|
serioes: { type: "string", description: "sachlich, hoechstens 90 Zeichen" },
|
|
hype: { type: "string", description: "mitreissend, aber nicht bettelnd, hoechstens 90 Zeichen" },
|
|
kurz: { type: "string", description: "knapp, hoechstens 50 Zeichen" },
|
|
},
|
|
},
|
|
preis: zahlOderNull,
|
|
waehrung: textOderNull,
|
|
preis_inkl_steuer: wahrOderNull,
|
|
kategorie: { type: "string", enum: KATEGORIEN },
|
|
format: { type: "string", enum: ["gross", "kompakt"] },
|
|
framework: { type: "array", items: { type: "string", enum: FRAMEWORKS } },
|
|
abo: wahrOderNull,
|
|
escrow: wahrOderNull,
|
|
bild: {
|
|
type: "object",
|
|
additionalProperties: false,
|
|
required: ["quelle", "nummer", "box"],
|
|
properties: {
|
|
quelle: { type: "string", enum: ["screenshot", "link", "keins"] },
|
|
nummer: { type: "integer", description: "Nummer des Screenshots (S1 = 1) bzw. Kandidaten (K1 = 1)" },
|
|
box: {
|
|
anyOf: [{ type: "null" }, {
|
|
type: "object",
|
|
additionalProperties: false,
|
|
required: ["x", "y", "b", "h"],
|
|
properties: {
|
|
x: { type: "number" }, y: { type: "number" }, b: { type: "number" }, h: { type: "number" },
|
|
},
|
|
}],
|
|
},
|
|
},
|
|
},
|
|
unsicher: { type: "array", items: { type: "string", enum: ["titel", "preis", "waehrung", "kategorie", "framework", "bild", "abo"] } },
|
|
},
|
|
};
|
|
|
|
const ANWEISUNG = `Du bereitest Werbekarten fuer den FiveM-Roleplay-Server BLUE MOON vor.
|
|
DogFather zeigt sie waehrend er zockt: Dinge (Scripts, MLOs, Maps, Fahrzeuge), die er fuer den Server kaufen will.
|
|
BLUE MOON laeuft auf dem Framework Qbox (qbx_core, kompatibel mit vielen QBCore-Ressourcen).
|
|
|
|
Lies Seite und Screenshots und fuelle die Antwortform:
|
|
- titel: der Produktname, hoechstens 30 Zeichen. Keinen Shopnamen anhaengen.
|
|
- texte: drei deutsche Varianten, warum das nach BLUE MOON soll. „serioes" sachlich, „hype" mitreissend,
|
|
„kurz" in wenigen Worten. NIE bettelnd, NIE „spendet", „unterstuetzt", „schickt Geschenke", keine Links,
|
|
keine Emojis. Eher: „Das holen wir nach BLUE MOON." Erfinde keine Funktionen, die nirgends stehen.
|
|
- preis/waehrung: der Kaufpreis, wie er da steht (bei Rabatt der reduzierte). Unklar -> null und „preis" in unsicher.
|
|
- preis_inkl_steuer: false, wenn der Shop „exkl. MwSt"/„excl. VAT" sagt oder Steuer erst an der Kasse kommt
|
|
(bei Tebex-Shops ueblich); true, wenn ausdruecklich inklusive; sonst null.
|
|
- kategorie: mlo (Gebaeude/Innenraum), map, script (Spiellogik/Oberflaeche), fahrzeug.
|
|
- format: „gross" fuer Gebaeude, Maps und Fahrzeuge (breites Bild), „kompakt" fuer Scripts.
|
|
- framework: alle genannten (qbox, qbcore, esx, standalone, vrp); nichts genannt -> ["unbekannt"].
|
|
- abo: true bei Abo/Monatspreis/Subscription, false bei Einmalkauf, sonst null.
|
|
- escrow: true bei Escrow/Tebex-Asset-Escrow, false bei Open Source, sonst null.
|
|
- bild: das beste Produktbild. Es zeigt das Produkt selbst (Gebaeude, Map, Script-Oberflaeche im Spiel),
|
|
nicht Logos, Preisgrafiken, Textbanner oder Shopmenues.
|
|
Liegt es in einem Screenshot: quelle „screenshot", nummer = Screenshot-Nummer, box = Bereich des
|
|
Produktbilds in Prozent der Screenshot-Breite/-Hoehe (x,y = linke obere Ecke, b,h = Breite, Hoehe).
|
|
Ist ein Kandidat aus dem Link besser: quelle „link", nummer = Kandidaten-Nummer, box null.
|
|
Kein brauchbares: quelle „keins", nummer 0, box null.
|
|
- unsicher: jedes Feld, bei dem du raten musstest.`;
|
|
|
|
function abschneiden(s, max) {
|
|
const t = String(s || "").replace(/\s+/g, " ").trim();
|
|
if (t.length <= max) return t;
|
|
const kurz = t.slice(0, max - 1);
|
|
const wort = kurz.lastIndexOf(" ");
|
|
return `${(wort > max * 0.6 ? kurz.slice(0, wort) : kurz).trim()}…`;
|
|
}
|
|
|
|
/** Den Inhalt der Anfrage bauen: Text, Screenshots, Kandidatenbilder. */
|
|
function inhaltBauen({ seite, bilder, hinweis, mitKandidaten }) {
|
|
const teile = [];
|
|
const zeilen = [];
|
|
if (seite) {
|
|
zeilen.push(`LINK (${seite.shop}):`, `Titel: ${seite.titel}`, `Beschreibung: ${seite.beschreibung}`);
|
|
if (seite.preis !== null) zeilen.push(`Preis laut Seitendaten: ${seite.preis} ${seite.waehrung || ""}`);
|
|
zeilen.push(`Sichtbarer Text (gekuerzt): ${seite.text.slice(0, 5000)}`);
|
|
}
|
|
(bilder || []).forEach((b, i) => {
|
|
teile.push({ type: "text", text: `Screenshot S${i + 1}:` });
|
|
teile.push({ type: "image", source: { type: "base64", media_type: b.typ, data: b.daten } });
|
|
});
|
|
if (seite && mitKandidaten) {
|
|
seite.bilder.slice(0, 4).forEach((u, i) => {
|
|
teile.push({ type: "text", text: `Kandidat K${i + 1}:` });
|
|
teile.push({ type: "image", source: { type: "url", url: u } });
|
|
});
|
|
}
|
|
if (hinweis) zeilen.push(`Wunsch von DogFather fuer die Texte: ${hinweis}`);
|
|
teile.unshift({ type: "text", text: zeilen.join("\n") || "Nur Screenshots, kein Link." });
|
|
return teile;
|
|
}
|
|
|
|
/** Ein Aufruf. `stark` = das staerkere Modell (mit der Rueckfall-Absicherung,
|
|
* die die Schnittstelle fuer Sonnet 5.5 vorsieht). */
|
|
async function fragen(k, inhalt, stark) {
|
|
const anfrage = {
|
|
model: stark ? KI_MODELL_STARK : KI_MODELL,
|
|
max_tokens: 4000,
|
|
system: ANWEISUNG,
|
|
messages: [{ role: "user", content: inhalt }],
|
|
/* Auslesen und kurz formulieren -- dafuer reicht wenig Nachdenken,
|
|
und es kostet entsprechend wenig. */
|
|
output_config: { format: { type: "json_schema", schema: KI_SCHEMA }, effort: "low" },
|
|
};
|
|
const antwort = stark
|
|
? await k.beta.messages.create({ ...anfrage, betas: ["server-side-fallback-2026-07-01"], fallbacks: "default" })
|
|
: await k.messages.create(anfrage);
|
|
if (antwort.stop_reason === "refusal") throw new AbrufFehler("ki_abgelehnt");
|
|
if (antwort.stop_reason === "max_tokens") throw new AbrufFehler("ki_abgeschnitten");
|
|
const text = (antwort.content || []).find((b) => b.type === "text")?.text || "";
|
|
let j;
|
|
try { j = JSON.parse(text); } catch { throw new AbrufFehler("ki_unlesbar"); }
|
|
return { j, modell: anfrage.model, nutzung: antwort.usage || null };
|
|
}
|
|
|
|
/** Die Antwort der KI in die Form bringen, die die Regie braucht -- und
|
|
* alles nachschneiden, was die Schnittstelle nicht erzwingen kann. */
|
|
function vorschlagAus(j, seite) {
|
|
const kat = KATEGORIEN.includes(j.kategorie) ? j.kategorie : "mlo";
|
|
const box = j.bild?.box && [j.bild.box.x, j.bild.box.y, j.bild.box.b, j.bild.box.h].every(Number.isFinite)
|
|
? {
|
|
x: Math.max(0, Math.min(100, j.bild.box.x)), y: Math.max(0, Math.min(100, j.bild.box.y)),
|
|
b: Math.max(1, Math.min(100, j.bild.box.b)), h: Math.max(1, Math.min(100, j.bild.box.h)),
|
|
} : null;
|
|
return {
|
|
titel: abschneiden(j.titel || seite?.titel || "", 30),
|
|
texte: {
|
|
serioes: abschneiden(j.texte?.serioes, 90),
|
|
hype: abschneiden(j.texte?.hype, 90),
|
|
kurz: abschneiden(j.texte?.kurz, 90),
|
|
},
|
|
preis: Number.isFinite(j.preis) && j.preis > 0 ? Math.round(j.preis * 100) / 100 : null,
|
|
waehrung: j.waehrung ? String(j.waehrung).toUpperCase().slice(0, 3) : null,
|
|
preis_inkl_steuer: typeof j.preis_inkl_steuer === "boolean" ? j.preis_inkl_steuer : null,
|
|
kategorie: kat,
|
|
format: j.format === "kompakt" ? "kompakt" : "gross",
|
|
framework: (Array.isArray(j.framework) ? j.framework : []).filter((f) => FRAMEWORKS.includes(f)),
|
|
abo: typeof j.abo === "boolean" ? j.abo : null,
|
|
escrow: typeof j.escrow === "boolean" ? j.escrow : null,
|
|
bild: {
|
|
quelle: ["screenshot", "link", "keins"].includes(j.bild?.quelle) ? j.bild.quelle : "keins",
|
|
nummer: Number.isInteger(j.bild?.nummer) ? j.bild.nummer : 0,
|
|
box,
|
|
},
|
|
unsicher: Array.isArray(j.unsicher) ? j.unsicher.filter((x) => typeof x === "string") : [],
|
|
};
|
|
}
|
|
|
|
/** Ohne KI: was die Seite selbst sagt, in derselben Form. */
|
|
export function vorschlagOhneKi(seite) {
|
|
return {
|
|
titel: abschneiden(seite?.titel?.split(/\s[-|–·]\s/)[0] || "", 30),
|
|
texte: { serioes: abschneiden(seite?.beschreibung, 90), hype: "", kurz: "" },
|
|
preis: seite?.preis ?? null,
|
|
waehrung: seite?.waehrung ?? null,
|
|
preis_inkl_steuer: null,
|
|
kategorie: "mlo",
|
|
format: "gross",
|
|
framework: [],
|
|
abo: null,
|
|
escrow: null,
|
|
bild: { quelle: seite?.bilder?.length ? "link" : "keins", nummer: seite?.bilder?.length ? 1 : 0, box: null },
|
|
unsicher: ["kategorie", "framework", "preis"],
|
|
};
|
|
}
|
|
|
|
/** Die KI fragen. Bleiben Pflichtfelder unsicher und gab es Screenshots,
|
|
* einmal mit dem staerkeren Modell -- Bauauftrag 4c. */
|
|
export async function kiAuswerten({ seite, bilder, hinweis }) {
|
|
const k = kiKlient();
|
|
if (!k) throw new AbrufFehler("ki_fehlt");
|
|
let mitKandidaten = !!seite?.bilder?.length;
|
|
let r;
|
|
try {
|
|
r = await fragen(k, inhaltBauen({ seite, bilder, hinweis, mitKandidaten }), false);
|
|
} catch (f) {
|
|
/* EIN KANDIDATENBILD, DAS DIE SCHNITTSTELLE NICHT HOLEN KANN (Shop
|
|
sperrt fremde Abrufer), laesst die ganze Anfrage scheitern. Dann
|
|
einmal ohne Kandidaten -- die Bilder kommen trotzdem in die
|
|
Galerie, nur ohne Rangfolge der KI. */
|
|
if (mitKandidaten && f instanceof Anthropic.BadRequestError) {
|
|
mitKandidaten = false;
|
|
r = await fragen(k, inhaltBauen({ seite, bilder, hinweis, mitKandidaten }), false);
|
|
} else throw f;
|
|
}
|
|
let v = vorschlagAus(r.j, seite);
|
|
const verbrauch = [{ modell: r.modell, nutzung: r.nutzung }];
|
|
const kritisch = ["titel", "preis", "bild"].some((x) => v.unsicher.includes(x));
|
|
if (kritisch && bilder?.length) {
|
|
try {
|
|
const s = await fragen(k, inhaltBauen({ seite, bilder, hinweis, mitKandidaten }), true);
|
|
const sv = vorschlagAus(s.j, seite);
|
|
verbrauch.push({ modell: s.modell, nutzung: s.nutzung });
|
|
/* Nur uebernehmen, wenn es WENIGER Unsicherheit hat -- ein zweiter
|
|
Versuch, der nicht besser ist, ersetzt den ersten nicht. */
|
|
if (sv.unsicher.length < v.unsicher.length) v = sv;
|
|
} catch { /* der erste Vorschlag bleibt */ }
|
|
}
|
|
if (!mitKandidaten && v.bild.quelle === "link") v.bild = { quelle: "keins", nummer: 0, box: null };
|
|
return { vorschlag: v, verbrauch, mitKandidaten };
|
|
}
|
|
|
|
/* =====================================================================
|
|
4. DIE PRUEFUNGEN (Bauauftrag 4d) -- sie warnen, sie entscheiden nicht
|
|
===================================================================== */
|
|
const kurse = new Map(); // "USD:2026-10-27" -> Kurs nach EUR
|
|
let kursHolen = async (von) => {
|
|
const a = await holen(`https://api.frankfurter.app/latest?from=${encodeURIComponent(von)}&to=EUR`,
|
|
{ max: 64 * 1024, frist: 6000, annehmen: "application/json" });
|
|
const j = JSON.parse(a.inhalt.toString("utf8"));
|
|
const k = Number(j?.rates?.EUR);
|
|
if (!(k > 0)) throw new AbrufFehler("kurs_fehlt");
|
|
return k;
|
|
};
|
|
/** Nur fuer Pruefungen: einen festen Kurs einsetzen statt die EZB zu fragen. */
|
|
export function kursHolenSetzen(f) { kursHolen = f; kurse.clear(); }
|
|
async function kurs(von) {
|
|
const schluessel = `${von}:${new Date().toISOString().slice(0, 10)}`;
|
|
if (!kurse.has(schluessel)) kurse.set(schluessel, await kursHolen(von));
|
|
return kurse.get(schluessel);
|
|
}
|
|
|
|
/** Den Zielbetrag vorschlagen und die Warnungen sammeln.
|
|
* `lage` = { budget_cent, mwst, offene_cent, vorhandene: [{titel, quelle, stand}] } */
|
|
export async function pruefungen(v, { url, lage }) {
|
|
const p = [];
|
|
let cent = v.preis !== null ? Math.round(v.preis * 100) : null;
|
|
let euroText = null;
|
|
|
|
if (cent !== null && v.waehrung && v.waehrung !== "EUR") {
|
|
try {
|
|
const k = await kurs(v.waehrung);
|
|
cent = Math.round(cent * k);
|
|
euroText = `${v.preis.toFixed(2).replace(".", ",")} ${v.waehrung} ≈ ${(cent / 100).toFixed(2).replace(".", ",")} € (Tageskurs EZB)`;
|
|
p.push({ art: "warn", text: `Fremdwährung: ${euroText}.` });
|
|
} catch {
|
|
/* DRITTER AUSGANG: ohne Kurs keine Umrechnung -- gesagt, nicht geraten. */
|
|
p.push({ art: "offen", text: `Preis in ${v.waehrung} — der Tageskurs war nicht abrufbar. Bitte selbst umrechnen.` });
|
|
cent = null;
|
|
}
|
|
}
|
|
if (cent !== null && v.preis_inkl_steuer === false) {
|
|
const mwst = Number(lage.mwst) || 19;
|
|
const brutto = Math.round(cent * (1 + mwst / 100));
|
|
p.push({ art: "warn", text: `Preis ohne MwSt. — mit ${mwst} % sind es etwa ${(brutto / 100).toFixed(2).replace(".", ",")} €. Als Ziel vorgeschlagen.` });
|
|
cent = brutto;
|
|
}
|
|
if (cent === null) p.push({ art: "offen", text: "Kein Preis gefunden — bitte eintragen." });
|
|
|
|
const fw = v.framework || [];
|
|
if (fw.includes("qbox")) p.push({ art: "ok", text: "Qbox-kompatibel laut Shop." });
|
|
else if (fw.includes("qbcore")) p.push({ art: "warn", text: "Nur QBCore genannt — läuft auf Qbox meist über die Brücke. Prüfen." });
|
|
else if (fw.includes("standalone")) p.push({ art: "ok", text: "Standalone — braucht kein Framework." });
|
|
else if (fw.some((f) => ["esx", "vrp"].includes(f))) p.push({ art: "rot", text: `Nur ${fw.filter((f) => f !== "unbekannt").join("/").toUpperCase()} — nicht für Qbox.` });
|
|
else p.push({ art: "offen", text: "Framework nicht genannt — Qbox-Tauglichkeit unklar." });
|
|
|
|
if (v.abo === true) p.push({ art: "rot", text: "Abo erkannt — du kaufst nur Einmalkäufe." });
|
|
if (v.escrow === true) p.push({ art: "ok", text: "Escrow (verschlüsselt) — Konfiguration offen, Kern nicht." });
|
|
|
|
if (cent !== null) {
|
|
const budget = Number(lage.budget_cent) || 10_000;
|
|
const summe = (Number(lage.offene_cent) || 0) + cent;
|
|
if (summe > budget) {
|
|
p.push({ art: "warn", text: `Budget: mit diesem Ziel sind ${(summe / 100).toFixed(2).replace(".", ",")} € offen, Grenze ${(budget / 100).toFixed(0)} €.` });
|
|
}
|
|
}
|
|
const norm = (s) => String(s || "").toLowerCase().replace(/^https?:\/\/(www\.)?/, "").replace(/[?#].*$/, "").replace(/\/+$/, "");
|
|
const doppelt = (lage.vorhandene || []).find((z) => (url && z.quelle && norm(z.quelle) === norm(url))
|
|
|| (v.titel && z.titel && z.titel.toLowerCase() === v.titel.toLowerCase()));
|
|
if (doppelt) {
|
|
p.push({ art: "warn", text: `Doppelt: „${doppelt.titel}“ gibt es schon (${doppelt.stand === "gekauft" ? "schon gekauft" : doppelt.stand}).` });
|
|
}
|
|
if (v.unsicher?.length) {
|
|
p.push({ art: "offen", text: `Unsicher war die KI bei: ${v.unsicher.join(", ")}.` });
|
|
}
|
|
return { ziel_cent: cent, pruefungen: p };
|
|
}
|