okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-split-agent8' into f-split-vision788e0b731

main
7.0 KiB125 linesraw
1/**
2 * Files and pictures dropped or pasted into a chat.
3 *
4 * `POST /api/chat/upload?sessionId=&name=` takes the bytes in any of three forms: multipart/form-data (one or more files), a JSON body
5 * { name, dataUrl } (a pasted or read picture), or the raw bytes with the file's type. A picture is kept as an upload the next message
6 * can name (imageIds) and is shown again by its id; any other file is saved inside the chat's folder under .strata/attachments and named
7 * in the next message (@path), so the assistant reads it. Nothing is ever written outside those two places.
8 */
9
10import { randomUUID } from 'node:crypto';
11import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
12import { basename, extname, join } from 'node:path';
13
14export const IMAGE_TYPES = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/webp': 'webp' };
15export const MAX_UPLOAD_BYTES = 12 * 1024 * 1024;
16export const MAX_IMAGE_BYTES = 6 * 1024 * 1024;
17export const MAX_IMAGES = 4;
18
19const safeName = name => String(name ?? 'file').replace(/[\\/:*?"<>|\x00-\x1f]/g, '_').replace(/^\.+/, '').slice(0, 120) || 'file';
20
21/** The files of a multipart/form-data body: [{ name, type, bytes }]. */
22export function parseMultipart(body, contentType) {
23  const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(String(contentType ?? ''));
24  if (!m) throw new Error('This upload is not readable. Try again.');
25  const boundary = Buffer.from('--' + (m[1] ?? m[2]).trim());
26  const files = [];
27  let at = body.indexOf(boundary);
28  while (at >= 0) {
29    const next = body.indexOf(boundary, at + boundary.length);
30    if (next < 0) break;
31    let part = body.subarray(at + boundary.length, next);
32    if (part.subarray(0, 2).toString() === '\r\n') part = part.subarray(2);
33    const head = part.indexOf('\r\n\r\n');
34    if (head > 0) {
35      const headers = part.subarray(0, head).toString('utf8');
36      let data = part.subarray(head + 4);
37      if (data.subarray(-2).toString() === '\r\n') data = data.subarray(0, -2);
38      const file = /filename="([^"]*)"/i.exec(headers);
39      if (file) files.push({ name: file[1] || 'file', type: (/content-type:\s*([^\r\n;]+)/i.exec(headers)?.[1] ?? 'application/octet-stream').trim().toLowerCase(), bytes: Buffer.from(data) });
40    }
41    at = next;
42  }
43  if (!files.length) throw new Error('No file was in this upload.');
44  return files;
45}
46
47const typeFromBytes = b => (b.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) ? 'image/png' : b.subarray(0, 3).equals(Buffer.from([255, 216, 255])) ? 'image/jpeg' : b.subarray(0, 4).toString() === 'RIFF' && b.subarray(8, 12).toString() === 'WEBP' ? 'image/webp' : null);
48
49export function createUploads({ dir, folderOf, attachments }) {
50  mkdirSync(dir, { recursive: true });
51  const index = new Map();   // id -> { id, chatId, name, type, size, file }
52  const metaFile = id => join(dir, id + '.json');
53  const load = id => {
54    if (index.has(id)) return index.get(id);
55    try { const m = JSON.parse(readFileSync(metaFile(id), 'utf8')); index.set(id, m); return m; } catch { return null; }
56  };
57
58  /** Store one file; returns what the page needs to show it. */
59  function saveOne(chatId, f) {
60    if (f.bytes.length > MAX_UPLOAD_BYTES) throw Object.assign(new Error(`"${safeName(f.name)}" is bigger than ${MAX_UPLOAD_BYTES / 1024 / 1024} MB.`), { code: 'too-big' });
61    // A picture is recognised by its first bytes, not by the name or the type the sender claimed.
62    const real = typeFromBytes(f.bytes);
63    if (real) {
64      if (f.bytes.length > MAX_IMAGE_BYTES) throw Object.assign(new Error(`The picture "${safeName(f.name)}" is bigger than ${MAX_IMAGE_BYTES / 1024 / 1024} MB. Choose a smaller one.`), { code: 'too-big' });
65      const id = randomUUID();
66      const file = join(dir, id + '.' + IMAGE_TYPES[real]);
67      writeFileSync(file, f.bytes);
68      const meta = { id, chatId, name: safeName(f.name), type: real, size: f.bytes.length, file, kind: 'image' };
69      writeFileSync(metaFile(id), JSON.stringify(meta)); index.set(id, meta);
70      return { id, kind: 'image', name: meta.name, type: real, size: meta.size, url: `/api/chat/upload/${id}` };
71    }
72    if (/^image\//i.test(f.type)) throw Object.assign(new Error(`"${safeName(f.name)}" is a picture type the model cannot read. Use PNG, JPEG or WebP.`), { code: 'bad-image' });
73    const root = folderOf(chatId);
74    const target = join(root, '.strata', 'attachments');
75    mkdirSync(target, { recursive: true });
76    let name = safeName(f.name), n = 1;
77    while (existsSync(join(target, name))) name = `${basename(f.name, extname(f.name))}-${++n}${extname(f.name)}`.replace(/[\\/:*?"<>|]/g, '_');
78    const path = join(target, name);
79    writeFileSync(path, f.bytes);
80    attachments.add(chatId, path);
81    return { id: null, kind: 'file', name, type: f.type, size: f.bytes.length, path, attached: true };
82  }
83
84  return {
85    /** Accept a request body in any of the three forms. */
86    accept(chatId, { body, contentType, name }) {
87      const ct = String(contentType ?? '');
88      let files;
89      if (/^multipart\/form-data/i.test(ct)) files = parseMultipart(body, ct);
90      else if (/^application\/json/i.test(ct)) {
91        const j = JSON.parse(body.toString('utf8') || '{}');
92        const list = Array.isArray(j.files) ? j.files : [j];
93        files = list.map(x => {
94          const m = /^data:([^;,]+);base64,([A-Za-z0-9+/=]+)$/.exec(String(x.dataUrl ?? x.url ?? ''));
95          if (!m) throw new Error('A picture must be sent as a data address (data:image/png;base64,...).');
96          return { name: x.name ?? 'Picture', type: m[1], bytes: Buffer.from(m[2], 'base64') };
97        });
98      } else files = [{ name: name ?? 'file', type: ct || 'application/octet-stream', bytes: body }];
99      if (files.length > 10) throw new Error('Drop up to ten files at a time.');
100      return files.map(f => saveOne(chatId, f));
101    },
102    /** The picture of an upload as { bytes, type, name }, for the page and for the model. */
103    image(id) {
104      const m = load(String(id));
105      if (!m || m.kind !== 'image') return null;
106      try { return { bytes: readFileSync(m.file), type: m.type, name: m.name, chatId: m.chatId }; } catch { return null; }
107    },
108    /** The pictures a message names (imageIds), as data addresses the engine and the agent take. */
109    dataUrls(chatId, ids) {
110      const list = Array.isArray(ids) ? ids : [];
111      if (list.length > MAX_IMAGES) throw new Error(`Attach up to ${MAX_IMAGES} pictures per message.`);
112      return list.map(id => {
113        const img = this.image(id);
114        if (!img || (img.chatId && chatId && img.chatId !== chatId)) throw new Error('A picture is no longer available. Attach it again.');
115        return { url: `data:${img.type};base64,${img.bytes.toString('base64')}`, name: img.name };
116      });
117    },
118    /** Remove uploads older than a day (the folder never grows without end). */
119    sweep(maxAgeMs = 24 * 3600_000) {
120      let removed = 0;
121      for (const f of readdirSync(dir)) { const p = join(dir, f); try { if (Date.now() - statSync(p).mtimeMs > maxAgeMs) { unlinkSync(p); removed += 1; } } catch { /* gone already */ } }
122      return removed;
123    },
124  };
125}