okami.mom/strata

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

Niko1221Merge f-023-int into f-023-guifcb0c2d0e

main
11.8 KiB218 linesraw
1/**
2 * What the person chose in Settings -> Tools, and the single place that validates it.
3 *
4 * Saved (inside the host's settings file): which tool groups are off, which web search service to use (and its key, which never leaves
5 * this file: the screen only learns whether one is saved), whether the browser tool is on, and the person's own tools.
6 *
7 * The profile builder reads `profileView()`; the screen reads `view()`. Custom command and instruction tools are served by the app's
8 * own small tool server (custom-tools-mcp.mjs) from a JSON file this module writes, so they appear to the assistant as ordinary tools:
9 * `mcp__strata-instructions__<name>` (look-only: it just returns the person's instructions) and `mcp__strata-commands__<name>`
10 * (runs the person's command; asks first in Manual and is refused in Plan). A person's own tool server (a web address or a program)
11 * is added as `mcp__custom-<name>__...` and asks first in Manual like any connected tool.
12 */
13import { mkdirSync, renameSync, writeFileSync } from 'node:fs';
14import { join } from 'node:path';
15import { GROUP_IDS, TOOL_GROUPS } from './tools-catalog.mjs';
16import { SHELLS, clampTimeoutSec } from './custom-command-run.mjs';
17
18export const SEARCH_PROVIDERS = ['builtin', 'exa', 'perplexity', 'deepseek'];
19const KINDS = ['instructions', 'command', 'server'];
20const NAME = /^[A-Za-z][A-Za-z0-9 _-]{0,39}$/;
21const MAX_CUSTOM = 40;
22
23export const INSTRUCTIONS_SERVER = 'strata-instructions';
24export const COMMANDS_SERVER = 'strata-commands';
25
26const slug = value => String(value).toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 40) || 'tool';
27const clean = (value, max) => String(value ?? '').replace(/\0/g, '').slice(0, max);
28
29function normalize(raw) {
30  const r = raw && typeof raw === 'object' ? raw : {};
31  const search = r.search && typeof r.search === 'object' ? r.search : {};
32  return {
33    off: [...new Set((Array.isArray(r.off) ? r.off : []).filter(id => GROUP_IDS.includes(id)))],
34    search: { provider: SEARCH_PROVIDERS.includes(search.provider) ? search.provider : 'builtin', key: typeof search.key === 'string' ? search.key : '' },
35    browser: { enabled: r.browser?.enabled === true },
36    // Manual mode asks once per chat before the first web search or page. This switch (off unless the person turned it on) skips that question.
37    webWithoutAsking: r.webWithoutAsking === true,
38    custom: (Array.isArray(r.custom) ? r.custom : []).filter(t => t && NAME.test(t.name ?? '') && KINDS.includes(t.kind)).slice(0, MAX_CUSTOM).map(t => ({
39      id: String(t.id), name: String(t.name), about: clean(t.about, 300), kind: t.kind, enabled: t.enabled !== false,
40      instructions: clean(t.instructions, 20000), command: clean(t.command, 2000), address: clean(t.address, 2000),
41      args: (Array.isArray(t.args) ? t.args : []).slice(0, 50).map(a => clean(a, 1000)),
42      // a command tool's folder, shell and time allowed (custom-command-run.mjs); '' / 'auto' / 120 when not set
43      cwd: clean(t.cwd, 1000).trim(), shell: SHELLS.includes(t.shell) ? t.shell : 'auto', timeoutSec: clampTimeoutSec(t.timeoutSec),
44    })),
45  };
46}
47
48function validateCustom(body, existing) {
49  const name = String(body?.name ?? '').trim();
50  if (!NAME.test(name)) throw new Error('Give the tool a short name: letters, numbers, spaces or hyphens.');
51  const about = clean(body?.about, 300).trim();
52  if (!about) throw new Error('Say what the tool does, in a sentence. The assistant reads this to decide when to use it.');
53  const kind = body?.kind;
54  if (!KINDS.includes(kind)) throw new Error('Choose how the tool works.');
55  const out = { name, about, kind, instructions: '', command: '', address: '', args: [], cwd: '', shell: 'auto', timeoutSec: clampTimeoutSec(undefined) };
56  if (kind === 'instructions') {
57    out.instructions = clean(body.instructions, 20000).trim();
58    if (!out.instructions) throw new Error('Write the instructions the assistant should follow when it uses this tool.');
59  } else if (kind === 'command') {
60    out.command = clean(body.command, 2000).trim();
61    if (!out.command) throw new Error('Enter the command to run.');
62    if (/[\r\n]/.test(out.command)) throw new Error('Put the command on one line.');
63    // The edit form of Settings does not send these three: an edit keeps what the tool had.
64    const before = existing.find(t => t.id === body.id && t.kind === 'command');
65    out.cwd = body.cwd !== undefined ? clean(body.cwd, 1000).trim() : before?.cwd ?? '';
66    if (/[\r\n]/.test(out.cwd)) throw new Error('Put the folder on one line.');
67    if (body.shell !== undefined && !SHELLS.includes(body.shell)) throw new Error('Choose how the command runs: automatic, cmd, PowerShell, bash or sh.');
68    out.shell = body.shell !== undefined ? body.shell : before?.shell ?? 'auto';
69    if (body.timeoutSec !== undefined && !(Number(body.timeoutSec) >= 1 && Number(body.timeoutSec) <= 3600)) throw new Error('Give the time allowed in seconds, from 1 to 3600.');
70    out.timeoutSec = body.timeoutSec !== undefined ? clampTimeoutSec(body.timeoutSec) : before?.timeoutSec ?? clampTimeoutSec(undefined);
71  } else {
72    out.address = clean(body.address, 2000).trim();
73    if (!out.address) throw new Error('Enter the tool server’s web address, or the program that starts it.');
74    if (/[\r\n]/.test(out.address)) throw new Error('Put the address or program on one line.');
75    if (/^https?:\/\//i.test(out.address)) {
76      let url; try { url = new URL(out.address); } catch { throw new Error('That web address is not valid.'); }
77      if (url.username || url.password) throw new Error('Use a web address without a user name or password in it.');
78    }
79    out.args = (Array.isArray(body.args) ? body.args : []).slice(0, 50).map(a => clean(a, 1000)).filter(Boolean);
80  }
81  if (existing.some(t => t.name.toLowerCase() === name.toLowerCase() && t.id !== body.id)) throw new Error('You already have a tool with that name.');
82  return out;
83}
84
85const idFor = (name, existing) => {
86  const base = slug(name);
87  let id = base, n = 2;
88  while (existing.some(t => t.id === id)) id = `${base}_${n++}`;
89  return id;
90};
91
92/**
93 * @param {{read: () => object|undefined, write: (value: object) => void, dataDir: string, browser?: () => {found: boolean, name: string|null, path?: string|null, cli?: string|null}}} deps
94 */
95export function createAgentTools({ read, write, dataDir, browser = () => ({ found: false, name: null }) }) {
96  const state = () => normalize(read());
97  const filePath = join(dataDir, 'agent', 'custom-tools.json');
98
99  /** The file the app's own tool server reads: instruction tools and command tools that are on. */
100  function writeToolFile(s) {
101    const instructions = {}, commands = {};
102    for (const t of s.custom.filter(t => t.enabled)) {
103      const key = t.id;
104      if (t.kind === 'instructions') instructions[key] = { description: t.about, text: t.instructions };
105      else if (t.kind === 'command') commands[key] = { description: t.about, command: t.command, cwd: t.cwd, shell: t.shell, timeoutSec: t.timeoutSec };
106    }
107    mkdirSync(join(dataDir, 'agent'), { recursive: true });
108    const tmp = `${filePath}.tmp`;
109    writeFileSync(tmp, JSON.stringify({ instructions, commands }, null, 1));
110    renameSync(tmp, filePath);
111    return { instructions: Object.keys(instructions).length, commands: Object.keys(commands).length };
112  }
113
114  const save = s => { write(s); writeToolFile(s); };
115
116  function view() {
117    const s = state();
118    const probe = browser();
119    return {
120      groups: TOOL_GROUPS.map(g => ({ id: g.id, name: g.name, about: g.about, area: g.area, asks: g.asks, enabled: !s.off.includes(g.id) })),
121      search: { provider: s.search.provider, keySet: !!s.search.key },
122      webWithoutAsking: s.webWithoutAsking,
123      // `found` means the browser tool can run: a browser on this computer AND the tool server in the agent component.
124      browser: { enabled: s.browser.enabled, found: !!(probe.found && probe.cli), name: probe.name ?? null, ...(probe.found && !probe.cli ? { missing: 'component' } : {}) },
125      custom: s.custom.map(t => ({
126        id: t.id, name: t.name, about: t.about, kind: t.kind, enabled: t.enabled,
127        summary: t.kind === 'instructions' ? t.instructions.slice(0, 80) : t.kind === 'command' ? t.command : t.address,
128        instructions: t.instructions, command: t.command, address: t.address, args: t.args,
129        ...(t.kind === 'command' ? { cwd: t.cwd, shell: t.shell, timeoutSec: t.timeoutSec } : {}),
130      })),
131    };
132  }
133
134  return {
135    view,
136    filePath,
137    /** For the profile builder: plain values, secrets included. Never sent to the screen. */
138    profileView() {
139      const s = state();
140      const custom = s.custom.filter(t => t.enabled);
141      const servers = {};
142      for (const t of custom.filter(t => t.kind === 'server')) {
143        const name = `custom-${t.id.replace(/_/g, "-")}`.slice(0, 32);
144        servers[name] = /^https?:\/\//i.test(t.address) ? { url: t.address } : { command: t.address, args: t.args };
145      }
146      return {
147        off: new Set(s.off),
148        search: s.search,
149        webWithoutAsking: s.webWithoutAsking,
150        browserEnabled: s.browser.enabled && !!(browser().found && browser().cli),
151        browserPath: browser().path ?? null,
152        browserCli: browser().cli ?? null,
153        servers,
154        hasInstructionTools: custom.some(t => t.kind === 'instructions'),
155        hasCommandTools: custom.some(t => t.kind === 'command'),
156        toolFile: filePath,
157      };
158    },
159    update(change) {
160      const s = state();
161      if (change?.groups) {
162        for (const [id, on] of Object.entries(change.groups)) {
163          if (!GROUP_IDS.includes(id)) throw new Error('That tool is not known.');
164          s.off = on === false ? [...new Set([...s.off, id])] : s.off.filter(x => x !== id);
165        }
166      }
167      if (change?.search) {
168        const provider = change.search.provider;
169        if (provider !== undefined) {
170          if (!SEARCH_PROVIDERS.includes(provider)) throw new Error('Choose one of the listed search services.');
171          if (provider !== s.search.provider) s.search = { provider, key: '' };   // a key belongs to its service
172        }
173        if (change.search.key !== undefined) {
174          const key = String(change.search.key).trim();
175          if (!key || key.length > 500 || /[\s\0]/.test(key)) throw new Error('That key does not look right. Paste it again without spaces.');
176          s.search = { ...s.search, key };
177        }
178      }
179      if (typeof change?.webWithoutAsking === 'boolean') s.webWithoutAsking = change.webWithoutAsking;
180      if (change?.browser && typeof change.browser.enabled === 'boolean') s.browser = { enabled: change.browser.enabled };
181      if (change?.custom) {
182        for (const [id, on] of Object.entries(change.custom)) {
183          const t = s.custom.find(x => x.id === id);
184          if (!t) throw new Error('That tool is not in your list.');
185          t.enabled = on !== false;
186        }
187      }
188      save(s);
189      return view();
190    },
191    addCustom(body) {
192      const s = state();
193      if (s.custom.length >= MAX_CUSTOM) throw new Error(`You can have up to ${MAX_CUSTOM} tools of your own.`);
194      const t = validateCustom(body, s.custom);
195      s.custom.push({ id: idFor(t.name, s.custom), enabled: true, ...t });
196      save(s);
197      return view();
198    },
199    editCustom(id, body) {
200      const s = state();
201      const at = s.custom.findIndex(t => t.id === id);
202      if (at < 0) throw new Error('That tool is not in your list.');
203      const t = validateCustom({ ...body, id }, s.custom);
204      s.custom[at] = { ...s.custom[at], ...t };
205      save(s);
206      return view();
207    },
208    removeCustom(id) {
209      const s = state();
210      if (!s.custom.some(t => t.id === id)) throw new Error('That tool is not in your list.');
211      s.custom = s.custom.filter(t => t.id !== id);
212      save(s);
213      return view();
214    },
215    /** Make sure the tool server's file exists (host start). */
216    ensureFile() { writeToolFile(state()); },
217  };
218}