@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/tools.js ADDED
@@ -0,0 +1,139 @@
1
+ // @clarity-js/agent — what the agent can do, and what it must ask first. Each tool says how risky it is:
2
+ //
3
+ // read reads the project never asked
4
+ // run runs the project's own code (a render) asked, unless the user allowed edits
5
+ // write changes a file in the project asked, unless the user allowed edits
6
+ // exec runs a command asked, unless the command was allowed
7
+ // spend costs money (a paid generation) asked with its price, always
8
+ // publish goes out of this computer (deploy, post) asked, always
9
+ //
10
+ // Nothing reads or writes outside the project's folder: a path that leaves it, by .. or a link, is refused.
11
+
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { spawn } from 'node:child_process';
15
+
16
+ const WINDOWS = process.platform === 'win32';
17
+ import { lineDiff } from './diff.js';
18
+
19
+ const obj = (properties, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
20
+ const str = (description) => ({ type: 'string', description });
21
+
22
+ /** A path inside root, or an error. Links are followed and must land inside too. */
23
+ export function inside(root, given = '.') {
24
+ const base = fs.realpathSync(root), full = path.resolve(base, String(given));
25
+ let real = full;
26
+ try { real = fs.realpathSync(full); } catch { // not there yet: its nearest existing parent decides
27
+ let p = path.dirname(full); while (!fs.existsSync(p) && p !== path.dirname(p)) p = path.dirname(p);
28
+ real = path.join(fs.realpathSync(p), path.relative(p, full));
29
+ }
30
+ if (real !== base && !real.startsWith(base + path.sep)) throw new Error(`${given} is outside the project (${base}); the agent works only inside it.`);
31
+ return real;
32
+ }
33
+ const rel = (root, p) => (path.relative(fs.realpathSync(root), p) || '.').split(path.sep).join('/'); // src/App.clarity, on Windows too: it is read by a model, and written into code
34
+ // files the agent should not read without asking: secrets
35
+ const SECRET = /(^|[\\/])(\.env(\..*)?|id_[rd]sa.*|.*\.pem|keys\.json|\.npmrc|\.netrc)$/i;
36
+ const SKIP = new Set(['node_modules', '.git', 'dist', '.clarity', '.next', 'build', '.cache']);
37
+
38
+ function walk(dir, depth, out, root, limit = 2000) {
39
+ if (out.length >= limit) return;
40
+ for (const e of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
41
+ if (SKIP.has(e.name)) continue;
42
+ const p = path.join(dir, e.name);
43
+ out.push(rel(root, p) + (e.isDirectory() ? '/' : ''));
44
+ if (out.length >= limit) return;
45
+ if (e.isDirectory() && depth > 1) walk(p, depth - 1, out, root, limit);
46
+ }
47
+ }
48
+ const globRe = (g) => new RegExp('^' + g.split('**').map((s) => s.split('*').map((t) => t.replace(/[.+^${}()|[\]\\?]/g, '\\$&')).join('[^/]*')).join('.*') + '$');
49
+
50
+ /** The file tools, the search, and the command. */
51
+ export const CORE_TOOLS = [
52
+ { name: 'list_files', risk: 'read', description: 'List the files and folders of the project (or a folder of it), as paths from its root. node_modules, .git and build folders are left out.', inputSchema: obj({ path: str('A folder of the project (its root).'), depth: { type: 'integer', minimum: 1, maximum: 8, description: 'How deep (3).' } }),
53
+ run({ path: p = '.', depth = 3 }, { root }) { const out = []; walk(inside(root, p), depth, out, root); return { text: out.join('\n') || '(empty)', data: { files: out } }; } },
54
+ { name: 'read_file', risk: 'read', description: 'Read a text file of the project, with line numbers. For a long file give offset and limit (lines).', inputSchema: obj({ path: str('The file, from the project\'s root.'), offset: { type: 'integer', minimum: 1 }, limit: { type: 'integer', minimum: 1, maximum: 4000 } }, ['path']),
55
+ async run({ path: p, offset = 1, limit = 1200 }, ctx) {
56
+ const f = inside(ctx.root, p);
57
+ if (SECRET.test(f) && !(await ctx.ask?.({ tool: 'read_file', summary: `read ${rel(ctx.root, f)}, which may hold secrets` }))) return { text: 'Not read: the user did not allow reading a file that may hold secrets.', error: true };
58
+ const lines = fs.readFileSync(f, 'utf8').split('\n'), part = lines.slice(offset - 1, offset - 1 + limit);
59
+ return { text: part.map((l, i) => `${String(offset + i).padStart(5)} ${l}`).join('\n') + (offset - 1 + limit < lines.length ? `\n… ${lines.length - (offset - 1 + limit)} more lines (offset ${offset + limit})` : '') };
60
+ } },
61
+ { name: 'write_file', risk: 'write', description: 'Write a whole file (made if it is not there; its folders too). For a small change to a file that is there, use edit_file.', inputSchema: obj({ path: str('The file, from the project\'s root.'), content: str('Everything the file holds.') }, ['path', 'content']),
62
+ summary: ({ path: p, content }) => `write ${p} (${String(content ?? '').split('\n').length} lines)`,
63
+ // what it would change, for the question that is asked first
64
+ preview({ path: p, content }, { root }) { const f = inside(root, p), was = fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : null; return { path: rel(root, f), ...lineDiff(was, String(content ?? ''), { path: rel(root, f) }) }; },
65
+ run({ path: p, content }, { root, touch }) { const f = inside(root, p), had = fs.existsSync(f); touch?.(f); fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, content); return { text: `${had ? 'Wrote' : 'Made'} ${rel(root, f)} (${content.split('\n').length} lines).`, data: { path: rel(root, f), made: !had } }; } },
66
+ { name: 'edit_file', risk: 'write', description: 'Change part of a file: replace old (which must be found exactly once, unless all is true) with new.', inputSchema: obj({ path: str('The file.'), old: str('The text there now, exactly.'), new: str('What to put instead.'), all: { type: 'boolean', description: 'Replace every place it is found.' } }, ['path', 'old', 'new']),
67
+ summary: ({ path: p }) => `edit ${p}`,
68
+ preview({ path: p, old, new: neu, all = false }, { root }) {
69
+ const f = inside(root, p), text = fs.readFileSync(f, 'utf8'), n = text.split(old).length - 1;
70
+ if (n === 0 || (n > 1 && !all)) return null;
71
+ return { path: rel(root, f), ...lineDiff(text, all ? text.split(old).join(neu) : text.replace(old, () => neu), { path: rel(root, f) }) };
72
+ },
73
+ run({ path: p, old, new: neu, all = false }, { root, touch }) {
74
+ const f = inside(root, p), text = fs.readFileSync(f, 'utf8'), n = text.split(old).length - 1;
75
+ if (n === 0) return { text: `Not changed: that text is not in ${p}. Read the file and quote it exactly.`, error: true };
76
+ if (n > 1 && !all) return { text: `Not changed: that text is in ${p} ${n} times. Quote more around it, or set all.`, error: true };
77
+ touch?.(f);
78
+ fs.writeFileSync(f, all ? text.split(old).join(neu) : text.replace(old, () => neu));
79
+ return { text: `Changed ${p} (${all ? n : 1} place${(all ? n : 1) === 1 ? '' : 's'}).` };
80
+ } },
81
+ { name: 'search', risk: 'read', description: 'Find text in the project\'s files (a regular expression): each line with its file and number.', inputSchema: obj({ pattern: str('A regular expression.'), path: str('A folder or file to look in (the whole project).'), glob: str('Only files whose path matches, as *.clarity or src/**/*.js.'), limit: { type: 'integer', minimum: 1, maximum: 500 } }, ['pattern']),
82
+ run({ pattern, path: p = '.', glob, limit = 100 }, { root }) {
83
+ const re = new RegExp(pattern, 'i'), g = glob ? globRe(glob) : null, out = [], start = inside(root, p);
84
+ const visit = (f) => {
85
+ if (out.length >= limit) return;
86
+ const st = fs.statSync(f);
87
+ if (st.isDirectory()) { for (const e of fs.readdirSync(f)) if (!SKIP.has(e)) visit(path.join(f, e)); return; }
88
+ const r = rel(root, f);
89
+ if (g && !g.test(r) && !g.test(path.basename(r))) return;
90
+ if (st.size > 2e6 || SECRET.test(f)) return;
91
+ const text = fs.readFileSync(f, 'utf8'); if (text.includes('\u0000')) return;
92
+ text.split('\n').forEach((l, i) => { if (out.length < limit && re.test(l)) out.push(`${r}:${i + 1}: ${l.trim().slice(0, 200)}`); });
93
+ };
94
+ visit(start);
95
+ return { text: out.join('\n') || 'Nothing found.', data: { matches: out.length } };
96
+ } },
97
+ { name: 'run_command', risk: 'exec', description: `Run a shell command in the project's folder (npm test, npx clarity check, git status …): its output and exit code. The shell is ${WINDOWS ? 'cmd.exe (Windows)' : 'sh'}. It is asked first unless the user allowed it.`, inputSchema: obj({ command: str('The command.'), timeout: { type: 'integer', minimum: 1, maximum: 1800, description: 'Seconds (120).' } }, ['command']),
98
+ summary: ({ command }) => `run: ${command}`,
99
+ run({ command, timeout = 120 }, { root, signal }) {
100
+ return new Promise((resolve) => {
101
+ // (cmd is given the line as it is written: Node's own quoting of an argument is not the quoting cmd reads)
102
+ const child = WINDOWS ? spawn('cmd', ['/d', '/s', '/c', `"${command}"`], { cwd: fs.realpathSync(root), env: { ...process.env, CI: '1', FORCE_COLOR: '0' }, windowsVerbatimArguments: true, windowsHide: true })
103
+ : spawn('sh', ['-c', command], { cwd: fs.realpathSync(root), env: { ...process.env, CI: '1', FORCE_COLOR: '0' } });
104
+ let out = ''; const add = (d) => { out += d; if (out.length > 200000) out = out.slice(-200000); };
105
+ child.stdout.on('data', add); child.stderr.on('data', add);
106
+ // (on Windows ending cmd leaves what it started running: the whole tree is ended)
107
+ const end = () => { if (WINDOWS && child.pid) spawn('taskkill', ['/pid', String(child.pid), '/t', '/f'], { windowsHide: true, stdio: 'ignore' }).on('error', () => child.kill()); else child.kill('SIGTERM'); };
108
+ const t = setTimeout(end, timeout * 1000), stop = end;
109
+ signal?.addEventListener?.('abort', stop, { once: true });
110
+ child.on('close', (code, sig) => { clearTimeout(t); signal?.removeEventListener?.('abort', stop); out = out.replace(/\r\n/g, '\n'); const tail = out.length > 20000 ? '…\n' + out.slice(-20000) : out; resolve({ text: `${tail.trimEnd()}\n[exit ${code ?? sig}]`, error: code !== 0, data: { code } }); });
111
+ child.on('error', (e) => { clearTimeout(t); resolve({ text: e.message, error: true }); });
112
+ });
113
+ } },
114
+ ];
115
+
116
+ /**
117
+ * When to ask. mode: 'ask' (writes and commands are asked), 'edits' (writes allowed, commands asked), 'auto'
118
+ * (writes and the allowed commands run; spend and publish are still asked). allow: command prefixes that run
119
+ * without asking ('npm test', 'npx clarity check'). Money and anything that leaves the computer are always asked.
120
+ */
121
+ export function policy({ mode = 'ask', allow = [] } = {}) {
122
+ const allowed = new Set(allow), safe = ['git status', 'git diff', 'git log', 'ls', 'npx clarity check', 'npx clarity lint', 'npm test', 'npm run test', 'node --check'];
123
+ return {
124
+ mode,
125
+ allowCommand(prefix) { allowed.add(prefix); },
126
+ decide(tool, args) {
127
+ if (tool.risk === 'read') return 'allow';
128
+ if (tool.risk === 'spend' || tool.risk === 'publish') return 'ask';
129
+ if (tool.risk === 'write' || tool.risk === 'run') return mode === 'ask' ? 'ask' : 'allow';
130
+ if (tool.risk === 'exec') {
131
+ const c = String(args?.command ?? '').trim();
132
+ if (/[;&|`$<>]/.test(c.replace(/2>&1/g, ''))) return 'ask'; // chains and redirections are always looked at
133
+ if ([...allowed, ...(mode === 'ask' ? [] : safe)].some((p) => c === p || c.startsWith(p + ' '))) return 'allow';
134
+ return 'ask';
135
+ }
136
+ return 'ask';
137
+ },
138
+ };
139
+ }
@@ -0,0 +1,191 @@
1
+ // The agent's panel: the conversation as a page. One component, shown by the editor's side panel and by the
2
+ // window on the desktop; `bridge` is how it talks to the session behind it:
3
+ // bridge.post(message) what the person did (send, answer, stop, new, model, mode, undo, hello)
4
+ // bridge.can what the shell can do itself: { editorDiff } (an editor shows a change in its own diff view)
5
+ // bridge.listen(fn) → stop what to show (state, item, status; from a shell with no pickers of its own also
6
+ // prompt { id, what, title, fields } → answered with filled { what, values }, and notice { text })
7
+
8
+ component Panel(bridge) {
9
+ state items = []
10
+ state busy = false
11
+ state model = null
12
+ state mode = 'ask'
13
+ state problem = null
14
+ state name = ''
15
+ state usage = { input: 0, output: 0 }
16
+ state spent = null
17
+ state draft = ''
18
+ state open = {}
19
+ state asking = null
20
+ state filled = {}
21
+ let notes = 0
22
+
23
+ const MODES = [['ask', 'Ask first'], ['edits', 'Edit files'], ['auto', 'Edit and run']]
24
+ let end = null
25
+ let stop = null
26
+
27
+ // what came from the session
28
+ function take(m) {
29
+ if (m.type === 'state') { items = m.items; name = m.name ?? '' }
30
+ if (m.type === 'item') {
31
+ const at = items.findIndex((i) => i.id === m.item.id)
32
+ items = at < 0 ? [...items, m.item] : items.map((i) => (i.id === m.item.id ? m.item : i))
33
+ queueMicrotask(() => end?.scrollIntoView?.({ block: 'end' }))
34
+ }
35
+ if (m.type === 'prompt') { asking = m; filled = Object.fromEntries(m.fields.map((f) => [f.name, f.value ?? ''])) }
36
+ if (m.type === 'notice') items = [...items, { id: 'note' + (++notes), kind: 'note', text: m.text }]
37
+ if (m.type === 'state' || m.type === 'status') {
38
+ busy = m.busy; model = m.model; mode = m.mode; problem = m.problem; usage = m.usage ?? usage; spent = m.spent ?? null
39
+ }
40
+ }
41
+ onMount { stop = bridge.listen(take); bridge.post({ type: 'hello' }) }
42
+ onCleanup { stop?.() }
43
+
44
+ action send() {
45
+ const text = draft.trim()
46
+ if (!text || busy) return
47
+ bridge.post({ type: 'send', text })
48
+ draft = ''
49
+ }
50
+ action answer(id, value) { bridge.post({ type: 'answer', id, value }) }
51
+ action halt() { bridge.post({ type: 'stop' }) }
52
+ action fresh() { bridge.post({ type: 'new' }) }
53
+ action setMode(next) { bridge.post({ type: 'mode', mode: next }) }
54
+ action pickModel() { bridge.post({ type: 'pick-model' }) }
55
+ action giveKey() { bridge.post({ type: 'give-key' }) }
56
+ action toggle(id) { open = { ...open, [id]: !open[id] } }
57
+ action undo(id, force) { bridge.post({ type: 'undo', id, force }) }
58
+ action openDiff(checkpoint, file) { bridge.post({ type: 'open-diff', checkpoint, path: file }) }
59
+ const editorDiff = bridge.can?.editorDiff === true
60
+ // a diff as lines to draw: what was added, taken away, and where
61
+ const rows = (diff) => String(diff ?? '').split('\n').filter((text) => !text.startsWith('--- ') && !text.startsWith('+++ ')).map((text, n) => ({ n, text: text || ' ', kind: text.startsWith('@@') ? 'ca-hunk' : text[0] === '+' ? 'ca-add' : text[0] === '-' ? 'ca-del' : 'ca-same' }))
62
+ const listed = (paths) => paths.slice(0, 6).join(', ') + (paths.length > 6 ? ' and ' + (paths.length - 6) + ' more' : '')
63
+ action fill(name, value) { filled = { ...filled, [name]: value } }
64
+ action submitAsked() { bridge.post({ type: 'filled', id: asking.id, what: asking.what, values: filled }); asking = null; filled = {} }
65
+ action cancelAsked() { asking = null; filled = {} }
66
+ function keys(e) { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); send() } }
67
+ const tokens = (n) => (n >= 1000 ? (n / 1000).toFixed(n >= 10000 ? 0 : 1) + 'k' : String(n))
68
+
69
+ render {
70
+ <section class="ca-panel" aria-label="Clarity Agent">
71
+ <header class="ca-top">
72
+ <button type="button" class="ca-model" on:click={ pickModel() } title="Choose the model" disabled={ busy }>{ model ?? 'Choose a model' }</button>
73
+ <label class="ca-mode">
74
+ <span class="ca-hidden">What it may do without asking</span>
75
+ <select value={ mode } on:change={ (e) => setMode(e.target.value) } disabled={ busy }>
76
+ <list each={ MODES } as="m" key={ m[0] }><option value={ m[0] }>{ m[1] }</option></list>
77
+ </select>
78
+ </label>
79
+ <button type="button" class="ca-quiet" on:click={ fresh() } disabled={ busy } title="Start a new conversation">New</button>
80
+ </header>
81
+
82
+ <div class="ca-talk" role="log" aria-live="polite">
83
+ <when test={ items.length === 0 }>
84
+ <div class="ca-empty">
85
+ <p class="ca-lead">Say what to build or change in { name || 'this project' }.</p>
86
+ <p>The agent reads and edits the project's files and runs its checks. It asks before it changes anything, unless you let it.</p>
87
+ </div>
88
+ </when>
89
+ <list each={ items } as="item" key={ item.id }>
90
+ <article class={ 'ca-item ca-is-' + item.kind }>
91
+ <when test={ item.kind === 'user' }><p class="ca-said">{ item.text }</p></when>
92
+ <when test={ item.kind === 'text' }><p class="ca-text">{ item.text }</p></when>
93
+ <when test={ item.kind === 'tool' }>
94
+ <button type="button" class="ca-tool" aria-expanded={ open[item.id] ? 'true' : 'false' } on:click={ toggle(item.id) }>
95
+ <span class={ 'ca-dot' + (item.done ? (item.error ? ' ca-bad' : ' ca-good') : ' ca-busy') } aria-hidden="true"></span>
96
+ <span class="ca-what">{ item.summary }</span>
97
+ <span class="ca-hidden">{ item.done ? (item.error ? 'failed' : 'done') : 'working' }</span>
98
+ </button>
99
+ <when test={ open[item.id] && item.output }><pre class="ca-out">{ item.output }</pre></when>
100
+ <when test={ item.changes && item.changes.length > 0 }>
101
+ <ul class="ca-changes">
102
+ <list each={ item.changes } as="change" key={ change.path }>
103
+ <li>
104
+ <button type="button" class="ca-change" aria-expanded={ open[item.id + ':' + change.path] ? 'true' : 'false' } on:click={ toggle(item.id + ':' + change.path) }>
105
+ <span class="ca-path">{ change.path }</span>
106
+ <when test={ change.status !== 'changed' }><span class="ca-status">{ change.status === 'made' ? 'new' : 'removed' }</span></when>
107
+ <span class="ca-plus">+{ change.added }</span>
108
+ <span class="ca-minus">−{ change.removed }</span>
109
+ </button>
110
+ <when test={ open[item.id + ':' + change.path] }>
111
+ <pre class="ca-diff"><list each={ rows(change.diff) } as="row" key={ row.n }><span class={ 'ca-l ' + row.kind }>{ row.text }</span></list></pre>
112
+ <when test={ editorDiff && !item.undone }><button type="button" class="ca-quiet" on:click={ openDiff(item.checkpoint, change.path) }>Open in the editor's diff</button></when>
113
+ </when>
114
+ </li>
115
+ </list>
116
+ </ul>
117
+ <when test={ item.checkpoint && !item.undone }><button type="button" class="ca-quiet ca-undo" disabled={ busy } on:click={ undo(item.checkpoint, false) } title="Put the files back as they were before this step. Later steps are undone too.">Undo from here</button></when>
118
+ <when test={ item.undone }><p class="ca-note">Undone.</p></when>
119
+ </when>
120
+ <when test={ item.others && item.others.length > 0 }><p class="ca-note">Also changed by this command (not kept, so not undone): { listed(item.others) }</p></when>
121
+ </when>
122
+ <when test={ item.kind === 'ask' }>
123
+ <div class="ca-ask" role="group" aria-label="The agent asks">
124
+ <p class="ca-question">{ item.summary }</p>
125
+ <when test={ item.diff }>
126
+ <p class="ca-note"><span class="ca-path">{ item.path }</span> <span class="ca-plus">+{ item.added }</span> <span class="ca-minus">−{ item.removed }</span></p>
127
+ <pre class="ca-diff"><list each={ rows(item.diff) } as="row" key={ row.n }><span class={ 'ca-l ' + row.kind }>{ row.text }</span></list></pre>
128
+ </when>
129
+ <when test={ item.usd != null }><p class="ca-cost">This costs about ${ Number(item.usd).toFixed(2) }{ item.note ? ' · ' + item.note : '' }</p></when>
130
+ <when test={ item.answer === null }>
131
+ <div class="ca-answers">
132
+ <button type="button" class="ca-yes" on:click={ answer(item.id, true) }>Allow</button>
133
+ <when test={ item.risk === 'exec' }><button type="button" on:click={ answer(item.id, 'always') }>Always allow this command</button></when>
134
+ <button type="button" class="ca-no" on:click={ answer(item.id, false) }>Don't allow</button>
135
+ </div>
136
+ </when>
137
+ <when test={ item.answer !== null }><p class="ca-answered">{ item.answer ? (item.answer === 'always' ? 'Allowed from now on' : 'Allowed') : 'Not allowed' }</p></when>
138
+ </div>
139
+ </when>
140
+ <when test={ item.kind === 'refused' }><p class="ca-note">{ item.summary }</p></when>
141
+ <when test={ item.kind === 'note' }><p class="ca-note">{ item.text }</p></when>
142
+ <when test={ item.kind === 'undone' }><p class="ca-note">Put back as before: { listed(item.files) }{ item.skipped && item.skipped.length ? '. Too large to have been kept: ' + listed(item.skipped) : '' }</p></when>
143
+ <when test={ item.kind === 'undo-blocked' }>
144
+ <div class="ca-ask" role="group" aria-label="Undo needs your word">
145
+ <p>You changed { listed(item.conflicts) } after the agent did. Undoing puts back what was there before the agent's step, and your change is lost.</p>
146
+ <when test={ !item.settled }><div class="ca-answers"><button type="button" class="ca-no" disabled={ busy } on:click={ undo(item.checkpoint, true) }>Undo anyway</button></div></when>
147
+ </div>
148
+ </when>
149
+ <when test={ item.kind === 'error' }><p class="ca-error" role="alert">{ item.text }</p></when>
150
+ <when test={ item.kind === 'done' }><p class="ca-note">{ item.stopped ? 'Stopped.' : item.unfinished ? 'It ran out of steps. Say "go on" to continue.' : 'Done in ' + item.steps + (item.steps === 1 ? ' step.' : ' steps.') }</p></when>
151
+ </article>
152
+ </list>
153
+ <when test={ problem }>
154
+ <div class="ca-setup" role="alert">
155
+ <p>{ problem }</p>
156
+ <div class="ca-answers">
157
+ <button type="button" class="ca-yes" on:click={ giveKey() }>Add a key</button>
158
+ <button type="button" on:click={ pickModel() }>Choose a model</button>
159
+ </div>
160
+ </div>
161
+ </when>
162
+ <div ref={ (el) => { end = el } }></div>
163
+ </div>
164
+
165
+ <when test={ asking }>
166
+ <form class="ca-form" on:submit={ (e) => { e.preventDefault(); submitAsked() } }>
167
+ <p class="ca-question">{ asking.title }</p>
168
+ <list each={ asking.fields } as="field" key={ field.name }>
169
+ <label class="ca-field"><span>{ field.label }</span>
170
+ <input type={ field.secret ? 'password' : 'text' } name={ field.name } placeholder={ field.placeholder ?? '' } autocomplete="off" spellcheck="false" value={ filled[field.name] ?? '' } on:input={ (e) => fill(field.name, e.target.value) } />
171
+ </label>
172
+ </list>
173
+ <div class="ca-answers">
174
+ <button type="submit" class="ca-yes">Save</button>
175
+ <button type="button" on:click={ cancelAsked() }>Cancel</button>
176
+ </div>
177
+ </form>
178
+ </when>
179
+
180
+ <form class="ca-write" on:submit={ (e) => { e.preventDefault(); send() } }>
181
+ <label class="ca-hidden" for="ca-draft">What should the agent do?</label>
182
+ <textarea id="ca-draft" rows="3" placeholder="Add a booking page with a calendar and a form" value={ draft } on:input={ (e) => { draft = e.target.value } } on:keydown={ keys }></textarea>
183
+ <div class="ca-foot">
184
+ <span class="ca-meter">{ usage.input + usage.output > 0 ? tokens(usage.input) + ' in · ' + tokens(usage.output) + ' out' : '' }{ spent && spent.today > 0 ? ' · $' + spent.today.toFixed(2) + ' today' : '' }</span>
185
+ <when test={ busy }><button type="button" class="ca-no" on:click={ halt() }>Stop</button></when>
186
+ <when test={ !busy }><button type="submit" class="ca-yes" disabled={ !draft.trim() }>Send</button></when>
187
+ </div>
188
+ </form>
189
+ </section>
190
+ }
191
+ }
package/ui/main.js ADDED
@@ -0,0 +1,28 @@
1
+ // The panel put on a page: it finds how to reach the session behind it, by where it runs.
2
+ // in an editor's webview acquireVsCodeApi(): postMessage out, a `message` event in
3
+ // in the desktop window POST /say out, an event stream (/events) in, each with the window's token
4
+ import { mount } from '@ozsarman/clarityjs/runtime'
5
+ import { Panel } from './Panel.clarity'
6
+
7
+ function bridge() {
8
+ if (typeof acquireVsCodeApi === 'function') {
9
+ const editor = acquireVsCodeApi()
10
+ return {
11
+ can: { editorDiff: true },
12
+ post: (message) => editor.postMessage(message),
13
+ listen(fn) { const hear = (e) => fn(e.data); addEventListener('message', hear); return () => removeEventListener('message', hear) },
14
+ }
15
+ }
16
+ const token = document.querySelector('meta[name="clarity-agent-token"]')?.content ?? ''
17
+ return {
18
+ can: {},
19
+ post: (message) => fetch('/say', { method: 'POST', headers: { 'content-type': 'application/json', 'x-clarity-agent': token }, body: JSON.stringify(message) }).catch(() => {}),
20
+ listen(fn) {
21
+ const stream = new EventSource('/events?t=' + encodeURIComponent(token))
22
+ stream.onmessage = (e) => fn(JSON.parse(e.data))
23
+ return () => stream.close()
24
+ },
25
+ }
26
+ }
27
+
28
+ mount(Panel, document.getElementById('ca-root'), { bridge: bridge() })
package/ui/panel.css ADDED
@@ -0,0 +1,93 @@
1
+ /* The agent's panel. In an editor it takes the editor's own colours (the --vscode-* variables); in the window on
2
+ the desktop those are not there and its own are used, light or dark as the system is. */
3
+ :root {
4
+ --ca-ink: var(--vscode-foreground, #1d2330);
5
+ --ca-soft: var(--vscode-descriptionForeground, #5b6475);
6
+ --ca-page: var(--vscode-sideBar-background, #f6f4ef);
7
+ --ca-card: var(--vscode-editorWidget-background, #ffffff);
8
+ --ca-line: var(--vscode-panel-border, #d9d5cb);
9
+ --ca-go: var(--vscode-button-background, #1f5fd1);
10
+ --ca-go-ink: var(--vscode-button-foreground, #ffffff);
11
+ --ca-field: var(--vscode-input-background, #ffffff);
12
+ --ca-bad: var(--vscode-errorForeground, #b3261e);
13
+ --ca-good: var(--vscode-testing-iconPassed, #1d7a46);
14
+ --ca-focus: var(--vscode-focusBorder, #1f5fd1);
15
+ --ca-mono: var(--vscode-editor-font-family, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
16
+ }
17
+ @media (prefers-color-scheme: dark) {
18
+ :root {
19
+ --ca-ink: var(--vscode-foreground, #e7e9ee);
20
+ --ca-soft: var(--vscode-descriptionForeground, #9aa3b5);
21
+ --ca-page: var(--vscode-sideBar-background, #14171d);
22
+ --ca-card: var(--vscode-editorWidget-background, #1c2028);
23
+ --ca-line: var(--vscode-panel-border, #2c323d);
24
+ --ca-go: var(--vscode-button-background, #4d8dff);
25
+ --ca-go-ink: var(--vscode-button-foreground, #0b1020);
26
+ --ca-field: var(--vscode-input-background, #0f1217);
27
+ --ca-bad: var(--vscode-errorForeground, #ff8a80);
28
+ --ca-good: var(--vscode-testing-iconPassed, #5fd28c);
29
+ --ca-focus: var(--vscode-focusBorder, #4d8dff);
30
+ }
31
+ }
32
+ html, body { height: 100%; margin: 0; }
33
+ body { background: var(--ca-page); color: var(--ca-ink); font: 13px/1.5 var(--vscode-font-family, system-ui, -apple-system, "Segoe UI", sans-serif); }
34
+ #ca-root { height: 100%; }
35
+ .ca-panel { display: flex; flex-direction: column; height: 100%; min-width: 0; }
36
+ .ca-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
37
+ .ca-panel button, .ca-panel select, .ca-panel textarea { font: inherit; color: inherit; }
38
+ .ca-panel button { background: transparent; border: 1px solid var(--ca-line); border-radius: 4px; padding: 3px 10px; cursor: pointer; }
39
+ .ca-panel button:disabled { opacity: 0.55; cursor: default; }
40
+ .ca-panel button:focus-visible, .ca-panel select:focus-visible, .ca-panel textarea:focus-visible { outline: 2px solid var(--ca-focus); outline-offset: 1px; }
41
+ .ca-panel .ca-yes { background: var(--ca-go); color: var(--ca-go-ink); border-color: transparent; }
42
+ .ca-panel .ca-no { border-color: var(--ca-bad); color: var(--ca-bad); }
43
+
44
+ .ca-top { display: flex; gap: 6px; align-items: center; padding: 8px 10px; border-bottom: 1px solid var(--ca-line); }
45
+ .ca-model { flex: 1 1 auto; min-width: 0; text-align: left; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--ca-mono); font-size: 12px; }
46
+ .ca-mode select { background: var(--ca-field); border: 1px solid var(--ca-line); border-radius: 4px; padding: 3px 4px; }
47
+
48
+ .ca-talk { flex: 1 1 auto; overflow-y: auto; padding: 12px 10px; display: flex; flex-direction: column; gap: 8px; }
49
+ .ca-empty { color: var(--ca-soft); max-width: 46ch; margin: auto 0; }
50
+ .ca-empty p { margin: 0 0 8px; }
51
+ .ca-lead { color: var(--ca-ink); font-size: 15px; }
52
+ .ca-item p { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
53
+ .ca-is-user { align-self: flex-end; max-width: 88%; background: var(--ca-card); border: 1px solid var(--ca-line); border-radius: 10px 10px 2px 10px; padding: 6px 10px; }
54
+ .ca-tool { display: flex; gap: 8px; align-items: baseline; width: 100%; text-align: left; border: 0 !important; padding: 2px 0 !important; color: var(--ca-soft) !important; font-family: var(--ca-mono); font-size: 12px; }
55
+ .ca-what { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
56
+ .ca-dot { flex: none; width: 7px; height: 7px; border-radius: 50%; background: var(--ca-soft); transform: translateY(-1px); }
57
+ .ca-dot.ca-good { background: var(--ca-good); }
58
+ .ca-dot.ca-bad { background: var(--ca-bad); }
59
+ .ca-dot.ca-busy { animation: ca-pulse 1.1s ease-in-out infinite; }
60
+ @keyframes ca-pulse { 50% { opacity: 0.25; } }
61
+ @media (prefers-reduced-motion: reduce) { .ca-dot.ca-busy { animation: none; } }
62
+ .ca-out { margin: 4px 0 2px 15px; padding: 8px; max-height: 220px; overflow: auto; background: var(--ca-field); border: 1px solid var(--ca-line); border-radius: 4px; font: 12px/1.45 var(--ca-mono); white-space: pre-wrap; overflow-wrap: anywhere; }
63
+ .ca-ask, .ca-setup { background: var(--ca-card); border: 1px solid var(--ca-line); border-left: 3px solid var(--ca-go); border-radius: 4px; padding: 8px 10px; }
64
+ .ca-setup { border-left-color: var(--ca-bad); }
65
+ .ca-setup p { margin: 0; }
66
+ .ca-question { font-family: var(--ca-mono); font-size: 12px; }
67
+ .ca-cost, .ca-answered, .ca-note { color: var(--ca-soft); }
68
+ .ca-answers { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; }
69
+ .ca-error { color: var(--ca-bad); }
70
+
71
+ .ca-write { border-top: 1px solid var(--ca-line); padding: 8px 10px 10px; }
72
+ .ca-write textarea { display: block; width: 100%; box-sizing: border-box; resize: vertical; min-height: 54px; background: var(--ca-field); border: 1px solid var(--ca-line); border-radius: 4px; padding: 6px 8px; }
73
+ .ca-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-top: 6px; }
74
+ .ca-meter { color: var(--ca-soft); font-size: 12px; font-variant-numeric: tabular-nums; }
75
+
76
+ .ca-form { border-top: 1px solid var(--ca-line); padding: 8px 10px; display: grid; gap: 6px; }
77
+ .ca-form p { margin: 0; }
78
+ .ca-field { display: grid; gap: 2px; color: var(--ca-soft); font-size: 12px; }
79
+ .ca-field input { font: 12px var(--ca-mono); color: var(--ca-ink); background: var(--ca-field); border: 1px solid var(--ca-line); border-radius: 4px; padding: 5px 8px; }
80
+ .ca-field input:focus-visible { outline: 2px solid var(--ca-focus); outline-offset: 1px; }
81
+
82
+ .ca-changes { list-style: none; margin: 2px 0 0 15px; padding: 0; display: grid; gap: 2px; }
83
+ .ca-change { display: flex; gap: 8px; align-items: baseline; width: 100%; text-align: left; border: 0 !important; padding: 1px 0 !important; font: 12px var(--ca-mono); }
84
+ .ca-path { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--ca-mono); font-size: 12px; }
85
+ .ca-plus { color: var(--ca-good); font-variant-numeric: tabular-nums; }
86
+ .ca-minus { color: var(--ca-bad); font-variant-numeric: tabular-nums; }
87
+ .ca-status { color: var(--ca-soft); }
88
+ .ca-diff { margin: 4px 0; padding: 4px 0; max-height: 260px; overflow: auto; background: var(--ca-field); border: 1px solid var(--ca-line); border-radius: 4px; font: 12px/1.45 var(--ca-mono); }
89
+ .ca-l { display: block; white-space: pre; padding: 0 8px; min-width: max-content; }
90
+ .ca-add { background: var(--vscode-diffEditor-insertedLineBackground, color-mix(in srgb, var(--ca-good) 20%, transparent)); }
91
+ .ca-del { background: var(--vscode-diffEditor-removedLineBackground, color-mix(in srgb, var(--ca-bad) 18%, transparent)); }
92
+ .ca-hunk { color: var(--ca-soft); }
93
+ .ca-undo { margin: 4px 0 0 15px; font-size: 12px; }