@clarity-js/agent 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/app.js ADDED
@@ -0,0 +1,139 @@
1
+ // @clarity-js/agent — the agent in a window of its own.
2
+ //
3
+ // clarity agent app [--model provider:model] [--mode ask|edits|auto] [--port n] [--no-open]
4
+ //
5
+ // import { startApp } from '@clarity-js/agent/app'
6
+ // const app = await startApp({ root: '.' }) → { url, port, token, session, close() }
7
+ //
8
+ // It is a small server on this computer (127.0.0.1, nowhere else) and a page: the same panel the editor shows,
9
+ // in a browser window without the browser's bars where Chrome or Edge is there, otherwise in the default
10
+ // browser. The page can be installed (it has a manifest), and then it is an app in the Dock or the Start menu.
11
+ //
12
+ // What keeps it this computer's alone: it listens on the loopback address only; the page's address carries a
13
+ // token made for this run, and nothing is said or heard without it; a request whose Host is not this address
14
+ // is refused (a page elsewhere that points a name at 127.0.0.1 gets nothing); so is one that comes from another
15
+ // page (Origin). The page loads nothing from anywhere else, and its policy says so.
16
+
17
+ import http from 'node:http';
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import crypto from 'node:crypto';
21
+ import { spawn } from 'node:child_process';
22
+ import { fileURLToPath, pathToFileURL } from 'node:url';
23
+ import { createSession } from './session.js';
24
+
25
+ const HERE = path.dirname(fileURLToPath(import.meta.url)), UI = path.join(HERE, '..', 'ui');
26
+ const ICON = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#14171d"/><path d="M44 21a16 16 0 1 0 0 22" fill="none" stroke="#4d8dff" stroke-width="7" stroke-linecap="round"/><circle cx="45" cy="32" r="4.5" fill="#f6f4ef"/></svg>`;
27
+ const MANIFEST = JSON.stringify({ name: 'Clarity Agent', short_name: 'Clarity Agent', start_url: '.', display: 'standalone', background_color: '#14171d', theme_color: '#14171d', icons: [{ src: 'icon.svg', sizes: 'any', type: 'image/svg+xml', purpose: 'any' }] });
28
+ const POLICY = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; manifest-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
29
+ const page = (token, name, built) => `<!doctype html>
30
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
31
+ <meta name="clarity-agent-token" content="${token}"><meta name="color-scheme" content="light dark">
32
+ <title>${name.replace(/[<&"]/g, '')} — Clarity Agent</title>
33
+ <link rel="icon" href="icon.svg" type="image/svg+xml"><link rel="manifest" href="manifest.webmanifest"><link rel="stylesheet" href="ui/panel.css">
34
+ </head><body><div id="ca-root"></div>${built ? '<script src="ui/panel.js"></script>' : '<script type="module" src="ui/main.js"></script>'}</body></html>`;
35
+
36
+ /** Clarity's compiler and where its runtime's files are: the project's own copy, or the one beside this package. */
37
+ async function findClarity(root) {
38
+ const tries = [pathToFileURL(path.join(root, 'package.json')).href, import.meta.url];
39
+ for (const from of tries) {
40
+ try {
41
+ const { createRequire } = await import('node:module');
42
+ const main = createRequire(from).resolve('@ozsarman/clarityjs');
43
+ const { compile } = await import(pathToFileURL(main).href);
44
+ return { compile, runtimeDir: path.dirname(main) };
45
+ } catch { /* the next place */ }
46
+ }
47
+ throw new Error('Clarity Agent\'s window needs @ozsarman/clarityjs (it draws its page with it): npm i @ozsarman/clarityjs');
48
+ }
49
+
50
+ /** The browsers that can show a page as a window of its own (--app). */
51
+ function appBrowsers(platform = process.platform, env = process.env) {
52
+ if (platform === 'darwin') return ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge', '/Applications/Chromium.app/Contents/MacOS/Chromium', '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser'];
53
+ if (platform === 'win32') return [env['ProgramFiles'], env['ProgramFiles(x86)'], env.LOCALAPPDATA].filter(Boolean).flatMap((d) => [path.join(d, 'Google/Chrome/Application/chrome.exe'), path.join(d, 'Microsoft/Edge/Application/msedge.exe')]);
54
+ return ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/usr/bin/microsoft-edge', '/snap/bin/chromium'];
55
+ }
56
+ /** Show an address: as a window of its own if a browser that can is found, else in the default browser. → what was run */
57
+ export function openWindow(url, { platform = process.platform, env = process.env, exists = fs.existsSync, run = (cmd, args) => spawn(cmd, args, { detached: true, stdio: 'ignore' }).unref() } = {}) {
58
+ const browser = appBrowsers(platform, env).find((p) => exists(p));
59
+ const [cmd, args] = browser ? [browser, [`--app=${url}`, '--new-window']] : platform === 'darwin' ? ['open', [url]] : platform === 'win32' ? ['cmd', ['/c', 'start', '', url]] : ['xdg-open', [url]];
60
+ try { run(cmd, args); } catch { return null; }
61
+ return { cmd, args, window: !!browser };
62
+ }
63
+
64
+ /**
65
+ * Start the window's server.
66
+ * @param options root (the project) · port (0: any free one) · open (true: show the window) · model, mode ·
67
+ * make, options (as createSession) · clarity ({ compile, runtimeDir }: found unless given) · keys (the key store,
68
+ * for a key given in the window) · panel ({ js, css }: the panel built beforehand into one script, as an app that
69
+ * carries no compiler serves it; then Clarity is not looked for)
70
+ * → { url, port, token, session, close() }
71
+ */
72
+ export async function startApp({ root = process.cwd(), port = 0, open = true, model = null, mode = 'ask', make = null, options = {}, clarity = null, keys = null, opener = openWindow, panel = null } = {}) {
73
+ root = fs.realpathSync(root);
74
+ const kit = panel ? null : clarity ?? await findClarity(root), token = crypto.randomBytes(24).toString('base64url'), streams = new Set();
75
+ const post = (message) => { const line = `data: ${JSON.stringify(message)}\n\n`; for (const s of streams) s.write(line); };
76
+ const session = createSession({ root, post, make, model, mode, options });
77
+ let asked = 0;
78
+ // what the panel leaves to its shell: here a small form on the page asks, and its answer comes back as `filled`
79
+ const shell = async (m) => {
80
+ if (m.type === 'pick-model') post({ type: 'prompt', id: 'p' + (++asked), what: 'model', title: 'Which model?', fields: [{ name: 'spec', label: 'provider:model', placeholder: 'anthropic:claude-sonnet-5-5', value: session.state().model ?? '' }] });
81
+ else if (m.type === 'give-key') post({ type: 'prompt', id: 'p' + (++asked), what: 'key', title: 'A key for a provider', fields: [{ name: 'id', label: 'Provider', placeholder: 'anthropic' }, { name: 'key', label: 'Key', secret: true }] });
82
+ else if (m.type === 'filled' && m.what === 'model') await session.handle({ type: 'model', spec: String(m.values?.spec ?? '').trim() || null });
83
+ else if (m.type === 'filled' && m.what === 'key') {
84
+ const id = String(m.values?.id ?? '').trim().toLowerCase(), key = String(m.values?.key ?? '').trim();
85
+ if (!/^[a-z0-9-]{2,40}$/.test(id) || !key) { post({ type: 'notice', text: 'A key needs the provider\'s name (anthropic, openai, gemini …) and the key.' }); return; }
86
+ const store = keys ?? (await import('./index.js')).keyStore({ envName: (await import('./index.js')).envNameOf });
87
+ const where = store.set(id, key);
88
+ post({ type: 'notice', text: `The key for ${id} is kept in ${where === 'keychain' ? 'the system keychain' : 'a file only you can read'}.` });
89
+ await session.handle({ type: 'model', spec: session.state().model }); // the next message is tried with it
90
+ } else await session.handle(m);
91
+ };
92
+ const types = { '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8' };
93
+ const give = (res, status, type, body, more = {}) => { res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer', ...more }); res.end(body); };
94
+ const server = http.createServer(async (req, res) => {
95
+ try {
96
+ const at = server.address(), here = [`127.0.0.1:${at.port}`, `localhost:${at.port}`];
97
+ if (!here.includes(req.headers.host ?? '')) return give(res, 403, 'text/plain', 'This is not for you.');
98
+ const origin = req.headers.origin;
99
+ if (origin && !here.some((h) => origin === `http://${h}`)) return give(res, 403, 'text/plain', 'This is not for you.');
100
+ const url = new URL(req.url, `http://${req.headers.host}`), given = url.searchParams.get('t') ?? req.headers['x-clarity-agent'] ?? '';
101
+ const known = given.length === token.length && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(token));
102
+ if (req.method === 'GET' && url.pathname === '/') return known ? give(res, 200, 'text/html; charset=utf-8', page(token, path.basename(root), !!panel), { 'content-security-policy': POLICY }) : give(res, 403, 'text/plain', 'Open Clarity Agent from the address the terminal printed: it carries this run\'s token.');
103
+ if (req.method === 'GET' && url.pathname === '/icon.svg') return give(res, 200, 'image/svg+xml', ICON);
104
+ if (req.method === 'GET' && url.pathname === '/manifest.webmanifest') return give(res, 200, 'application/manifest+json', MANIFEST);
105
+ if (panel) {
106
+ if (req.method === 'GET' && url.pathname === '/ui/panel.js') return give(res, 200, types['.js'], panel.js);
107
+ if (req.method === 'GET' && url.pathname === '/ui/panel.css') return give(res, 200, types['.css'], panel.css);
108
+ }
109
+ if (!panel && req.method === 'GET' && url.pathname === '/ui/Panel.clarity') return give(res, 200, types['.js'], kit.compile(fs.readFileSync(path.join(UI, 'Panel.clarity'), 'utf8'), { filename: 'Panel.clarity', runtimePath: '/clarity/runtime.js' }).code);
110
+ if (!panel && req.method === 'GET' && url.pathname === '/ui/main.js') return give(res, 200, types['.js'], fs.readFileSync(path.join(UI, 'main.js'), 'utf8').replace("'@ozsarman/clarityjs/runtime'", "'/clarity/runtime.js'"));
111
+ if (req.method === 'GET' && url.pathname === '/ui/panel.css') return give(res, 200, types['.css'], fs.readFileSync(path.join(UI, 'panel.css')));
112
+ const part = /^\/clarity\/([\w.-]+\.js)$/.exec(url.pathname);
113
+ if (kit && req.method === 'GET' && part && fs.existsSync(path.join(kit.runtimeDir, part[1]))) return give(res, 200, types['.js'], fs.readFileSync(path.join(kit.runtimeDir, part[1])));
114
+ if (req.method === 'GET' && url.pathname === '/events') {
115
+ if (!known) return give(res, 403, 'text/plain', 'No.');
116
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive', 'x-accel-buffering': 'no' });
117
+ // a window that has just come (or come back) is told the whole of it at once: its own hello may have been said before it could hear
118
+ res.write(`: the agent\n\ndata: ${JSON.stringify(session.state())}\n\n`); streams.add(res); req.on('close', () => streams.delete(res));
119
+ return;
120
+ }
121
+ if (req.method === 'POST' && url.pathname === '/say') {
122
+ if (!known) return give(res, 403, 'text/plain', 'No.');
123
+ let body = ''; for await (const chunk of req) { body += chunk; if (body.length > 1e6) return give(res, 413, 'text/plain', 'Too long.'); }
124
+ let message; try { message = JSON.parse(body); } catch { return give(res, 400, 'text/plain', 'Not a message.'); }
125
+ give(res, 204, 'text/plain', '');
126
+ shell(message).catch((e) => post({ type: 'notice', text: e.message }));
127
+ return;
128
+ }
129
+ give(res, 404, 'text/plain', 'Not here.');
130
+ } catch (e) { try { give(res, 500, 'text/plain', e.message); } catch { /* it was already answered */ } }
131
+ });
132
+ await new Promise((done, fail) => { server.once('error', fail); server.listen(port, '127.0.0.1', done); });
133
+ const url = `http://127.0.0.1:${server.address().port}/?t=${token}`;
134
+ const shown = open ? opener(url) : null;
135
+ return {
136
+ url, port: server.address().port, token, session, shown,
137
+ async close() { for (const s of streams) s.end(); streams.clear(); await session.dispose(); await new Promise((done) => { server.closeAllConnections?.(); server.close(() => done()); }); },
138
+ };
139
+ }
package/src/budget.js ADDED
@@ -0,0 +1,34 @@
1
+ // @clarity-js/agent — money is asked about before it is spent. Every paid generation is estimated first, checked
2
+ // against the limits (per day, per month, per connector), and written to a ledger after it is made. A limit that
3
+ // would be passed stops the agent; it says how much and asks.
4
+
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { configDir } from './keys.js';
8
+
9
+ const day = (t) => new Date(t).toISOString().slice(0, 10), month = (t) => new Date(t).toISOString().slice(0, 7);
10
+ export const usd = (v) => `$${(Math.round((v ?? 0) * 100) / 100).toFixed(2)}`;
11
+
12
+ /** limits: { daily, monthly, perConnector: { tripo: 5 } } in US dollars; the defaults are small on purpose. */
13
+ export function ledger({ env = process.env, file = path.join(configDir(env), 'ledger.json'), limits = {}, now = () => Date.now() } = {}) {
14
+ const lim = { daily: 5, monthly: 50, perConnector: {}, ...limits };
15
+ const read = () => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return []; } };
16
+ const spent = (pick) => read().filter(pick).reduce((s, e) => s + (e.usd ?? 0), 0);
17
+ return {
18
+ limits: lim,
19
+ today() { const d = day(now()); return spent((e) => day(e.at) === d); },
20
+ thisMonth() { const m = month(now()); return spent((e) => month(e.at) === m); },
21
+ byConnector(id) { const m = month(now()); return spent((e) => e.connector === id && month(e.at) === m); },
22
+ /** Would this spend pass a limit? → null, or the limit it passes in words. */
23
+ check(connector, amount) {
24
+ if (!(amount > 0)) return null;
25
+ if (this.today() + amount > lim.daily) return `today's limit of ${usd(lim.daily)} (spent ${usd(this.today())})`;
26
+ if (this.thisMonth() + amount > lim.monthly) return `this month's limit of ${usd(lim.monthly)} (spent ${usd(this.thisMonth())})`;
27
+ const per = lim.perConnector?.[connector];
28
+ if (per != null && this.byConnector(connector) + amount > per) return `the ${usd(per)} monthly limit for ${connector} (spent ${usd(this.byConnector(connector))})`;
29
+ return null;
30
+ },
31
+ record(entry) { const all = read(); all.push({ at: now(), ...entry }); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(all.slice(-5000), null, 2)); return all.at(-1); },
32
+ entries() { return read(); },
33
+ };
34
+ }
package/src/chat.js ADDED
@@ -0,0 +1,288 @@
1
+ // @clarity-js/agent — the agent reached from where a team talks: Slack, Discord, Telegram, Linear.
2
+ //
3
+ // clarity keys set telegram-bot (or slack-bot + slack-signing, discord-bot, linear + linear-webhook)
4
+ // clarity agent chat allow telegram 123456789 who may talk to it: nobody, until somebody is named
5
+ // clarity agent chat stay and answer (--port 8787, --host 127.0.0.1, --mode ask)
6
+ //
7
+ // A message from somebody on the list is a task; the thread, channel or issue it came in is one conversation
8
+ // (a session, as the window and the editor's panel have). What the agent says comes back there; what it must ask
9
+ // comes as a question with Allow and Don't allow (buttons where the service has them, a reply of "allow" or
10
+ // "deny" where it has none).
11
+ //
12
+ // What keeps it the owner's: every request is checked against the service's own signature before a byte of it
13
+ // is read as a message (Slack: HMAC over the timestamp and body; Discord: Ed25519; Linear: HMAC over the body),
14
+ // and a stale one is refused; a person not on the list is told their id and nothing else happens; an answer to
15
+ // a question counts only from somebody on the list. Telegram needs no address open to the internet (the agent
16
+ // asks Telegram for messages). The others send to an address: the server listens on this computer alone unless
17
+ // told otherwise, and a tunnel or a reverse proxy the owner sets up brings their requests to it.
18
+
19
+ import crypto from 'node:crypto';
20
+ import http from 'node:http';
21
+ import { createSession } from './session.js';
22
+
23
+ /** The keys the services need, and the environment variable each may come from. */
24
+ export const CHAT_KEYS = { 'slack-bot': 'SLACK_BOT_TOKEN', 'slack-signing': 'SLACK_SIGNING_SECRET', 'discord-bot': 'DISCORD_BOT_TOKEN', 'telegram-bot': 'TELEGRAM_BOT_TOKEN', linear: 'LINEAR_API_KEY', 'linear-webhook': 'LINEAR_WEBHOOK_SECRET' };
25
+ export const CHAT_PLATFORMS = ['slack', 'discord', 'telegram', 'linear'];
26
+
27
+ const same = (a, b) => { const x = Buffer.from(String(a)), y = Buffer.from(String(b)); return x.length === y.length && crypto.timingSafeEqual(x, y); };
28
+ const hmac = (secret, text) => crypto.createHmac('sha256', secret).update(text).digest('hex');
29
+ const chunks = (text, most) => { const out = []; let s = String(text); while (s.length > most) { let at = s.lastIndexOf('\n', most); if (at < most / 2) at = most; out.push(s.slice(0, at)); s = s.slice(at).replace(/^\n/, ''); } if (s) out.push(s); return out; };
30
+ const fence = (text, lines = 30) => { const all = String(text).split('\n'); return '```\n' + all.slice(0, lines).join('\n').replace(/```/g, "'''") + (all.length > lines ? `\n… ${all.length - lines} more lines` : '') + '\n```'; };
31
+
32
+ // ── what the services sign ──
33
+ /** Slack: v0=HMAC-SHA256(signing secret, "v0:<timestamp>:<body>"), no older than five minutes. */
34
+ export function verifySlack({ secret, timestamp, signature, body, now = Date.now() }) {
35
+ if (!secret || !timestamp || !signature || Math.abs(now / 1000 - Number(timestamp)) > 300) return false;
36
+ return same('v0=' + hmac(secret, `v0:${timestamp}:${body}`), signature);
37
+ }
38
+ /** Discord: Ed25519 over the timestamp followed by the body, checked with the application's public key (hex). */
39
+ export function verifyDiscord({ publicKey, timestamp, signature, body }) {
40
+ try {
41
+ if (!/^[0-9a-f]{64}$/i.test(publicKey ?? '') || !/^[0-9a-f]{128}$/i.test(signature ?? '') || !timestamp) return false;
42
+ const key = crypto.createPublicKey({ key: Buffer.concat([Buffer.from('302a300506032b6570032100', 'hex'), Buffer.from(publicKey, 'hex')]), format: 'der', type: 'spki' });
43
+ return crypto.verify(null, Buffer.from(timestamp + body), key, Buffer.from(signature, 'hex'));
44
+ } catch { return false; }
45
+ }
46
+ /** Linear: HMAC-SHA256(webhook secret, body) as hex; the body's webhookTimestamp no more than a minute old. */
47
+ export function verifyLinear({ secret, signature, body, now = Date.now() }) {
48
+ if (!secret || !signature || !same(hmac(secret, body), signature)) return false;
49
+ try { return Math.abs(now - Number(JSON.parse(body).webhookTimestamp)) <= 60000; } catch { return false; }
50
+ }
51
+
52
+ // ── what a session shows, as a message of a chat ──
53
+ function messageOf(item) {
54
+ if (item.kind === 'text') return { text: item.text };
55
+ if (item.kind === 'ask' && item.answer === null) return { text: `May I: ${item.summary}${item.usd != null ? ` (about $${Number(item.usd).toFixed(2)})` : ''}${item.diff ? '\n' + fence(item.diff) : ''}`, ask: item.id };
56
+ if (item.kind === 'tool' && item.done && item.changes?.length) return { text: item.changes.map((f) => `± ${f.path} +${f.added} −${f.removed}`).join('\n') };
57
+ if (item.kind === 'tool' && item.done && item.error) return { text: `${item.summary} failed: ${String(item.output).split('\n')[0].slice(0, 200)}` };
58
+ if (item.kind === 'error') return { text: `It failed: ${item.text}` };
59
+ if (item.kind === 'undone') return { text: `Put back as before: ${item.files.join(', ')}` };
60
+ if (item.kind === 'undo-blocked') return { text: `Not undone: ${item.conflicts.join(', ')} changed since. Say "undo anyway" to lose that.` };
61
+ if (item.kind === 'done') return { text: item.stopped ? 'Stopped.' : item.unfinished ? 'The steps ran out. Say "go on" to continue.' : `Done in ${item.steps} step${item.steps === 1 ? '' : 's'}.` };
62
+ return null;
63
+ }
64
+
65
+ /**
66
+ * The hub: conversations by where they are held, and who may hold them.
67
+ * @param options root · adapters: { slack, discord, telegram, linear } (as the makers below give them) ·
68
+ * allow: { slack: [user ids], … } · mode ('ask') · make, options (as createSession) · most (8 conversations at once)
69
+ * → { hear({ platform, chat, user, text }), answer({ platform, chat, user, ask, value }), http(method, path, headers, body), sessions, close() }
70
+ */
71
+ export function createHub({ root = process.cwd(), adapters = {}, allow = {}, mode = 'ask', make = null, options = {}, most = 8, log = () => {} } = {}) {
72
+ const sessions = new Map(), told = new Set();
73
+ const may = (platform, user) => (allow[platform] ?? []).map(String).includes(String(user));
74
+ const send = (platform, chat, message) => Promise.resolve(adapters[platform].send(chat, message)).catch((e) => log(`${platform}: could not send (${e.message})`));
75
+ function sessionOf(platform, chat) {
76
+ const key = `${platform}:${chat}`;
77
+ let s = sessions.get(key);
78
+ if (s) return s;
79
+ if (sessions.size >= most) { const idle = [...sessions].find(([, v]) => !v.session.busy); if (!idle) return null; idle[1].session.dispose(); sessions.delete(idle[0]); }
80
+ const shown = new Set(), waiting = [];
81
+ const post = (m) => {
82
+ if (m.type === 'status' && m.problem && !shown.has('p:' + m.problem)) { shown.add('p:' + m.problem); send(platform, chat, { text: m.problem }); }
83
+ if (m.type !== 'item') return;
84
+ const item = m.item, out = messageOf(item), mark = item.id + ':' + (item.kind === 'tool' ? 'done' : item.kind === 'ask' ? String(item.answer) : '');
85
+ if (item.kind === 'ask') { const at = waiting.indexOf(item.id); if (item.answer === null && at < 0) waiting.push(item.id); else if (item.answer !== null && at >= 0) waiting.splice(at, 1); }
86
+ if (!out || shown.has(mark)) return;
87
+ shown.add(mark); send(platform, chat, out);
88
+ };
89
+ s = { session: createSession({ root, post, make, mode, options }), waiting, platform, chat };
90
+ sessions.set(key, s);
91
+ return s;
92
+ }
93
+ const hub = {
94
+ sessions,
95
+ /** Somebody said something. */
96
+ async hear({ platform, chat, user, text }) {
97
+ text = String(text ?? '').trim();
98
+ if (!text || !adapters[platform]) return 'ignored';
99
+ if (!may(platform, user)) {
100
+ if (!told.has(`${platform}:${user}`)) { told.add(`${platform}:${user}`); await send(platform, chat, { text: `You are not on this agent's list. Its owner can add you: clarity agent chat allow ${platform} ${user}` }); }
101
+ return 'refused';
102
+ }
103
+ const s = sessionOf(platform, chat);
104
+ if (!s) { await send(platform, chat, { text: 'The agent is busy in as many conversations as it holds at once. Try again when one ends.' }); return 'busy'; }
105
+ const word = text.toLowerCase();
106
+ if (/^(allow|yes|evet)$/.test(word) || /^(deny|no|hayır)$/.test(word)) { if (!s.waiting.length) return 'ignored'; await s.session.handle({ type: 'answer', id: s.waiting[0], value: /^(allow|yes|evet)$/.test(word) }); return 'answered'; }
107
+ if (word === 'stop') { await s.session.handle({ type: 'stop' }); return 'stopped'; }
108
+ if (word === 'new') { await s.session.handle({ type: 'new' }); await send(platform, chat, { text: 'A new conversation.' }); return 'new'; }
109
+ if (word === 'undo' || word === 'undo anyway') { const last = s.session.checkpoints.list().at(-1); if (!last) { await send(platform, chat, { text: 'Nothing to undo.' }); return 'ignored'; } await s.session.handle({ type: 'undo', id: last.id, force: word === 'undo anyway' }); return 'undone'; }
110
+ if (s.session.busy) { await send(platform, chat, { text: 'Still working on the last thing. Say "stop" to end it.' }); return 'busy'; }
111
+ s.session.handle({ type: 'send', text }).catch((e) => log(`${platform}: ${e.message}`));
112
+ return 'sent';
113
+ },
114
+ /** Somebody pressed Allow or Don't allow. Only somebody on the list is heard. */
115
+ async answer({ platform, chat, user, ask, value }) {
116
+ const s = sessions.get(`${platform}:${chat}`);
117
+ if (!s || !may(platform, user) || !s.waiting.includes(ask)) return false;
118
+ await s.session.handle({ type: 'answer', id: ask, value: !!value });
119
+ return true;
120
+ },
121
+ /** A request from a service. → { status, type, body } */
122
+ async http(method, path, headers, body) {
123
+ for (const a of Object.values(adapters)) { const route = a.routes?.[`${method} ${path}`]; if (route) return route({ headers, body, hub }); }
124
+ return { status: 404, type: 'text/plain', body: 'Not here.' };
125
+ },
126
+ async close() { for (const a of Object.values(adapters)) await a.stop?.(); for (const s of sessions.values()) await s.session.dispose(); sessions.clear(); },
127
+ };
128
+ return hub;
129
+ }
130
+
131
+ const json = (o, status = 200) => ({ status, type: 'application/json', body: JSON.stringify(o) });
132
+ const no = (status = 401) => ({ status, type: 'text/plain', body: 'No.' });
133
+ const call = async (fetchImpl, url, init, name) => { const r = await fetchImpl(url, init); if (!r.ok) throw new Error(`${name} answered ${r.status}`); return r.json().catch(() => ({})); };
134
+
135
+ /** Slack: the Events API and interactivity, answered in the thread. */
136
+ export function slack({ token, signingSecret, fetchImpl = fetch, now = () => Date.now() }) {
137
+ const seen = new Set();
138
+ const checked = (headers, body) => verifySlack({ secret: signingSecret, timestamp: headers['x-slack-request-timestamp'], signature: headers['x-slack-signature'], body, now: now() });
139
+ return {
140
+ id: 'slack',
141
+ async send(chat, { text, ask }) {
142
+ const [channel, thread_ts] = chat.split('|');
143
+ for (const part of chunks(text, 2900)) {
144
+ const blocks = ask ? [{ type: 'section', text: { type: 'mrkdwn', text: part } }, { type: 'actions', elements: [{ type: 'button', style: 'primary', text: { type: 'plain_text', text: 'Allow' }, action_id: 'clarity_allow', value: `${ask}:1` }, { type: 'button', style: 'danger', text: { type: 'plain_text', text: "Don't allow" }, action_id: 'clarity_deny', value: `${ask}:0` }] }] : undefined;
145
+ const r = await call(fetchImpl, 'https://slack.com/api/chat.postMessage', { method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json; charset=utf-8' }, body: JSON.stringify({ channel, thread_ts, text: part, ...(blocks ? { blocks } : {}) }) }, 'Slack');
146
+ if (r.ok === false) throw new Error(`Slack: ${r.error}`);
147
+ }
148
+ },
149
+ routes: {
150
+ 'POST /slack/events': async ({ headers, body, hub }) => {
151
+ if (!checked(headers, body)) return no();
152
+ const p = JSON.parse(body);
153
+ if (p.type === 'url_verification') return json({ challenge: p.challenge });
154
+ const e = p.event ?? {};
155
+ // a mention in a channel, or a direct message; not the bot's own, not an edit; a retry of one already heard is dropped
156
+ if (p.type === 'event_callback' && (e.type === 'app_mention' || (e.type === 'message' && e.channel_type === 'im')) && !e.bot_id && !e.subtype && !seen.has(p.event_id)) {
157
+ seen.add(p.event_id); if (seen.size > 2000) seen.delete(seen.values().next().value);
158
+ hub.hear({ platform: 'slack', chat: `${e.channel}|${e.thread_ts ?? e.ts}`, user: e.user, text: String(e.text ?? '').replace(/^\s*<@[A-Z0-9]+>\s*/, '') });
159
+ }
160
+ return { status: 200, type: 'text/plain', body: '' };
161
+ },
162
+ 'POST /slack/actions': async ({ headers, body, hub }) => {
163
+ if (!checked(headers, body)) return no();
164
+ const p = JSON.parse(new URLSearchParams(body).get('payload') ?? '{}'), action = p.actions?.[0];
165
+ if (p.type === 'block_actions' && /^clarity_(allow|deny)$/.test(action?.action_id ?? '')) { const [ask, v] = String(action.value).split(':'); hub.answer({ platform: 'slack', chat: `${p.channel?.id}|${p.message?.thread_ts ?? p.message?.ts}`, user: p.user?.id, ask, value: v === '1' }); }
166
+ return { status: 200, type: 'text/plain', body: '' };
167
+ },
168
+ },
169
+ };
170
+ }
171
+
172
+ /** Discord: the /clarity command and its buttons, by the interactions endpoint; the rest is said in the channel. */
173
+ export function discord({ token, publicKey, appId, fetchImpl = fetch }) {
174
+ const api = (path, body, method = 'POST') => call(fetchImpl, `https://discord.com/api/v10${path}`, { method, headers: { authorization: `Bot ${token}`, 'content-type': 'application/json' }, body: JSON.stringify(body) }, 'Discord');
175
+ return {
176
+ id: 'discord',
177
+ /** Tell Discord of the command (once): /clarity task:<what to do>. */
178
+ register: () => api(`/applications/${appId}/commands`, [{ name: 'clarity', description: 'Ask Clarity Agent to do something in the project', options: [{ type: 3, name: 'task', description: 'What to do (or: stop, new, undo, allow, deny)', required: true }] }], 'PUT'),
179
+ async send(chat, { text, ask }) {
180
+ const parts = chunks(text, 1900);
181
+ for (const [i, part] of parts.entries()) await api(`/channels/${chat}/messages`, { content: part, allowed_mentions: { parse: [] }, ...(ask && i === parts.length - 1 ? { components: [{ type: 1, components: [{ type: 2, style: 3, label: 'Allow', custom_id: `clarity:${ask}:1` }, { type: 2, style: 4, label: "Don't allow", custom_id: `clarity:${ask}:0` }] }] } : {}) });
182
+ },
183
+ routes: {
184
+ 'POST /discord/interactions': async ({ headers, body, hub }) => {
185
+ if (!verifyDiscord({ publicKey, timestamp: headers['x-signature-timestamp'], signature: headers['x-signature-ed25519'], body })) return no();
186
+ const p = JSON.parse(body), user = p.member?.user?.id ?? p.user?.id;
187
+ if (p.type === 1) return json({ type: 1 }); // Discord checks the address: PING → PONG
188
+ if (p.type === 2 && p.data?.name === 'clarity') {
189
+ const text = String(p.data.options?.find((o) => o.name === 'task')?.value ?? '');
190
+ const heard = await hub.hear({ platform: 'discord', chat: p.channel_id, user, text });
191
+ return json({ type: 4, data: { content: heard === 'refused' ? 'You are not on this agent\'s list.' : `> ${text.slice(0, 300)}`, allowed_mentions: { parse: [] }, ...(heard === 'refused' ? { flags: 64 } : {}) } });
192
+ }
193
+ if (p.type === 3 && /^clarity:/.test(p.data?.custom_id ?? '')) {
194
+ const [, ask, v] = p.data.custom_id.split(':'), ok = await hub.answer({ platform: 'discord', chat: p.channel_id, user, ask, value: v === '1' });
195
+ return ok ? json({ type: 7, data: { content: `${p.message?.content ?? ''}\n${v === '1' ? 'Allowed' : 'Not allowed'}.`.slice(0, 1990), components: [] } }) : json({ type: 4, data: { content: 'That is not yours to answer, or it was answered already.', flags: 64 } });
196
+ }
197
+ return json({ type: 4, data: { content: 'Not understood.', flags: 64 } });
198
+ },
199
+ },
200
+ };
201
+ }
202
+
203
+ /** Telegram: the bot asks for its messages (long polling), so no address has to be open to the internet. */
204
+ export function telegram({ token, fetchImpl = fetch, wait = 25, log = () => {} }) {
205
+ const api = (method, body, signal) => call(fetchImpl, `https://api.telegram.org/bot${token}/${method}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal }, 'Telegram');
206
+ let stop = null, running = null;
207
+ return {
208
+ id: 'telegram',
209
+ async send(chat, { text, ask }) {
210
+ const parts = chunks(text, 4000);
211
+ for (const [i, part] of parts.entries()) await api('sendMessage', { chat_id: chat, text: part, ...(ask && i === parts.length - 1 ? { reply_markup: { inline_keyboard: [[{ text: 'Allow', callback_data: `clarity:${ask}:1` }, { text: "Don't allow", callback_data: `clarity:${ask}:0` }]] } } : {}) });
212
+ },
213
+ /** One round: the updates since `offset`, each given to the hub. → the next offset */
214
+ async poll(hub, offset = 0, signal) {
215
+ const r = await api('getUpdates', { offset, timeout: wait, allowed_updates: ['message', 'callback_query'] }, signal);
216
+ for (const u of r.result ?? []) {
217
+ offset = Math.max(offset, u.update_id + 1);
218
+ if (u.message?.text) hub.hear({ platform: 'telegram', chat: String(u.message.chat.id), user: String(u.message.from?.id), text: u.message.text.replace(/^\/(clarity|start)(@\w+)?\s*/, '') });
219
+ else if (u.callback_query && /^clarity:/.test(u.callback_query.data ?? '')) {
220
+ const [, ask, v] = u.callback_query.data.split(':'), ok = await hub.answer({ platform: 'telegram', chat: String(u.callback_query.message?.chat.id), user: String(u.callback_query.from?.id), ask, value: v === '1' });
221
+ await api('answerCallbackQuery', { callback_query_id: u.callback_query.id, text: ok ? (v === '1' ? 'Allowed' : 'Not allowed') : 'Not yours to answer' }).catch(() => {});
222
+ }
223
+ }
224
+ return offset;
225
+ },
226
+ start(hub) {
227
+ stop = new AbortController();
228
+ running = (async () => { let offset = 0; while (!stop.signal.aborted) { try { offset = await this.poll(hub, offset, stop.signal); } catch (e) { if (stop.signal.aborted) break; log(`telegram: ${e.message}`); await new Promise((r) => setTimeout(r, 5000)); } } })();
229
+ },
230
+ async stop() { stop?.abort(); await running?.catch(() => {}); },
231
+ };
232
+ }
233
+
234
+ /** Linear: a comment on an issue that starts with @clarity (or /clarity) is a task; the agent answers in comments. */
235
+ export function linear({ key, webhookSecret, fetchImpl = fetch, now = () => Date.now() }) {
236
+ const mine = new Set(); // comments the agent wrote: not heard as tasks
237
+ return {
238
+ id: 'linear',
239
+ async send(chat, { text, ask }) {
240
+ const body = ask ? `${text}\n\nReply \`allow\` or \`deny\`.` : text;
241
+ const r = await call(fetchImpl, 'https://api.linear.app/graphql', { method: 'POST', headers: { authorization: key, 'content-type': 'application/json' }, body: JSON.stringify({ query: 'mutation($issueId: String!, $body: String!) { commentCreate(input: { issueId: $issueId, body: $body }) { success comment { id } } }', variables: { issueId: chat, body } }) }, 'Linear');
242
+ if (r.errors?.length) throw new Error(`Linear: ${r.errors[0].message}`);
243
+ const id = r.data?.commentCreate?.comment?.id; if (id) { mine.add(id); if (mine.size > 2000) mine.delete(mine.values().next().value); }
244
+ },
245
+ routes: {
246
+ 'POST /linear/webhook': async ({ headers, body, hub }) => {
247
+ if (!verifyLinear({ secret: webhookSecret, signature: headers['linear-signature'], body, now: now() })) return no();
248
+ const p = JSON.parse(body), d = p.data ?? {};
249
+ if (p.type === 'Comment' && p.action === 'create' && d.issueId && !mine.has(d.id)) {
250
+ const said = String(d.body ?? '').trim(), task = /^[@/]clarity\b[\s:,]*/i.test(said) ? said.replace(/^[@/]clarity\b[\s:,]*/i, '') : /^(allow|deny|stop|undo|undo anyway)$/i.test(said) ? said : null;
251
+ if (task) hub.hear({ platform: 'linear', chat: d.issueId, user: d.userId ?? d.user?.id, text: task });
252
+ }
253
+ return { status: 200, type: 'text/plain', body: '' };
254
+ },
255
+ },
256
+ };
257
+ }
258
+
259
+ /** The adapters there are keys for. keys: the key store · config: the project's "chat" settings ({ discord: { appId, publicKey } }) */
260
+ export function chatAdapters({ keys, config = {}, fetchImpl = fetch, log = () => {} }) {
261
+ const out = {}, k = (id) => keys.get(id);
262
+ if (k('slack-bot') && k('slack-signing')) out.slack = slack({ token: k('slack-bot'), signingSecret: k('slack-signing'), fetchImpl });
263
+ if (k('discord-bot') && config.discord?.publicKey) out.discord = discord({ token: k('discord-bot'), publicKey: config.discord.publicKey, appId: config.discord.appId, fetchImpl });
264
+ if (k('telegram-bot')) out.telegram = telegram({ token: k('telegram-bot'), fetchImpl, log });
265
+ if (k('linear') && k('linear-webhook')) out.linear = linear({ key: k('linear'), webhookSecret: k('linear-webhook'), fetchImpl });
266
+ return out;
267
+ }
268
+
269
+ /**
270
+ * Stay and answer. → { hub, port, url, close() }
271
+ * @param options as createHub, and port (8787), host ('127.0.0.1': this computer alone)
272
+ */
273
+ export async function serveChat({ port = 8787, host = '127.0.0.1', ...rest } = {}) {
274
+ const hub = createHub(rest), needsServer = Object.values(rest.adapters ?? {}).some((a) => a.routes);
275
+ let server = null;
276
+ if (needsServer) {
277
+ server = http.createServer(async (req, res) => {
278
+ try {
279
+ let body = ''; for await (const chunk of req) { body += chunk; if (body.length > 2e6) { res.writeHead(413).end(); return; } }
280
+ const r = await hub.http(req.method, new URL(req.url, 'http://x').pathname, req.headers, body);
281
+ res.writeHead(r.status, { 'content-type': r.type, 'cache-control': 'no-store' }); res.end(r.body);
282
+ } catch { try { res.writeHead(400).end(); } catch { /* answered already */ } }
283
+ });
284
+ await new Promise((done, fail) => { server.once('error', fail); server.listen(port, host, done); });
285
+ }
286
+ for (const a of Object.values(rest.adapters ?? {})) a.start?.(hub);
287
+ return { hub, port: server?.address().port ?? null, url: server ? `http://${host}:${server.address().port}` : null, async close() { await hub.close(); if (server) await new Promise((done) => { server.closeAllConnections?.(); server.close(() => done()); }); } };
288
+ }
@@ -0,0 +1,126 @@
1
+ // @clarity-js/agent — checkpoints: what a step changed, and the way back.
2
+ //
3
+ // A tool that is about to write a file says so first (ctx.touch(path)); what the file held then is kept. When the
4
+ // step ends, what it held is compared with what it holds now: that is the step's checkpoint — the files made,
5
+ // changed or removed, each with its diff. undo(id) puts every file back as it was before that step, undoing the
6
+ // steps after it too (they were built on it). A file somebody else changed since is not overwritten unless asked.
7
+ //
8
+ // What a command does (npm install, a formatter) is not kept: nobody can know beforehand which files it will
9
+ // change. Those files are listed with the step ("others"), so it is seen that they changed; they are not undone.
10
+ //
11
+ // const cps = createCheckpoints({ root })
12
+ // const step = cps.begin('write src/a.js'); step.touch(file); …write…; const cp = step.end()
13
+ // cps.undo(cp.id) → { done, restored, conflicts, skipped }
14
+
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import crypto from 'node:crypto';
18
+ import { lineDiff } from './diff.js';
19
+
20
+ const SKIP = new Set(['node_modules', '.git', 'dist', '.clarity', '.next', 'build', '.cache']);
21
+ const hash = (buf) => (buf == null ? null : crypto.createHash('sha1').update(buf).digest('hex'));
22
+ const read = (abs) => { try { return fs.statSync(abs).isFile() ? fs.readFileSync(abs) : null; } catch { return null; } };
23
+ const asText = (buf) => (buf == null ? null : buf.toString('utf8'));
24
+
25
+ // every file of the project with its size and time, for seeing what a command touched (null: too many to look at)
26
+ function stats(root, most = 8000) {
27
+ const out = new Map(), walk = (dir) => {
28
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
29
+ if (SKIP.has(e.name)) continue;
30
+ const p = path.join(dir, e.name);
31
+ if (e.isDirectory()) { walk(p); if (out.size > most) return; }
32
+ else if (e.isFile()) { const st = fs.statSync(p); out.set(path.relative(root, p).split(path.sep).join('/'), `${st.size}:${st.mtimeMs}`); if (out.size > most) return; }
33
+ }
34
+ };
35
+ try { walk(root); } catch { return null; }
36
+ return out.size > most ? null : out;
37
+ }
38
+
39
+ /**
40
+ * @param options root · dir (where what files held is kept: .clarity/agent/checkpoints/<time> in the project) ·
41
+ * most (5 MB: a larger file's old content is not kept, and it is not undone)
42
+ * → { begin(label, { watch }), list(), get(id), before(id, path), undo(id, { force }), clear() }
43
+ */
44
+ export function createCheckpoints({ root = process.cwd(), dir = null, most = 5e6, now = () => Date.now() } = {}) {
45
+ root = fs.realpathSync(root);
46
+ const store = dir ?? path.join(root, '.clarity', 'agent', 'checkpoints', new Date(now()).toISOString().replace(/[:.]/g, '-'));
47
+ const all = []; let n = 0;
48
+ // where a path really is (through links, as far as it exists): a project reached by a link (macOS's /var, a linked
49
+ // folder) is the same project
50
+ const realOf = (abs) => { let p = path.resolve(abs); const tail = []; for (;;) { try { return path.join(fs.realpathSync(p), ...tail); } catch { tail.unshift(path.basename(p)); const up = path.dirname(p); if (up === p) return path.resolve(abs); p = up; } } };
51
+ const relOf = (abs) => path.relative(root, realOf(abs)).split(path.sep).join('/');
52
+ const kept = (id, i) => path.join(store, String(id), String(i));
53
+ return {
54
+ root,
55
+ /** A step that may change files. watch: also see which other files changed meanwhile (a command). */
56
+ begin(label = '', { watch = false } = {}) {
57
+ const was = new Map(), seen = watch ? stats(root) : null;
58
+ return {
59
+ /** Called before a file is written, made or removed. */
60
+ touch(abs) {
61
+ const rel = relOf(abs);
62
+ if (was.has(rel) || rel.startsWith('..')) return;
63
+ let buf = null, had = false, keep = true;
64
+ try { const st = fs.statSync(abs); had = st.isFile(); if (had) { if (st.size > most) keep = false; else buf = fs.readFileSync(abs); } } catch { /* not there */ }
65
+ was.set(rel, { had, buf, keep });
66
+ },
67
+ /** The step is over. → its checkpoint { id, label, at, files: [{ path, status, added, removed, diff, kept }], others } or null when nothing changed. */
68
+ end() {
69
+ const files = [], keep = [];
70
+ for (const [rel, w] of was) {
71
+ const abs = path.join(root, rel), after = read(abs);
72
+ if (w.had && after && w.keep && w.buf.equals(after)) continue;
73
+ if (!w.had && !after) continue;
74
+ const status = !w.had ? 'made' : !after ? 'removed' : 'changed';
75
+ const d = w.keep ? lineDiff(asText(w.buf), asText(after), { path: rel }) : { text: `${rel} is too large to keep: it will not be undone`, added: 0, removed: 0 };
76
+ files.push({ path: rel, status, added: d.added, removed: d.removed, diff: d.text, kept: w.keep, had: w.had, after: hash(after) });
77
+ keep.push(w);
78
+ }
79
+ let others = [];
80
+ if (seen) { const nowSeen = stats(root); if (nowSeen) { for (const [p, v] of nowSeen) if (seen.get(p) !== v && !was.has(p)) others.push(p); for (const p of seen.keys()) if (!nowSeen.has(p) && !was.has(p)) others.push(p); others.sort(); } }
81
+ if (!files.length) return others.length ? { id: null, label, at: now(), files: [], others } : null;
82
+ const id = ++n;
83
+ fs.mkdirSync(path.join(store, String(id)), { recursive: true });
84
+ keep.forEach((w, i) => { if (w.had && w.keep) fs.writeFileSync(kept(id, i), w.buf); });
85
+ const cp = { id, label, at: now(), files, others, undone: false };
86
+ all.push(cp);
87
+ return cp;
88
+ },
89
+ };
90
+ },
91
+ list: () => all.filter((c) => !c.undone).map((c) => ({ ...c, files: c.files.map((f) => ({ ...f })) })),
92
+ get: (id) => all.find((c) => c.id === id) ?? null,
93
+ /** What a file held before a step (a Buffer; null: it was not there, or was not kept). */
94
+ before(id, rel) {
95
+ const cp = all.find((c) => c.id === id), i = cp ? cp.files.findIndex((f) => f.path === rel) : -1;
96
+ if (i < 0 || !cp.files[i].had || !cp.files[i].kept) return null;
97
+ try { return fs.readFileSync(kept(id, i)); } catch { return null; }
98
+ },
99
+ /**
100
+ * Put the files back as they were before step `id`: that step and every later one are undone, the latest first.
101
+ * A file changed by somebody else since the agent last wrote it is a conflict: nothing is undone unless `force`.
102
+ * → { done, restored: [paths], conflicts: [paths], skipped: [paths too large to have been kept], ids }
103
+ */
104
+ undo(id, { force = false } = {}) {
105
+ const todo = all.filter((c) => c.id >= id && !c.undone).reverse();
106
+ if (!todo.length) return { done: false, restored: [], conflicts: [], skipped: [], ids: [] };
107
+ // what the agent last left in each file, against what is there now
108
+ const last = new Map(); for (const c of [...todo].reverse()) for (const f of c.files) last.set(f.path, f.after);
109
+ const conflicts = [...last].filter(([rel, h]) => hash(read(path.join(root, rel))) !== h).map(([rel]) => rel).sort();
110
+ if (conflicts.length && !force) return { done: false, restored: [], conflicts, skipped: [], ids: [] };
111
+ const restored = new Set(), skipped = new Set();
112
+ for (const c of todo) {
113
+ c.files.forEach((f, i) => {
114
+ const abs = path.join(root, f.path);
115
+ if (!f.kept) { skipped.add(f.path); return; }
116
+ if (!f.had) fs.rmSync(abs, { force: true });
117
+ else { fs.mkdirSync(path.dirname(abs), { recursive: true }); fs.writeFileSync(abs, fs.readFileSync(kept(c.id, i))); }
118
+ restored.add(f.path);
119
+ });
120
+ c.undone = true;
121
+ }
122
+ return { done: true, restored: [...restored].sort(), conflicts, skipped: [...skipped].sort(), ids: todo.map((c) => c.id) };
123
+ },
124
+ clear() { all.length = 0; try { fs.rmSync(store, { recursive: true, force: true }); } catch { /* nothing kept */ } },
125
+ };
126
+ }