@jantcz/webai 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/LICENSE +135 -0
- package/README.md +24 -2
- package/agents/.claude-plugin/plugin.json +4 -0
- package/agents/README.md +17 -0
- package/agents/agents/a11y-reviewer.md +16 -0
- package/agents/agents/copy-editor.md +14 -0
- package/agents/skills/czech-copy/SKILL.md +18 -0
- package/agents/skills/element-edit/SKILL.md +51 -0
- package/agents/skills/stock-images/SKILL.md +25 -0
- package/agents/skills/verify-change/SKILL.md +19 -0
- package/agents/skills/web-styling/SKILL.md +20 -0
- package/bin/webai-agent.js +355 -0
- package/bin/webai-bridge.js +5 -0
- package/bin/webai.js +4 -0
- package/package.json +85 -4
- package/src/agents/claude.js +161 -0
- package/src/agents/codex.js +111 -0
- package/src/agents/custom.js +64 -0
- package/src/agents/docker.js +46 -0
- package/src/agents/gemini.js +102 -0
- package/src/agents/index.js +25 -0
- package/src/agents/opencode.js +117 -0
- package/src/agents/pack.js +99 -0
- package/src/agents/pi.js +143 -0
- package/src/agents/webai.js +66 -0
- package/src/astro/annotate.js +163 -0
- package/src/astro/index.d.ts +5 -0
- package/src/astro/index.js +40 -0
- package/src/bridge.js +62 -0
- package/src/cli.js +108 -0
- package/src/client/overlay.js +887 -0
- package/src/config.js +23 -0
- package/src/core.js +102 -0
- package/src/history.js +108 -0
- package/src/html.js +43 -0
- package/src/index.d.ts +228 -0
- package/src/index.js +10 -0
- package/src/inject.js +80 -0
- package/src/next/index.d.ts +8 -0
- package/src/next/index.js +59 -0
- package/src/next/script.d.ts +3 -0
- package/src/next/script.js +13 -0
- package/src/prompt.js +17 -0
- package/src/proxy.js +68 -0
- package/src/server.js +211 -0
- package/src/session.js +455 -0
- package/src/static.js +64 -0
- package/src/vite.d.ts +5 -0
- package/src/vite.js +42 -0
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The built-in agent: a small loop over an OpenAI-compatible /chat/completions
|
|
3
|
+
// with file tools on the project (cwd), for when no coding CLI is at hand. Runs
|
|
4
|
+
// one turn per call: the prompt on stdin, the conversation in
|
|
5
|
+
// .webai/agent/<session>.json, events as JSON lines on stdout (the shape the
|
|
6
|
+
// overlay's session expects: status, text, tool, tool-error, done).
|
|
7
|
+
//
|
|
8
|
+
// usage: webai-agent --session <id> [--resume] --base-url <url> --model <id>
|
|
9
|
+
// [--fallbacks a,b,c] [--system <text>]
|
|
10
|
+
// The key comes from WEBAI_API_KEY (or OPENROUTER_API_KEY for openrouter.ai).
|
|
11
|
+
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { parseArgs } from 'node:util';
|
|
15
|
+
|
|
16
|
+
const MAX_STEPS = 25;
|
|
17
|
+
const MAX_READ_BYTES = 200_000;
|
|
18
|
+
const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
|
|
19
|
+
const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', '.astro', '.webai', '.agents', '.codex', '.gemini', '.claude', '.vercel', '.netlify']);
|
|
20
|
+
const TEXT_EXT = /\.(astro|html?|css|scss|sass|less|m?[jt]sx?|json|ya?ml|toml|md|mdx|svg|txt|xml|webmanifest|vue|svelte)$/i;
|
|
21
|
+
|
|
22
|
+
function parseOpts(argv) {
|
|
23
|
+
return parseArgs({
|
|
24
|
+
args: argv,
|
|
25
|
+
strict: false,
|
|
26
|
+
options: {
|
|
27
|
+
session: { type: 'string' },
|
|
28
|
+
resume: { type: 'boolean', default: false },
|
|
29
|
+
'base-url': { type: 'string' },
|
|
30
|
+
model: { type: 'string' },
|
|
31
|
+
fallbacks: { type: 'string', default: '' },
|
|
32
|
+
system: { type: 'string', default: '' },
|
|
33
|
+
},
|
|
34
|
+
}).values;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Set per run by `runAgent`; the defaults are the real process.
|
|
38
|
+
let root = process.cwd();
|
|
39
|
+
let out;
|
|
40
|
+
|
|
41
|
+
const TOOLS = [
|
|
42
|
+
tool('list_files', 'List the project files (without node_modules, dist and similar), optionally under a folder.', { dir: { type: 'string' } }),
|
|
43
|
+
tool('search_files', 'Find lines matching a regular expression in the project text files. Returns path:line: text.', { pattern: { type: 'string' }, dir: { type: 'string' } }, ['pattern']),
|
|
44
|
+
tool('read_file', 'Read a text file. Each line is prefixed with its number and a tab, which are not part of the content.', { path: { type: 'string' } }, ['path']),
|
|
45
|
+
tool(
|
|
46
|
+
'edit_file',
|
|
47
|
+
'Replace an exact, unique piece of text in a file. Include enough surrounding text to make old_text unique.',
|
|
48
|
+
{ path: { type: 'string' }, old_text: { type: 'string' }, new_text: { type: 'string' } },
|
|
49
|
+
['path', 'old_text', 'new_text'],
|
|
50
|
+
),
|
|
51
|
+
tool('write_file', 'Create or overwrite a whole text file.', { path: { type: 'string' }, content: { type: 'string' } }, ['path', 'content']),
|
|
52
|
+
tool('delete_file', 'Delete a file.', { path: { type: 'string' } }, ['path']),
|
|
53
|
+
tool(
|
|
54
|
+
'search_images',
|
|
55
|
+
'Search openly licensed photos and illustrations (Openverse; only ones that may be used on commercial sites and resized). Returns id, title, creator, license and size.',
|
|
56
|
+
{ query: { type: 'string', description: 'A few English words.' } },
|
|
57
|
+
['query'],
|
|
58
|
+
),
|
|
59
|
+
tool(
|
|
60
|
+
'add_image',
|
|
61
|
+
"Save an image from search_images into the project (e.g. public/images/hero.jpg, or src/assets/ when the site uses astro:assets) and get an HTML snippet with its credit.",
|
|
62
|
+
{ id: { type: 'string' }, path: { type: 'string' } },
|
|
63
|
+
['id', 'path'],
|
|
64
|
+
),
|
|
65
|
+
];
|
|
66
|
+
|
|
67
|
+
const TOOL_LABELS = { list_files: 'LS', search_files: 'Grep', read_file: 'Read', edit_file: 'Edit', write_file: 'Write', delete_file: 'Delete', search_images: 'Search images', add_image: 'Add image' };
|
|
68
|
+
|
|
69
|
+
const TOOLS_PROMPT = `You work on a website project through these tools (no shell). Read a file
|
|
70
|
+
before editing it; keep edits minimal and in the style of the code around them.
|
|
71
|
+
Text and styles often live elsewhere than the element's own file: props from a
|
|
72
|
+
parent, content collections (src/content), data files (src/data, src/config).
|
|
73
|
+
For a new image: search_images, then add_image, and insert the snippet it returns
|
|
74
|
+
with its credit caption.`;
|
|
75
|
+
|
|
76
|
+
function tool(name, description, properties, required = []) {
|
|
77
|
+
return { type: 'function', function: { name, description, parameters: { type: 'object', properties, required } } };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// ---------------------------------------------------------------- files
|
|
81
|
+
|
|
82
|
+
/** A path inside the project, or null (outside, hidden folders like .git, node_modules). */
|
|
83
|
+
export function inside(p) {
|
|
84
|
+
if (typeof p !== 'string' || !p.trim()) return null;
|
|
85
|
+
const abs = path.resolve(root, p.trim().replace(/^\/+/, ''));
|
|
86
|
+
const rel = path.relative(root, abs);
|
|
87
|
+
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return null;
|
|
88
|
+
const parts = rel.split(path.sep);
|
|
89
|
+
if (parts.some((x) => SKIP_DIRS.has(x)) || parts.at(-1) === '.env' || parts.at(-1).startsWith('.env.')) return null;
|
|
90
|
+
return { abs, rel: parts.join('/') };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function walk(dir, files = []) {
|
|
94
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
95
|
+
if (SKIP_DIRS.has(entry.name)) continue;
|
|
96
|
+
const full = path.join(dir, entry.name);
|
|
97
|
+
if (entry.isDirectory()) walk(full, files);
|
|
98
|
+
else if (entry.isFile()) files.push(path.relative(root, full).split(path.sep).join('/'));
|
|
99
|
+
}
|
|
100
|
+
return files;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Exact match first; then whole lines, ignoring indentation and quote style
|
|
105
|
+
* (weaker models get those wrong), new_text re-indented to the file.
|
|
106
|
+
*/
|
|
107
|
+
export function matchEdit(text, oldText, newText) {
|
|
108
|
+
const exact = text.split(oldText).length - 1;
|
|
109
|
+
if (exact) return { count: exact, old: oldText, new: newText };
|
|
110
|
+
const norm = (l) => l.trim().replace(/[“”„]/g, '"').replace(/[‘’‚]/g, "'");
|
|
111
|
+
const fileLines = text.split('\n');
|
|
112
|
+
const oldLines = oldText.split('\n');
|
|
113
|
+
while (oldLines.length && !oldLines.at(-1).trim()) oldLines.pop();
|
|
114
|
+
while (oldLines.length && !oldLines[0].trim()) oldLines.shift();
|
|
115
|
+
if (!oldLines.length) return { count: 0 };
|
|
116
|
+
const want = oldLines.map(norm);
|
|
117
|
+
const starts = [];
|
|
118
|
+
for (let i = 0; i + want.length <= fileLines.length; i++) {
|
|
119
|
+
if (want.every((w, j) => norm(fileLines[i + j]) === w)) starts.push(i);
|
|
120
|
+
}
|
|
121
|
+
if (starts.length !== 1) return { count: starts.length };
|
|
122
|
+
const matched = fileLines.slice(starts[0], starts[0] + want.length);
|
|
123
|
+
const width = (l) => l.match(/^\s*/)[0].replace(/\t/g, ' ').length;
|
|
124
|
+
const unit = matched.find((l) => /^\t/.test(l)) ? '\t' : ' ';
|
|
125
|
+
const pad = (n) => (unit === '\t' ? '\t'.repeat(Math.round(n / 2)) : ' '.repeat(n));
|
|
126
|
+
const diffs = (oldLines.length > 1 ? oldLines.slice(1) : oldLines).map((l, j) => width(matched[j + (oldLines.length > 1)]) - width(l));
|
|
127
|
+
const shift = diffs.sort((x, y) => diffs.filter((d) => d === y).length - diffs.filter((d) => d === x).length)[0];
|
|
128
|
+
const byText = new Map(matched.map((l) => [norm(l), l]));
|
|
129
|
+
const lines = newText.split('\n').map((l) => (l.trim() ? byText.get(norm(l)) ?? pad(Math.max(0, width(l) + shift)) + l.trim() : ''));
|
|
130
|
+
return { count: 1, old: matched.join('\n'), new: lines.join('\n') };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// ---------------------------------------------------------------- images (Openverse, no key)
|
|
134
|
+
|
|
135
|
+
const images = new Map();
|
|
136
|
+
|
|
137
|
+
async function searchImages(query) {
|
|
138
|
+
const url = `https://api.openverse.org/v1/images/?${new URLSearchParams({ q: query, page_size: '8', license_type: 'commercial,modification', mature: 'false' })}`;
|
|
139
|
+
const res = await fetch(url);
|
|
140
|
+
if (!res.ok) throw new Error(res.status === 429 ? 'Image search limit reached, try again later.' : `Image search failed (${res.status}).`);
|
|
141
|
+
const found = ((await res.json()).results ?? []).map((r) => ({
|
|
142
|
+
id: r.id,
|
|
143
|
+
title: r.title,
|
|
144
|
+
creator: r.creator,
|
|
145
|
+
license: `${['cc0', 'pdm'].includes(r.license) ? r.license.toUpperCase() : `CC ${r.license.toUpperCase()}`} ${r.license_version ?? ''}`.trim(),
|
|
146
|
+
size: r.width && r.height ? `${r.width}×${r.height}` : undefined,
|
|
147
|
+
url: r.url,
|
|
148
|
+
page: r.foreign_landing_url,
|
|
149
|
+
thumbnail: r.thumbnail,
|
|
150
|
+
credit: !['cc0', 'pdm'].includes(r.license),
|
|
151
|
+
}));
|
|
152
|
+
for (const f of found) images.set(f.id, f);
|
|
153
|
+
return found;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function imageSnippet(src, image) {
|
|
157
|
+
const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => `&${{ '&': 'amp', '<': 'lt', '>': 'gt', '"': 'quot' }[c]};`);
|
|
158
|
+
const credit = image.credit
|
|
159
|
+
? `\n <figcaption>Photo: <a href="${esc(image.page ?? image.url)}">${esc(image.title)}</a>${image.creator ? ` by ${esc(image.creator)}` : ''}, ${esc(image.license)}</figcaption>`
|
|
160
|
+
: '';
|
|
161
|
+
return `<figure>\n <img src="${esc(src)}" alt="${esc(image.title)}">${credit}\n</figure>`;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ---------------------------------------------------------------- tools
|
|
165
|
+
|
|
166
|
+
async function execute(call) {
|
|
167
|
+
const name = call.function?.name;
|
|
168
|
+
let args;
|
|
169
|
+
try {
|
|
170
|
+
args = JSON.parse(call.function?.arguments || '{}');
|
|
171
|
+
} catch {
|
|
172
|
+
return fail('Arguments are not valid JSON.');
|
|
173
|
+
}
|
|
174
|
+
out({ type: 'tool', id: call.id, name: TOOL_LABELS[name] ?? name, summary: String(args.path ?? args.pattern ?? args.query ?? args.dir ?? '').slice(0, 160) });
|
|
175
|
+
function fail(text) {
|
|
176
|
+
out({ type: 'tool-error', id: call.id, text: `${TOOL_LABELS[name] ?? name}: ${text}` });
|
|
177
|
+
return `Error: ${text}`;
|
|
178
|
+
}
|
|
179
|
+
const file = args.path === undefined ? null : inside(args.path);
|
|
180
|
+
if (args.path !== undefined && !file) return fail(`Not a project path: ${args.path}`);
|
|
181
|
+
try {
|
|
182
|
+
switch (name) {
|
|
183
|
+
case 'list_files': {
|
|
184
|
+
const base = args.dir ? inside(args.dir) : { abs: root };
|
|
185
|
+
if (!base) return fail(`Not a project folder: ${args.dir}`);
|
|
186
|
+
return walk(base.abs).sort().join('\n') || '(empty)';
|
|
187
|
+
}
|
|
188
|
+
case 'search_files': {
|
|
189
|
+
const re = new RegExp(args.pattern, 'i');
|
|
190
|
+
const base = args.dir ? inside(args.dir) : { abs: root };
|
|
191
|
+
if (!base) return fail(`Not a project folder: ${args.dir}`);
|
|
192
|
+
const hits = [];
|
|
193
|
+
for (const rel of walk(base.abs).filter((f) => TEXT_EXT.test(f))) {
|
|
194
|
+
fs.readFileSync(path.join(root, rel), 'utf8').split('\n').forEach((line, i) => {
|
|
195
|
+
if (hits.length < 100 && re.test(line)) hits.push(`${rel}:${i + 1}: ${line.trim().slice(0, 200)}`);
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
return hits.join('\n') || 'No matches.';
|
|
199
|
+
}
|
|
200
|
+
case 'read_file': {
|
|
201
|
+
if (!fs.existsSync(file.abs)) return fail(`No such file: ${file.rel}`);
|
|
202
|
+
if (!TEXT_EXT.test(file.rel)) return `Binary or non-text file (${fs.statSync(file.abs).size} bytes). Reference it by its path.`;
|
|
203
|
+
const text = fs.readFileSync(file.abs, 'utf8');
|
|
204
|
+
if (text.length > MAX_READ_BYTES) return fail(`File too large to read (${text.length} chars).`);
|
|
205
|
+
return text.split('\n').map((l, i) => `${i + 1}\t${l}`).join('\n');
|
|
206
|
+
}
|
|
207
|
+
case 'edit_file': {
|
|
208
|
+
if (!fs.existsSync(file.abs)) return fail(`No such file: ${file.rel}`);
|
|
209
|
+
const text = fs.readFileSync(file.abs, 'utf8');
|
|
210
|
+
if (!args.old_text) return fail('old_text is empty.');
|
|
211
|
+
const edit = matchEdit(text, args.old_text, args.new_text ?? '');
|
|
212
|
+
if (edit.count === 0) return fail('old_text not found. Read the file again and copy the text exactly.');
|
|
213
|
+
if (edit.count > 1) return fail(`old_text occurs ${edit.count} times. Include more surrounding text.`);
|
|
214
|
+
fs.writeFileSync(file.abs, text.replace(edit.old, () => edit.new));
|
|
215
|
+
return 'OK';
|
|
216
|
+
}
|
|
217
|
+
case 'write_file': {
|
|
218
|
+
if (!TEXT_EXT.test(file.rel)) return fail('Only text files (source, styles, content, config).');
|
|
219
|
+
fs.mkdirSync(path.dirname(file.abs), { recursive: true });
|
|
220
|
+
fs.writeFileSync(file.abs, String(args.content ?? ''));
|
|
221
|
+
return 'OK';
|
|
222
|
+
}
|
|
223
|
+
case 'delete_file': {
|
|
224
|
+
if (!fs.existsSync(file.abs)) return fail(`No such file: ${file.rel}`);
|
|
225
|
+
fs.rmSync(file.abs);
|
|
226
|
+
return 'OK';
|
|
227
|
+
}
|
|
228
|
+
case 'search_images': {
|
|
229
|
+
const found = await searchImages(String(args.query ?? ''));
|
|
230
|
+
if (!found.length) return 'No images found. Try other, more general words.';
|
|
231
|
+
return JSON.stringify(found.map(({ id, title, creator, license, size }) => ({ id, title, creator, license, size })));
|
|
232
|
+
}
|
|
233
|
+
case 'add_image': {
|
|
234
|
+
const image = images.get(args.id);
|
|
235
|
+
if (!image) return fail('Unknown id. Use an id from search_images (in this message).');
|
|
236
|
+
if (!/\.(jpe?g|png|webp|gif|avif)$/i.test(file.rel)) return fail('Use a path like public/images/name.jpg.');
|
|
237
|
+
let data;
|
|
238
|
+
for (const url of [image.url, image.thumbnail]) {
|
|
239
|
+
const res = await fetch(url).catch(() => null);
|
|
240
|
+
const buf = res?.ok ? Buffer.from(await res.arrayBuffer()) : null;
|
|
241
|
+
if (buf && buf.length <= MAX_IMAGE_BYTES) {
|
|
242
|
+
data = buf;
|
|
243
|
+
break;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (!data) return fail('This image could not be downloaded. Pick another one.');
|
|
247
|
+
fs.mkdirSync(path.dirname(file.abs), { recursive: true });
|
|
248
|
+
fs.writeFileSync(file.abs, data);
|
|
249
|
+
const src = file.rel.startsWith('public/') ? `/${file.rel.slice('public/'.length)}` : file.rel;
|
|
250
|
+
return `Saved ${file.rel} (${Math.round(data.length / 1024)} kB). Insert this (for src/assets, import the file and use <Image> instead):\n${imageSnippet(src, image)}`;
|
|
251
|
+
}
|
|
252
|
+
default:
|
|
253
|
+
return fail(`Unknown tool: ${name}`);
|
|
254
|
+
}
|
|
255
|
+
} catch (err) {
|
|
256
|
+
return fail(err.message);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// ---------------------------------------------------------------- the loop
|
|
261
|
+
|
|
262
|
+
function apiError(status, data) {
|
|
263
|
+
const detail = data?.error?.message ?? data?.message ?? '';
|
|
264
|
+
if (status === 401) return `The provider rejected the key (401). Set WEBAI_API_KEY (or OPENROUTER_API_KEY) where the dev server runs. ${detail}`.trim();
|
|
265
|
+
if (status === 429) return `The provider is rate limiting requests (429), try again in a moment. ${detail}`.trim();
|
|
266
|
+
return `API error ${status}: ${typeof detail === 'string' ? detail : JSON.stringify(detail)}`.slice(0, 600);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** After a stop mid-turn: every tool call gets a result, or the API refuses the conversation. */
|
|
270
|
+
function repaired(messages) {
|
|
271
|
+
const answered = new Set(messages.filter((m) => m.role === 'tool').map((m) => m.tool_call_id));
|
|
272
|
+
return messages.flatMap((m) => [m, ...(m.tool_calls ?? []).filter((c) => !answered.has(c.id)).map((c) => ({ role: 'tool', tool_call_id: c.id, content: 'Error: interrupted.' }))]);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
async function main(opts, env, readPrompt) {
|
|
276
|
+
const baseUrl = (opts['base-url'] ?? '').replace(/\/$/, '');
|
|
277
|
+
if (!baseUrl || !opts.model || !opts.session) throw new Error('usage: webai-agent --session <id> --base-url <url> --model <id> < prompt');
|
|
278
|
+
const key = env.WEBAI_API_KEY || (baseUrl.includes('openrouter.ai') ? env.OPENROUTER_API_KEY : '') || '';
|
|
279
|
+
const store = path.join(root, '.webai', 'agent', `${opts.session.replace(/[^\w-]/g, '')}.json`);
|
|
280
|
+
const messages = opts.resume && fs.existsSync(store) ? repaired(JSON.parse(fs.readFileSync(store, 'utf8'))) : [];
|
|
281
|
+
const save = () => {
|
|
282
|
+
fs.mkdirSync(path.dirname(store), { recursive: true });
|
|
283
|
+
fs.writeFileSync(store, JSON.stringify(messages));
|
|
284
|
+
};
|
|
285
|
+
const prompt = readPrompt();
|
|
286
|
+
messages.push({ role: 'user', content: prompt });
|
|
287
|
+
const system = [opts.system, TOOLS_PROMPT].filter(Boolean).join('\n\n');
|
|
288
|
+
const fallbacks = opts.fallbacks.split(',').map((m) => m.trim()).filter(Boolean);
|
|
289
|
+
let model = opts.model;
|
|
290
|
+
let costUsd = 0;
|
|
291
|
+
|
|
292
|
+
for (let step = 0; step < MAX_STEPS; step++) {
|
|
293
|
+
let msg;
|
|
294
|
+
const candidates = [model, ...fallbacks.filter((m) => m !== model)];
|
|
295
|
+
for (const candidate of candidates) {
|
|
296
|
+
if (candidate !== model) out({ type: 'status', text: `${model} is busy, switching to ${candidate}…` });
|
|
297
|
+
model = candidate;
|
|
298
|
+
const res = await fetch(`${baseUrl}/chat/completions`, {
|
|
299
|
+
method: 'POST',
|
|
300
|
+
headers: { 'Content-Type': 'application/json', ...(key ? { Authorization: `Bearer ${key}` } : {}), 'X-Title': 'webai' },
|
|
301
|
+
body: JSON.stringify({
|
|
302
|
+
model,
|
|
303
|
+
messages: [{ role: 'system', content: system }, ...messages],
|
|
304
|
+
tools: TOOLS,
|
|
305
|
+
tool_choice: 'auto',
|
|
306
|
+
...(baseUrl.includes('openrouter.ai') ? { usage: { include: true } } : {}),
|
|
307
|
+
}),
|
|
308
|
+
});
|
|
309
|
+
const data = await res.json().catch(() => ({}));
|
|
310
|
+
msg = res.ok ? data.choices?.[0]?.message : null;
|
|
311
|
+
if (msg) {
|
|
312
|
+
costUsd += data.usage?.cost ?? 0;
|
|
313
|
+
break;
|
|
314
|
+
}
|
|
315
|
+
const busy = res.status >= 500 || (res.status === 429 && /upstream|overload|temporarily/i.test(JSON.stringify(data)));
|
|
316
|
+
if (!res.ok && !busy) throw new Error(apiError(res.status, data));
|
|
317
|
+
if (candidate === candidates.at(-1)) throw new Error(res.ok ? 'The model returned no response.' : apiError(res.status, data));
|
|
318
|
+
}
|
|
319
|
+
const calls = msg.tool_calls ?? [];
|
|
320
|
+
messages.push({ role: 'assistant', content: msg.content ?? '', ...(calls.length ? { tool_calls: calls } : {}) });
|
|
321
|
+
if (msg.content?.trim()) out({ type: 'text', text: msg.content.trim() });
|
|
322
|
+
if (!calls.length) {
|
|
323
|
+
save();
|
|
324
|
+
out({ type: 'done', ok: true, costUsd });
|
|
325
|
+
return;
|
|
326
|
+
}
|
|
327
|
+
for (const call of calls) messages.push({ role: 'tool', tool_call_id: call.id, content: await execute(call) });
|
|
328
|
+
save();
|
|
329
|
+
}
|
|
330
|
+
save();
|
|
331
|
+
out({ type: 'done', ok: false, error: `The agent didn't finish within ${MAX_STEPS} steps.`, costUsd });
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** One turn. Injectable for tests: argv, working folder, environment, prompt reader and event writer. */
|
|
335
|
+
export async function runAgent(argv = process.argv.slice(2), io = {}) {
|
|
336
|
+
const { cwd = process.cwd(), env = process.env, readPrompt = () => fs.readFileSync(0, 'utf8'), write = (s) => process.stdout.write(s) } = io;
|
|
337
|
+
const saved = { root, out };
|
|
338
|
+
root = cwd;
|
|
339
|
+
out = (ev) => write(`${JSON.stringify(ev)}\n`);
|
|
340
|
+
let code = 0;
|
|
341
|
+
try {
|
|
342
|
+
await main(parseOpts(argv), env, readPrompt);
|
|
343
|
+
} catch (err) {
|
|
344
|
+
out({ type: 'done', ok: false, error: err.message });
|
|
345
|
+
code = 1;
|
|
346
|
+
}
|
|
347
|
+
({ root, out } = saved);
|
|
348
|
+
return code;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// Only true when executed as a script (covered by the child-process test, which node's coverage does not see).
|
|
352
|
+
/* node:coverage ignore next 3 */
|
|
353
|
+
if (process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(new URL(import.meta.url))) {
|
|
354
|
+
runAgent().then((code) => { process.exitCode = code; });
|
|
355
|
+
}
|
package/bin/webai.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,87 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jantcz/webai",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Click an element on your site, tell an AI coding agent what to change: it edits the source. For any dev server: CLI, Vite, Astro, Next.js. Claude Code, Codex, Gemini CLI, OpenCode, Pi or a built-in agent with free models.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/JanTcz/WebAI.git",
|
|
9
|
+
"directory": "packages/webai"
|
|
10
|
+
},
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./src/index.d.ts",
|
|
14
|
+
"default": "./src/index.js"
|
|
15
|
+
},
|
|
16
|
+
"./client": "./src/client/overlay.js",
|
|
17
|
+
"./astro": {
|
|
18
|
+
"types": "./src/astro/index.d.ts",
|
|
19
|
+
"default": "./src/astro/index.js"
|
|
20
|
+
},
|
|
21
|
+
"./vite": {
|
|
22
|
+
"types": "./src/vite.d.ts",
|
|
23
|
+
"default": "./src/vite.js"
|
|
24
|
+
},
|
|
25
|
+
"./next": {
|
|
26
|
+
"types": "./src/next/index.d.ts",
|
|
27
|
+
"default": "./src/next/index.js"
|
|
28
|
+
},
|
|
29
|
+
"./next/script": {
|
|
30
|
+
"types": "./src/next/script.d.ts",
|
|
31
|
+
"default": "./src/next/script.js"
|
|
32
|
+
},
|
|
33
|
+
"./html": "./src/html.js",
|
|
34
|
+
"./package.json": "./package.json"
|
|
35
|
+
},
|
|
36
|
+
"bin": {
|
|
37
|
+
"webai": "./bin/webai.js",
|
|
38
|
+
"webai-bridge": "./bin/webai-bridge.js"
|
|
39
|
+
},
|
|
40
|
+
"files": [
|
|
41
|
+
"src/**/*.js",
|
|
42
|
+
"src/**/*.d.ts",
|
|
43
|
+
"agents",
|
|
44
|
+
"bin"
|
|
45
|
+
],
|
|
46
|
+
"keywords": [
|
|
47
|
+
"ai",
|
|
48
|
+
"devtools",
|
|
49
|
+
"visual-editing",
|
|
50
|
+
"claude",
|
|
51
|
+
"codex",
|
|
52
|
+
"gemini",
|
|
53
|
+
"opencode",
|
|
54
|
+
"vite-plugin",
|
|
55
|
+
"astro-integration",
|
|
56
|
+
"withastro",
|
|
57
|
+
"nextjs",
|
|
58
|
+
"cli"
|
|
59
|
+
],
|
|
60
|
+
"engines": {
|
|
61
|
+
"node": ">=20"
|
|
62
|
+
},
|
|
63
|
+
"peerDependencies": {
|
|
64
|
+
"astro": ">=7",
|
|
65
|
+
"vite": ">=5",
|
|
66
|
+
"next": ">=14",
|
|
67
|
+
"react": ">=18"
|
|
68
|
+
},
|
|
69
|
+
"license": "PolyForm-Noncommercial-1.0.0",
|
|
70
|
+
"peerDependenciesMeta": {
|
|
71
|
+
"astro": {
|
|
72
|
+
"optional": true
|
|
73
|
+
},
|
|
74
|
+
"vite": {
|
|
75
|
+
"optional": true
|
|
76
|
+
},
|
|
77
|
+
"next": {
|
|
78
|
+
"optional": true
|
|
79
|
+
},
|
|
80
|
+
"react": {
|
|
81
|
+
"optional": true
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
"publishConfig": {
|
|
85
|
+
"access": "public"
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { PACK_DIR } from './pack.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Adapter for Claude Code in non-interactive mode (`claude -p`).
|
|
6
|
+
*
|
|
7
|
+
* One conversation = one session ID. The first message creates it via
|
|
8
|
+
* `--session-id`, later ones resume it via `--resume`, so the agent keeps
|
|
9
|
+
* context and the prompt cache is reused.
|
|
10
|
+
*
|
|
11
|
+
* @param {object} [opts]
|
|
12
|
+
* @param {string} [opts.bin] executable, default `claude`
|
|
13
|
+
* @param {string} [opts.model]
|
|
14
|
+
* @param {string} [opts.permissionMode] default `acceptEdits` – may edit files, not run Bash
|
|
15
|
+
* @param {string[]} [opts.allowedTools] e.g. `['Bash(npm run check)']`
|
|
16
|
+
* @param {boolean} [opts.projectSettings] load `.claude/` and `.mcp.json` from the project, default `true`
|
|
17
|
+
* @param {string[]} [opts.extraArgs]
|
|
18
|
+
*/
|
|
19
|
+
export function claudeAgent(opts = {}) {
|
|
20
|
+
const bin = opts.bin ?? 'claude';
|
|
21
|
+
return {
|
|
22
|
+
name: 'claude',
|
|
23
|
+
label: 'Claude Code',
|
|
24
|
+
bin,
|
|
25
|
+
// We pick the conversation ID ourselves via --session-id.
|
|
26
|
+
presetSessionId: true,
|
|
27
|
+
|
|
28
|
+
/** Options switchable from the panel. Empty value = default from the config. */
|
|
29
|
+
settings: {
|
|
30
|
+
model: [
|
|
31
|
+
{ value: '', label: opts.model ? `Default (${opts.model})` : 'Default' },
|
|
32
|
+
{ value: 'haiku', label: 'Haiku – cheapest, small edits' },
|
|
33
|
+
{ value: 'sonnet', label: 'Sonnet – balanced' },
|
|
34
|
+
{ value: 'opus', label: 'Opus – most capable' },
|
|
35
|
+
],
|
|
36
|
+
effort: [
|
|
37
|
+
{ value: '', label: 'Default' },
|
|
38
|
+
...['low', 'medium', 'high', 'xhigh', 'max'].map((v) => ({ value: v, label: v })),
|
|
39
|
+
],
|
|
40
|
+
},
|
|
41
|
+
|
|
42
|
+
command({ sessionId, resume, systemPrompt, settings = {} }) {
|
|
43
|
+
const args = [
|
|
44
|
+
'-p',
|
|
45
|
+
'--output-format', 'stream-json',
|
|
46
|
+
'--verbose',
|
|
47
|
+
'--include-partial-messages',
|
|
48
|
+
'--permission-mode', opts.permissionMode ?? 'acceptEdits',
|
|
49
|
+
resume ? '--resume' : '--session-id', sessionId,
|
|
50
|
+
// The system prompt isn't stored in the session, it's sent on every call.
|
|
51
|
+
'--append-system-prompt', systemPrompt,
|
|
52
|
+
];
|
|
53
|
+
const model = settings.model || opts.model;
|
|
54
|
+
if (model) args.push('--model', model);
|
|
55
|
+
if (settings.effort) args.push('--effort', settings.effort);
|
|
56
|
+
// Rules as separate arguments: a rule itself may contain a comma.
|
|
57
|
+
if (opts.allowedTools?.length) args.push('--allowedTools', ...opts.allowedTools);
|
|
58
|
+
// Without an allowed shell, don't offer Bash at all: in -p mode every attempt
|
|
59
|
+
// would be denied and the agent would waste time looking for another way.
|
|
60
|
+
if (!opts.allowedTools?.some((t) => t.startsWith('Bash'))) args.push('--disallowedTools', 'Bash');
|
|
61
|
+
// Skills and subagents from @jantcz/webai/agents (named webai:<skill>).
|
|
62
|
+
if (opts.skills !== false) args.push('--plugin-dir', PACK_DIR);
|
|
63
|
+
// No hooks, permissions or MCP servers from the project (bridge: the container writes to the project too).
|
|
64
|
+
if (opts.projectSettings === false) args.push('--setting-sources', 'user', '--strict-mcp-config');
|
|
65
|
+
args.push(...(opts.extraArgs ?? []));
|
|
66
|
+
// The prompt goes to stdin, not argv: it's often long and contains HTML.
|
|
67
|
+
return { cmd: bin, args, stdin: true };
|
|
68
|
+
},
|
|
69
|
+
|
|
70
|
+
/** Converts one stream-json line into UI events. */
|
|
71
|
+
parse(msg, ctx) {
|
|
72
|
+
switch (msg.type) {
|
|
73
|
+
case 'system':
|
|
74
|
+
return msg.subtype === 'init'
|
|
75
|
+
? [{ type: 'session', id: msg.session_id }, { type: 'status', text: `${msg.model ?? 'claude'} ready` }]
|
|
76
|
+
: [];
|
|
77
|
+
case 'stream_event': {
|
|
78
|
+
const ev = msg.event;
|
|
79
|
+
if (msg.parent_tool_use_id) return [];
|
|
80
|
+
if (ev?.type === 'content_block_delta' && ev.delta?.type === 'text_delta') {
|
|
81
|
+
return [{ type: 'delta', text: ev.delta.text }];
|
|
82
|
+
}
|
|
83
|
+
return [];
|
|
84
|
+
}
|
|
85
|
+
case 'assistant': {
|
|
86
|
+
if (msg.parent_tool_use_id) return [];
|
|
87
|
+
const out = [];
|
|
88
|
+
for (const block of msg.message?.content ?? []) {
|
|
89
|
+
if (block.type === 'text' && block.text.trim()) out.push({ type: 'text', text: block.text });
|
|
90
|
+
if (block.type === 'tool_use') out.push({ type: 'tool', id: block.id, name: block.name, summary: summarizeTool(block, ctx.root) });
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
case 'user': {
|
|
95
|
+
const out = [];
|
|
96
|
+
for (const block of msg.message?.content ?? []) {
|
|
97
|
+
if (block.type === 'tool_result' && block.is_error) {
|
|
98
|
+
out.push({ type: 'tool-error', id: block.tool_use_id, text: resultText(block.content).slice(0, 400) });
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
case 'result': {
|
|
104
|
+
const out = [];
|
|
105
|
+
for (const d of msg.permission_denials ?? []) {
|
|
106
|
+
out.push({ type: 'denied', name: d.tool_name, summary: summarizeTool({ name: d.tool_name, input: d.tool_input }, ctx.root) });
|
|
107
|
+
}
|
|
108
|
+
out.push({
|
|
109
|
+
type: 'done',
|
|
110
|
+
ok: !msg.is_error,
|
|
111
|
+
error: msg.is_error ? String(msg.result ?? msg.subtype) : undefined,
|
|
112
|
+
// total_cost_usd is the total for the whole session including previous --resume calls.
|
|
113
|
+
totalCostUsd: msg.total_cost_usd,
|
|
114
|
+
durationMs: msg.duration_ms,
|
|
115
|
+
turns: msg.num_turns,
|
|
116
|
+
});
|
|
117
|
+
return out;
|
|
118
|
+
}
|
|
119
|
+
default:
|
|
120
|
+
return [];
|
|
121
|
+
}
|
|
122
|
+
},
|
|
123
|
+
|
|
124
|
+
/** Stderr that tells us the session doesn't exist on disk. */
|
|
125
|
+
isMissingSession(stderr) {
|
|
126
|
+
return /no conversation found|session .* not found/i.test(stderr);
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function rel(file, root) {
|
|
132
|
+
if (!file) return '';
|
|
133
|
+
return path.isAbsolute(file) ? path.relative(root, file) || file : file;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function summarizeTool({ name, input = {} }, root) {
|
|
137
|
+
switch (name) {
|
|
138
|
+
case 'Edit':
|
|
139
|
+
case 'MultiEdit':
|
|
140
|
+
case 'Write':
|
|
141
|
+
case 'Read':
|
|
142
|
+
case 'NotebookEdit':
|
|
143
|
+
return rel(input.file_path ?? input.notebook_path, root);
|
|
144
|
+
case 'Bash':
|
|
145
|
+
return String(input.command ?? '').slice(0, 160);
|
|
146
|
+
case 'Grep':
|
|
147
|
+
case 'Glob':
|
|
148
|
+
// A search in the project root doesn't show the path.
|
|
149
|
+
return `${input.pattern ?? ''}${input.path && path.resolve(root, input.path) !== root ? ` in ${rel(input.path, root)}` : ''}`;
|
|
150
|
+
case 'WebFetch':
|
|
151
|
+
return input.url ?? '';
|
|
152
|
+
default:
|
|
153
|
+
return Object.values(input).filter((v) => typeof v === 'string').join(' ').slice(0, 120);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function resultText(content) {
|
|
158
|
+
if (typeof content === 'string') return content;
|
|
159
|
+
if (Array.isArray(content)) return content.map((c) => c.text ?? '').join('\n');
|
|
160
|
+
return '';
|
|
161
|
+
}
|