archivo del paquete→ .shtukbase/packages/chat/lens/chat.js
lens/chat.js
231 líneas, 12.6 KB.
El archivo tal como está en el paquete: el código y sus comentarios no se traducen.
- // chat.js: the chat lens. An agent loop over llm.js with the space tools: in the shell the tools
- // are `space.tools` and calls go through shtuk.call; opened as a file they run over a picked folder.
- (function () {
- 'use strict';
- var LLM = window.shtukLLM, md = window.chatMarkdown, fs = window.chatFs;
- var hosted = !!window.CHAT_HOSTED;
- var MAX_STEPS = 8, MAX_RESULT = 20000;
- var $ = function (s) { return document.querySelector(s); };
- var list = $('[data-list]'), log = $('[data-log]'), input = $('[data-input]');
- var sendBtn = $('[data-send]'), stopBtn = $('[data-stop]'), form = $('[data-settings]');
- // ---------- storage ----------
- // With lens.js, shtuk.storage (the shell keeps it for sandboxed frames): values are read into
- // `memory` before use (preload) and written through. Without it, localStorage or memory.
- var memory = {}, persistent = true, kept = window.shtuk && window.shtuk.storage;
- try { localStorage.setItem('shtuk-chat-probe', '1'); localStorage.removeItem('shtuk-chat-probe'); } catch (e) { persistent = false; }
- if (kept) persistent = true;
- async function preload(k) { if (kept) { try { var v = await kept.get(k); if (v != null) memory[k] = v; } catch (e) { /* shell without storage */ } } }
- function getItem(k) { if (kept) return memory[k] == null ? null : memory[k]; if (persistent) { try { return localStorage.getItem(k); } catch (e) { /* fall through */ } } return memory[k] == null ? null : memory[k]; }
- function setItem(k, v) { memory[k] = v; if (kept) { kept.set(k, v).catch(function () {}); return; } if (persistent) { try { localStorage.setItem(k, v); } catch (e) { /* quota */ } } }
- function readSettings() {
- if (persistent && !kept) return LLM.loadSettings();
- var s = JSON.parse(getItem('shtuk-llm') || '{}');
- return { baseUrl: s.baseUrl || LLM.defaults.baseUrl, model: s.model || LLM.defaults.model, apiKey: s.apiKey || '' };
- }
- var settings = readSettings();
- function saveSettings(s) { settings = s; if (persistent && !kept) LLM.saveSettings(s); else setItem('shtuk-llm', JSON.stringify(s)); }
- // ---------- space: tools and calls ----------
- var space = { info: null, tools: [], call: null, key: 'shtuk-chat:file' };
- async function connectHosted() {
- space.call = function (action, params) { return window.shtuk.call(action, params); };
- try { space.info = await space.call('space.info'); } catch (e) { space.info = null; }
- try { space.tools = (await space.call('space.tools')) || []; } catch (e) { space.tools = []; note('Хост не отдал space.tools: чат без инструментов.'); }
- space.key = 'shtuk-chat:' + ((space.info && space.info.name) || location.host);
- }
- async function connectFolder() {
- var store = await fs.open();
- space.call = function (action, params) { return store.call(action, params); };
- space.info = await store.call('space.info');
- space.tools = fs.tools;
- space.key = 'shtuk-chat:folder:' + store.name;
- await preload(space.key);
- load();
- render();
- $('[data-where]').textContent = '📁 ' + store.name;
- }
- function actionOf(tool) { return tool.action || tool.name.replace('_', '.'); }
- function systemPrompt() {
- var info = space.info ? JSON.stringify(space.info) : '(no space connected: tools are unavailable)';
- return [
- 'You are the assistant inside Shtukbase, a workspace where everything is Markdown files in a folder (a space).',
- 'A space holds pages (Markdown files with YAML front matter; `type` says what a page is, default Page).',
- 'A collection is a page with `type: Collection`; its `properties` describe fields and its records are the pages in its folder (`items.path` or `writeTo`).',
- 'A record is a page whose front matter holds the field values; its body is free Markdown.',
- 'Lenses are HTML views (table, board, record) that show pages; packages bring lenses, layouts, blueprints and settings.',
- 'Use the tools to look before you answer: `tree` to find pages, `records_list` to read a collection and its records, `records_read` for one record,',
- '`records_write` to create or change a record (meta is merged, body replaces when given). Paths start with / and end with .md.',
- 'Before writing, read the collection so values match its properties (select options by name). Say briefly what you changed.',
- 'Answer in the language the user writes in (Russian if the user writes in Russian). Be concise; use short Markdown.',
- 'Space info: ' + info
- ].join('\n');
- }
- // ---------- conversation ----------
- var msgs = [];
- function load() { try { msgs = JSON.parse(getItem(space.key) || '[]'); } catch (e) { msgs = []; } }
- function save() { setItem(space.key, JSON.stringify(msgs.slice(-200))); }
- // ---------- rendering ----------
- function el(tag, cls, text) { var n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n; }
- function nearBottom() { return log.scrollHeight - log.scrollTop - log.clientHeight < 48; }
- var stick = true;
- log.addEventListener('scroll', function () { stick = nearBottom(); });
- function follow() { if (stick) log.scrollTop = log.scrollHeight; }
- function shortArgs(s) {
- var a; try { a = JSON.parse(s || '{}'); } catch (e) { return String(s || '').slice(0, 60); }
- var t = Object.keys(a).map(function (k) { var v = a[k]; return typeof v === 'string' ? v : k; }).join(', ');
- return t.length > 60 ? t.slice(0, 59) + '…' : t;
- }
- function size(n) { return n < 1024 ? n + ' Б' : (n / 1024).toFixed(1) + ' КБ'; }
- function toolRow(tc) {
- var res = msgs.find(function (m) { return m.role === 'tool' && m.tool_call_id === tc.id; });
- var d = el('details', 'chat-tool');
- var s = el('summary');
- s.appendChild(el('span', 'chat-tool-name', tc.function.name));
- s.appendChild(el('span', 'chat-tool-args', shortArgs(tc.function.arguments)));
- var status = res ? (res.error ? 'ошибка' : size(res.content.length)) : '…';
- s.appendChild(el('span', 'chat-tool-size' + (res && res.error ? ' is-error' : ''), status));
- d.appendChild(s);
- d.appendChild(el('pre', 'chat-tool-body', 'args: ' + (tc.function.arguments || '{}') + (res ? '\n\n' + res.content : '')));
- return d;
- }
- function msgNode(m) {
- if (m.role === 'user') { var u = el('div', 'chat-msg chat-user'); u.appendChild(el('div', 'chat-bubble', m.content)); return u; }
- if (m.role === 'assistant') {
- var a = el('div', 'chat-msg chat-assistant');
- if (m.content) { var t = el('div', 'chat-text'); t.innerHTML = md(m.content); a.appendChild(t); }
- (m.tool_calls || []).forEach(function (tc) { a.appendChild(toolRow(tc)); });
- return a;
- }
- if (m.role === 'error') return el('div', 'chat-msg chat-error', m.content);
- return null;
- }
- function render() {
- list.textContent = '';
- if (!msgs.length) {
- var empty = el('div', 'chat-empty');
- empty.appendChild(el('p', null, 'Спросите о пространстве: что в нём, какие заявки новые, или попросите добавить запись.'));
- list.appendChild(empty);
- }
- msgs.forEach(function (m) { var n = msgNode(m); if (n) list.appendChild(n); });
- follow();
- }
- function note(text) { msgs.push({ role: 'error', content: text }); }
- // ---------- the agent loop ----------
- var ctrl = null;
- function busy(on) {
- sendBtn.hidden = on; stopBtn.hidden = !on;
- document.body.classList.toggle('is-busy', on);
- }
- function wire() {
- // what goes to the model: no error notes, and no tool calls when no tools are connected
- return msgs.filter(function (m) { return m.role !== 'error'; }).map(function (m) {
- var o = { role: m.role, content: m.content == null ? '' : m.content };
- if (m.tool_calls) o.tool_calls = m.tool_calls;
- if (m.tool_call_id) o.tool_call_id = m.tool_call_id;
- return o;
- });
- }
- async function run() {
- ctrl = new AbortController();
- busy(true);
- try {
- for (var step = 0; step < MAX_STEPS; step++) {
- var live = { role: 'assistant', content: '' };
- var node = el('div', 'chat-msg chat-assistant'), text = el('div', 'chat-text chat-live');
- node.appendChild(text); list.appendChild(node); follow();
- var pending = false;
- var reply = await LLM.chat(settings, [{ role: 'system', content: systemPrompt() }].concat(wire()), space.call ? space.tools : [], function (d) {
- if (d.text) { live.content += d.text; if (!pending) { pending = true; requestAnimationFrame(function () { pending = false; text.innerHTML = md(live.content); follow(); }); } }
- }, ctrl.signal);
- msgs.push(reply); save(); render();
- if (!reply.tool_calls) break;
- for (var i = 0; i < reply.tool_calls.length; i++) {
- var tc = reply.tool_calls[i], out;
- var tool = space.tools.find(function (t) { return t.name === tc.function.name; });
- try {
- if (!tool) throw new Error('Unknown tool: ' + tc.function.name);
- var args = tc.function.arguments ? JSON.parse(tc.function.arguments) : {};
- var result = await space.call(actionOf(tool), args);
- out = { role: 'tool', tool_call_id: tc.id, content: (JSON.stringify(result) || 'null').slice(0, MAX_RESULT) };
- } catch (e) {
- out = { role: 'tool', tool_call_id: tc.id, content: 'Error: ' + (e && e.message || e), error: true };
- }
- msgs.push(out); save(); render();
- }
- if (step === MAX_STEPS - 1) { note('Остановлено: больше ' + MAX_STEPS + ' шагов.'); }
- }
- } catch (e) {
- if (e && e.name === 'AbortError') note('Остановлено.');
- else note('Ошибка: ' + (e && e.message || e));
- } finally {
- ctrl = null; busy(false); save(); render(); input.focus();
- }
- }
- function send() {
- var text = input.value.trim();
- if (!text || ctrl) return;
- if (!settings.apiKey) { showSettings(true); return; }
- input.value = ''; grow();
- msgs.push({ role: 'user', content: text }); save();
- stick = true; render();
- run();
- }
- // ---------- input ----------
- function grow() { input.style.height = 'auto'; input.style.height = Math.min(input.scrollHeight, 200) + 'px'; }
- input.addEventListener('input', grow);
- input.addEventListener('keydown', function (e) {
- if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); send(); }
- });
- // Sandboxed frames block form submission, so the chat uses plain buttons and keys.
- sendBtn.addEventListener('click', send);
- stopBtn.addEventListener('click', function () { if (ctrl) ctrl.abort(); });
- $('[data-clear]').addEventListener('click', function () { if (ctrl) ctrl.abort(); msgs = []; save(); render(); });
- // ---------- settings ----------
- function showSettings(on) {
- form.hidden = !on;
- if (on) {
- field('baseUrl').value = settings.baseUrl; field('model').value = settings.model; field('apiKey').value = settings.apiKey;
- $('[data-memnote]').hidden = persistent;
- if (!window.shtuk || !window.shtuk.framed) (settings.apiKey ? field('model') : field('apiKey')).focus();
- }
- }
- $('[data-gear]').addEventListener('click', function () { showSettings(form.hidden); });
- $('[data-cancel]').addEventListener('click', function () { showSettings(false); });
- function field(name) { return form.querySelector('[name="' + name + '"]'); }
- function saveForm() {
- saveSettings({ baseUrl: field('baseUrl').value.trim() || LLM.defaults.baseUrl, model: field('model').value.trim() || LLM.defaults.model, apiKey: field('apiKey').value.trim() });
- showSettings(false);
- input.focus();
- }
- $('[data-save]').addEventListener('click', saveForm);
- form.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); saveForm(); } });
- // ---------- start ----------
- (async function () {
- if (hosted && window.shtuk) {
- await connectHosted();
- $('[data-where]').textContent = space.info && space.info.name ? space.info.name : '';
- } else if (fs && fs.supported) {
- var b = $('[data-folder]');
- b.hidden = false;
- b.addEventListener('click', function () { connectFolder().catch(function (e) { if (e.name !== 'AbortError') { note('Папка не открылась: ' + e.message); render(); } }); });
- $('[data-where]').textContent = 'без пространства';
- } else {
- $('[data-where]').textContent = 'без инструментов';
- }
- await preload('shtuk-llm');
- await preload(space.key);
- settings = readSettings();
- load();
- render();
- if (!settings.apiKey) showSettings(true);
- if (window.shtuk && window.shtuk.ready) window.shtuk.ready();
- })();
- })();