okami.mom/strata

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

Niko1221Merge f-0213-fixux (82d3a0345): user screenshots - a data folder on an external drive under /run/media is no longer refused as a system folder (real system folders still are; the doubled sentence is gone); one fit label everywhere (owner 11-08): 'fits' when the model files without the n-gram/PLE/Engram table fit graphics memory plus RAM, else 'may run slower' (the Unsloth sets were measured against RAM only; DeepSeek Needs shows the whole size; no-card PCs and small Macs say 'may run slower'; NVFP4-QAD sized by its 76.8 GB pack)b7bcbcde9

main
11.5 KiB188 linesraw
1/**
2 * The folder a chat works in, and what can be done with a file in it.
3 *
4 *   - Each chat can have its own project folder ("Select a folder" above the input). It becomes the agent's working folder and
5 *     sandbox for that chat and is remembered per chat.
6 *   - A file in that folder is opened by its PATH (file:///...), never through a local web address: in the browser, in its own app,
7 *     shown in the folder (Explorer /select), or copied as a path. Only files inside the chat's folder (or one the agent made
8 *     there) can be named, so a request cannot reach anywhere else.
9 */
10
11import { spawn } from 'node:child_process';
12import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync, realpathSync } from 'node:fs';
13import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
14import { pathToFileURL } from 'node:url';
15import { externalEnvironment } from './external-env.mjs';
16
17/** A folder no chat may use as its project: the top of a drive, or the system's own folders. */
18export function refusedFolder(dir) {
19  const p = resolve(dir);
20  if (dirname(p) === p) return 'Choose a folder inside a drive, not the whole drive.';
21  if (process.platform === 'win32') {
22    const win = (process.env.SystemRoot ?? 'C:\\Windows').toLowerCase();
23    const q = p.toLowerCase();
24    if (q === win || q.startsWith(win + sep) || /^[a-z]:\\(program files( \(x86\))?|programdata)(\\|$)/.test(q)) return 'That is a system folder. Choose one of your own folders.';
25  } else if (/^\/(bin|boot|dev|etc|lib|lib64|proc|root|run|sbin|sys|usr|var)(\/|$)/.test(p) && !/^\/run\/media\/[^/]+\/./.test(p)) return 'That is a system folder. Choose one of your own folders.';
26  return null;
27}
28
29export const isInside = (root, target) => {
30  const rel = relative(resolve(root), resolve(target));
31  return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel));
32};
33
34/** The chat -> folder table, kept in one small file. */
35export function createChatFolders({ file }) {
36  let table = {};
37  try { const parsed = JSON.parse(readFileSync(file, 'utf8')); if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) table = parsed; } catch { /* first run */ }
38  const save = () => {
39    try { mkdirSync(dirname(file), { recursive: true }); const tmp = file + '.tmp'; writeFileSync(tmp, JSON.stringify(table, null, 2)); renameSync(tmp, file); } catch { /* kept in memory */ }
40  };
41  const alive = p => { try { return statSync(p).isDirectory(); } catch { return false; } };
42  return {
43    /** The folder of a chat, or null (none chosen, or it was deleted: then the chat falls back to the default). */
44    get(chatId) { const p = table[chatId]; return typeof p === 'string' && alive(p) ? p : null; },
45    info(chatId) { const p = table[chatId]; return p ? { path: p, name: basename(p) || p, exists: alive(p) } : null; },
46    set(chatId, dir) {
47      const target = resolve(String(dir ?? '').trim());
48      if (!String(dir ?? '').trim() || !isAbsolute(target)) throw Object.assign(new Error('Choose a folder first.'), { code: 'folder-missing' });
49      let st; try { st = statSync(target); } catch { throw Object.assign(new Error("That folder doesn't exist."), { code: 'folder-missing' }); }
50      if (!st.isDirectory()) throw Object.assign(new Error("That's a file, not a folder."), { code: 'folder-missing' });
51      const why = refusedFolder(target);
52      if (why) throw Object.assign(new Error(why), { code: 'folder-refused' });
53      table[chatId] = target; save();
54      return { path: target, name: basename(target) || target, exists: true };
55    },
56    clear(chatId) { delete table[chatId]; save(); },
57  };
58}
59
60/**
61 * The folder a chat's files live in, one rule for the agent's writes, Open, Show in folder, preview and attach:
62 *   1. the folder the person chose for this chat; else
63 *   2. the folder the agent actually worked in for it (its session's working folder, so it is the one it wrote to); else
64 *   3. the default workspace (Documents/Strata/Workspace, or STRATA_WORKSPACE), where a chat with no folder is run.
65 * A folder that no longer exists is skipped. Never null while the default exists, so a chat with no chosen folder can still open its files.
66 */
67export function chatRootOf({ chosen = null, used = null, fallback = null } = {}) {
68  const alive = p => { try { return !!p && statSync(p).isDirectory(); } catch { return false; } };
69  for (const p of [chosen, used, fallback]) if (alive(p)) return resolve(p);
70  return fallback ? resolve(fallback) : null;
71}
72
73/** The real path of a file the chat may touch, or throws a plain sentence. Symbolic links are followed before the check. */
74export function resolveChatFile(root, rawPath) {
75  if (!root) throw Object.assign(new Error('This chat has no folder yet. Choose one first.'), { code: 'no-folder' });
76  const given = String(rawPath ?? '').trim();
77  if (!given) throw Object.assign(new Error('Which file?'), { code: 'file-missing' });
78  const full = isAbsolute(given) ? resolve(given) : resolve(root, given);
79  let real; try { real = realpathSync(full); } catch { throw Object.assign(new Error('That file is no longer there.'), { code: 'file-missing' }); }
80  let realRoot; try { realRoot = realpathSync(root); } catch { realRoot = resolve(root); }
81  if (!isInside(realRoot, real)) throw Object.assign(new Error("That file is outside this chat's folder, so it was not opened."), { code: 'outside' });
82  return real;
83}
84
85/**
86 * Start a program and return at once: detached, no shared output, never waited for.
87 * `STRATA_OPENER=record` (tests) records the command instead of starting anything.
88 */
89export function launch(command, args, { recorder = null } = {}) {
90  if (process.env.STRATA_OPENER === 'record' || recorder) { (recorder ?? launch.recorded).push([command, ...args]); return; }
91  // xdg-open and the browser it starts are the system's programs: they get the environment the AppImage was started from, not Strata's libraries.
92  const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: false, env: externalEnvironment() });
93  child.on('error', () => {});
94  child.unref();
95}
96launch.recorded = [];
97
98/** What "open" means on each system, for the browser, the file's own app, or the folder. */
99export function openCommand(how, file, platform = process.platform) {
100  const url = pathToFileURL(file).href;
101  if (how === 'folder') {
102    if (platform === 'win32') return ['explorer.exe', [`/select,${file}`]];
103    if (platform === 'darwin') return ['open', ['-R', file]];
104    return ['xdg-open', [dirname(file)]];
105  }
106  if (how === 'browser') {
107    if (platform === 'win32') return ['rundll32.exe', ['url.dll,FileProtocolHandler', url]];   // the default browser, handed a file:// address
108    if (platform === 'darwin') return ['open', [url]];
109    return ['xdg-open', [url]];
110  }
111  if (platform === 'win32') return ['rundll32.exe', ['url.dll,FileProtocolHandler', file]];
112  if (platform === 'darwin') return ['open', [file]];
113  return ['xdg-open', [file]];
114}
115
116export function openFile(root, rawPath, how = 'app', { platform = process.platform, recorder = null } = {}) {
117  if (!['browser', 'app', 'folder'].includes(how)) throw Object.assign(new Error('That way of opening is not known.'), { code: 'bad-how' });
118  const file = resolveChatFile(root, rawPath);
119  const [cmd, args] = openCommand(how, file, platform);
120  launch(cmd, args, { recorder });
121  return { ok: true, started: true, path: file, url: pathToFileURL(file).href, how };
122}
123
124// ---- previews, raw bytes and "attach as context" -----------------------------------------------------------------------------------
125
126import { readFileSync as readBytes } from 'node:fs';
127import { fileType } from './agent/deliverables.mjs';
128
129const MIME = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml', bmp: 'image/bmp', ico: 'image/x-icon', pdf: 'application/pdf' };
130export const mimeOf = file => MIME[String(file).split('.').pop().toLowerCase()] ?? 'application/octet-stream';
131const MAX_PREVIEW_TEXT = 1_000_000;
132
133/** A small CSV/TSV reader for the table preview: quotes, doubled quotes, commas/tabs inside quotes. */
134export function parseCsv(text, delimiter = ',', maxRows = 500) {
135  const rows = []; let row = [], cell = '', quoted = false;
136  for (let i = 0; i < text.length && rows.length < maxRows; i++) {
137    const ch = text[i];
138    if (quoted) { if (ch === '"') { if (text[i + 1] === '"') { cell += '"'; i++; } else quoted = false; } else cell += ch; }
139    else if (ch === '"') quoted = true;
140    else if (ch === delimiter) { row.push(cell); cell = ''; }
141    else if (ch === '\n' || ch === '\r') { if (ch === '\r' && text[i + 1] === '\n') i++; row.push(cell); rows.push(row); row = []; cell = ''; }
142    else cell += ch;
143  }
144  if (rows.length < maxRows && (cell !== '' || row.length)) { row.push(cell); rows.push(row); }
145  return rows;
146}
147
148/**
149 * What the sidebar needs to show a file: { kind, name, size, text?, rows?, rawUrl? }.
150 * html: the text (the page renders it sandboxed); markdown: the text; csv: parsed rows; pdf and images: the address of the raw bytes
151 * (/api/files/raw), which only serves a file inside the chat's folder; code and text: the text. Too big to show: kind only and a plain note.
152 */
153export function previewFile(root, rawPath, sessionId) {
154  const file = resolveChatFile(root, rawPath);
155  const st = statSync(file); const kind = fileType(file);
156  const base = { kind, name: basename(file), path: file, size: st.size, mtime: Math.round(st.mtimeMs), url: pathToFileURL(file).href };
157  const raw = `/api/files/raw?sessionId=${encodeURIComponent(sessionId)}&path=${encodeURIComponent(file)}`;
158  if (kind === 'image' || kind === 'pdf') return { ...base, rawUrl: raw, mime: mimeOf(file) };
159  if (kind === 'other') return { ...base, note: 'This kind of file has no preview. Open it in its own app.' };
160  if (st.size > MAX_PREVIEW_TEXT) return { ...base, note: 'This file is too big to show here. Open it in its own app.' };
161  const buf = readBytes(file);
162  if (buf.subarray(0, 2048).includes(0)) return { ...base, kind: 'other', note: 'This file is not text, so it has no preview.' };
163  const text = buf.toString('utf8');
164  if (kind === 'csv') return { ...base, rows: parseCsv(text, file.toLowerCase().endsWith('.tsv') ? '\t' : ','), truncated: text.split('\n').length > 500 };
165  return { ...base, text };
166}
167
168/** The bytes of a picture or PDF inside the chat's folder. */
169export function rawFile(root, rawPath) {
170  const file = resolveChatFile(root, rawPath);
171  const mime = mimeOf(file);
172  if (mime === 'application/octet-stream') throw Object.assign(new Error('Only pictures and PDFs are served this way.'), { code: 'bad-type' });
173  return { bytes: readBytes(file), mime };
174}
175
176/** Files the person attached from a deliverable; the next message to the chat names them (@path), so the assistant reads them again. */
177export function createAttachments() {
178  const table = new Map();
179  return {
180    list: chatId => [...(table.get(chatId) ?? [])],
181    add(chatId, file) { const l = table.get(chatId) ?? []; if (!l.includes(file)) l.push(file); table.set(chatId, l.slice(-10)); return [...table.get(chatId)]; },
182    remove(chatId, file) { const l = (table.get(chatId) ?? []).filter(f => f !== file); table.set(chatId, l); return l; },
183    /** Take them for the next message (and forget them). */
184    take(chatId) { const l = table.get(chatId) ?? []; table.delete(chatId); return l; },
185  };
186}
187/** The message with its attachments named in front, as the assistant's instructions explain (@path is a file the person pointed at). */
188export const withAttachments = (message, files) => (files.length ? files.map(f => '@' + (/\s/.test(f) ? '"' + f + '"' : f)).join(' ') + ' ' + message : message);