ShtukbaseStandard
package file→ .shtukbase/packages/chat/lens/chat.js

lens/chat.js

231 lines, 12.6 KB.

The file as it is in the package. Some comments in it may not be in English yet.

  1. // chat.js: the chat lens. An agent loop over llm.js with the space tools: in the shell the tools
  2. // are `space.tools` and calls go through shtuk.call; opened as a file they run over a picked folder.
  3. (function () {
  4. 'use strict';
  5. var LLM = window.shtukLLM, md = window.chatMarkdown, fs = window.chatFs;
  6. var hosted = !!window.CHAT_HOSTED;
  7. var MAX_STEPS = 8, MAX_RESULT = 20000;
  8. var $ = function (s) { return document.querySelector(s); };
  9. var list = $('[data-list]'), log = $('[data-log]'), input = $('[data-input]');
  10. var sendBtn = $('[data-send]'), stopBtn = $('[data-stop]'), form = $('[data-settings]');
  11. // ---------- storage ----------
  12. // With lens.js, shtuk.storage (the shell keeps it for sandboxed frames): values are read into
  13. // `memory` before use (preload) and written through. Without it, localStorage or memory.
  14. var memory = {}, persistent = true, kept = window.shtuk && window.shtuk.storage;
  15. try { localStorage.setItem('shtuk-chat-probe', '1'); localStorage.removeItem('shtuk-chat-probe'); } catch (e) { persistent = false; }
  16. if (kept) persistent = true;
  17. async function preload(k) { if (kept) { try { var v = await kept.get(k); if (v != null) memory[k] = v; } catch (e) { /* shell without storage */ } } }
  18. 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]; }
  19. 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 */ } } }
  20. function readSettings() {
  21. if (persistent && !kept) return LLM.loadSettings();
  22. var s = JSON.parse(getItem('shtuk-llm') || '{}');
  23. return { baseUrl: s.baseUrl || LLM.defaults.baseUrl, model: s.model || LLM.defaults.model, apiKey: s.apiKey || '' };
  24. }
  25. var settings = readSettings();
  26. function saveSettings(s) { settings = s; if (persistent && !kept) LLM.saveSettings(s); else setItem('shtuk-llm', JSON.stringify(s)); }
  27. // ---------- space: tools and calls ----------
  28. var space = { info: null, tools: [], call: null, key: 'shtuk-chat:file' };
  29. async function connectHosted() {
  30. space.call = function (action, params) { return window.shtuk.call(action, params); };
  31. try { space.info = await space.call('space.info'); } catch (e) { space.info = null; }
  32. try { space.tools = (await space.call('space.tools')) || []; } catch (e) { space.tools = []; note('Хост не отдал space.tools: чат без инструментов.'); }
  33. space.key = 'shtuk-chat:' + ((space.info && space.info.name) || location.host);
  34. }
  35. async function connectFolder() {
  36. var store = await fs.open();
  37. space.call = function (action, params) { return store.call(action, params); };
  38. space.info = await store.call('space.info');
  39. space.tools = fs.tools;
  40. space.key = 'shtuk-chat:folder:' + store.name;
  41. await preload(space.key);
  42. load();
  43. render();
  44. $('[data-where]').textContent = '📁 ' + store.name;
  45. }
  46. function actionOf(tool) { return tool.action || tool.name.replace('_', '.'); }
  47. function systemPrompt() {
  48. var info = space.info ? JSON.stringify(space.info) : '(no space connected: tools are unavailable)';
  49. return [
  50. 'You are the assistant inside Shtukbase, a workspace where everything is Markdown files in a folder (a space).',
  51. 'A space holds pages (Markdown files with YAML front matter; `type` says what a page is, default Page).',
  52. '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`).',
  53. 'A record is a page whose front matter holds the field values; its body is free Markdown.',
  54. 'Lenses are HTML views (table, board, record) that show pages; packages bring lenses, layouts, blueprints and settings.',
  55. '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,',
  56. '`records_write` to create or change a record (meta is merged, body replaces when given). Paths start with / and end with .md.',
  57. 'Before writing, read the collection so values match its properties (select options by name). Say briefly what you changed.',
  58. 'Answer in the language the user writes in (Russian if the user writes in Russian). Be concise; use short Markdown.',
  59. 'Space info: ' + info
  60. ].join('\n');
  61. }
  62. // ---------- conversation ----------
  63. var msgs = [];
  64. function load() { try { msgs = JSON.parse(getItem(space.key) || '[]'); } catch (e) { msgs = []; } }
  65. function save() { setItem(space.key, JSON.stringify(msgs.slice(-200))); }
  66. // ---------- rendering ----------
  67. function el(tag, cls, text) { var n = document.createElement(tag); if (cls) n.className = cls; if (text != null) n.textContent = text; return n; }
  68. function nearBottom() { return log.scrollHeight - log.scrollTop - log.clientHeight < 48; }
  69. var stick = true;
  70. log.addEventListener('scroll', function () { stick = nearBottom(); });
  71. function follow() { if (stick) log.scrollTop = log.scrollHeight; }
  72. function shortArgs(s) {
  73. var a; try { a = JSON.parse(s || '{}'); } catch (e) { return String(s || '').slice(0, 60); }
  74. var t = Object.keys(a).map(function (k) { var v = a[k]; return typeof v === 'string' ? v : k; }).join(', ');
  75. return t.length > 60 ? t.slice(0, 59) + '…' : t;
  76. }
  77. function size(n) { return n < 1024 ? n + ' Б' : (n / 1024).toFixed(1) + ' КБ'; }
  78. function toolRow(tc) {
  79. var res = msgs.find(function (m) { return m.role === 'tool' && m.tool_call_id === tc.id; });
  80. var d = el('details', 'chat-tool');
  81. var s = el('summary');
  82. s.appendChild(el('span', 'chat-tool-name', tc.function.name));
  83. s.appendChild(el('span', 'chat-tool-args', shortArgs(tc.function.arguments)));
  84. var status = res ? (res.error ? 'ошибка' : size(res.content.length)) : '…';
  85. s.appendChild(el('span', 'chat-tool-size' + (res && res.error ? ' is-error' : ''), status));
  86. d.appendChild(s);
  87. d.appendChild(el('pre', 'chat-tool-body', 'args: ' + (tc.function.arguments || '{}') + (res ? '\n\n' + res.content : '')));
  88. return d;
  89. }
  90. function msgNode(m) {
  91. if (m.role === 'user') { var u = el('div', 'chat-msg chat-user'); u.appendChild(el('div', 'chat-bubble', m.content)); return u; }
  92. if (m.role === 'assistant') {
  93. var a = el('div', 'chat-msg chat-assistant');
  94. if (m.content) { var t = el('div', 'chat-text'); t.innerHTML = md(m.content); a.appendChild(t); }
  95. (m.tool_calls || []).forEach(function (tc) { a.appendChild(toolRow(tc)); });
  96. return a;
  97. }
  98. if (m.role === 'error') return el('div', 'chat-msg chat-error', m.content);
  99. return null;
  100. }
  101. function render() {
  102. list.textContent = '';
  103. if (!msgs.length) {
  104. var empty = el('div', 'chat-empty');
  105. empty.appendChild(el('p', null, 'Спросите о пространстве: что в нём, какие заявки новые, или попросите добавить запись.'));
  106. list.appendChild(empty);
  107. }
  108. msgs.forEach(function (m) { var n = msgNode(m); if (n) list.appendChild(n); });
  109. follow();
  110. }
  111. function note(text) { msgs.push({ role: 'error', content: text }); }
  112. // ---------- the agent loop ----------
  113. var ctrl = null;
  114. function busy(on) {
  115. sendBtn.hidden = on; stopBtn.hidden = !on;
  116. document.body.classList.toggle('is-busy', on);
  117. }
  118. function wire() {
  119. // what goes to the model: no error notes, and no tool calls when no tools are connected
  120. return msgs.filter(function (m) { return m.role !== 'error'; }).map(function (m) {
  121. var o = { role: m.role, content: m.content == null ? '' : m.content };
  122. if (m.tool_calls) o.tool_calls = m.tool_calls;
  123. if (m.tool_call_id) o.tool_call_id = m.tool_call_id;
  124. return o;
  125. });
  126. }
  127. async function run() {
  128. ctrl = new AbortController();
  129. busy(true);
  130. try {
  131. for (var step = 0; step < MAX_STEPS; step++) {
  132. var live = { role: 'assistant', content: '' };
  133. var node = el('div', 'chat-msg chat-assistant'), text = el('div', 'chat-text chat-live');
  134. node.appendChild(text); list.appendChild(node); follow();
  135. var pending = false;
  136. var reply = await LLM.chat(settings, [{ role: 'system', content: systemPrompt() }].concat(wire()), space.call ? space.tools : [], function (d) {
  137. if (d.text) { live.content += d.text; if (!pending) { pending = true; requestAnimationFrame(function () { pending = false; text.innerHTML = md(live.content); follow(); }); } }
  138. }, ctrl.signal);
  139. msgs.push(reply); save(); render();
  140. if (!reply.tool_calls) break;
  141. for (var i = 0; i < reply.tool_calls.length; i++) {
  142. var tc = reply.tool_calls[i], out;
  143. var tool = space.tools.find(function (t) { return t.name === tc.function.name; });
  144. try {
  145. if (!tool) throw new Error('Unknown tool: ' + tc.function.name);
  146. var args = tc.function.arguments ? JSON.parse(tc.function.arguments) : {};
  147. var result = await space.call(actionOf(tool), args);
  148. out = { role: 'tool', tool_call_id: tc.id, content: (JSON.stringify(result) || 'null').slice(0, MAX_RESULT) };
  149. } catch (e) {
  150. out = { role: 'tool', tool_call_id: tc.id, content: 'Error: ' + (e && e.message || e), error: true };
  151. }
  152. msgs.push(out); save(); render();
  153. }
  154. if (step === MAX_STEPS - 1) { note('Остановлено: больше ' + MAX_STEPS + ' шагов.'); }
  155. }
  156. } catch (e) {
  157. if (e && e.name === 'AbortError') note('Остановлено.');
  158. else note('Ошибка: ' + (e && e.message || e));
  159. } finally {
  160. ctrl = null; busy(false); save(); render(); input.focus();
  161. }
  162. }
  163. function send() {
  164. var text = input.value.trim();
  165. if (!text || ctrl) return;
  166. if (!settings.apiKey) { showSettings(true); return; }
  167. input.value = ''; grow();
  168. msgs.push({ role: 'user', content: text }); save();
  169. stick = true; render();
  170. run();
  171. }
  172. // ---------- input ----------
  173. function grow() { input.style.height = 'auto'; input.style.height = Math.min(input.scrollHeight, 200) + 'px'; }
  174. input.addEventListener('input', grow);
  175. input.addEventListener('keydown', function (e) {
  176. if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); send(); }
  177. });
  178. // Sandboxed frames block form submission, so the chat uses plain buttons and keys.
  179. sendBtn.addEventListener('click', send);
  180. stopBtn.addEventListener('click', function () { if (ctrl) ctrl.abort(); });
  181. $('[data-clear]').addEventListener('click', function () { if (ctrl) ctrl.abort(); msgs = []; save(); render(); });
  182. // ---------- settings ----------
  183. function showSettings(on) {
  184. form.hidden = !on;
  185. if (on) {
  186. field('baseUrl').value = settings.baseUrl; field('model').value = settings.model; field('apiKey').value = settings.apiKey;
  187. $('[data-memnote]').hidden = persistent;
  188. if (!window.shtuk || !window.shtuk.framed) (settings.apiKey ? field('model') : field('apiKey')).focus();
  189. }
  190. }
  191. $('[data-gear]').addEventListener('click', function () { showSettings(form.hidden); });
  192. $('[data-cancel]').addEventListener('click', function () { showSettings(false); });
  193. function field(name) { return form.querySelector('[name="' + name + '"]'); }
  194. function saveForm() {
  195. saveSettings({ baseUrl: field('baseUrl').value.trim() || LLM.defaults.baseUrl, model: field('model').value.trim() || LLM.defaults.model, apiKey: field('apiKey').value.trim() });
  196. showSettings(false);
  197. input.focus();
  198. }
  199. $('[data-save]').addEventListener('click', saveForm);
  200. form.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); saveForm(); } });
  201. // ---------- start ----------
  202. (async function () {
  203. if (hosted && window.shtuk) {
  204. await connectHosted();
  205. $('[data-where]').textContent = space.info && space.info.name ? space.info.name : '';
  206. } else if (fs && fs.supported) {
  207. var b = $('[data-folder]');
  208. b.hidden = false;
  209. b.addEventListener('click', function () { connectFolder().catch(function (e) { if (e.name !== 'AbortError') { note('Папка не открылась: ' + e.message); render(); } }); });
  210. $('[data-where]').textContent = 'без пространства';
  211. } else {
  212. $('[data-where]').textContent = 'без инструментов';
  213. }
  214. await preload('shtuk-llm');
  215. await preload(space.key);
  216. settings = readSettings();
  217. load();
  218. render();
  219. if (!settings.apiKey) showSettings(true);
  220. if (window.shtuk && window.shtuk.ready) window.shtuk.ready();
  221. })();
  222. })();