@jantcz/webai 0.0.0-stage → 0.3.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 +373 -0
- package/bin/webai-bridge.js +5 -0
- package/bin/webai.js +4 -0
- package/package.json +85 -4
- package/src/agents/claude.js +194 -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 +63 -0
- package/src/cli.js +119 -0
- package/src/client/overlay.js +1169 -0
- package/src/config.js +23 -0
- package/src/core.js +116 -0
- package/src/history.js +108 -0
- package/src/html.js +43 -0
- package/src/index.d.ts +244 -0
- package/src/index.js +10 -0
- package/src/inject.js +80 -0
- package/src/mcp/endpoint.js +71 -0
- package/src/mcp/stdio.js +103 -0
- package/src/mcp/tools.js +126 -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/pages.js +202 -0
- package/src/prompt.js +17 -0
- package/src/proxy.js +68 -0
- package/src/server.js +252 -0
- package/src/session.js +497 -0
- package/src/static.js +64 -0
- package/src/vite.d.ts +5 -0
- package/src/vite.js +145 -0
package/src/config.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
|
|
5
|
+
export const CONFIG_FILE = 'webai.config.mjs';
|
|
6
|
+
|
|
7
|
+
/** Options from `webai.config.mjs` in the project (or `config`), `{}` when there is none. */
|
|
8
|
+
export async function loadConfig(root, config, logger = consoleLogger) {
|
|
9
|
+
const file = config ? path.resolve(config) : path.join(root, CONFIG_FILE);
|
|
10
|
+
if (!fs.existsSync(file)) {
|
|
11
|
+
if (config) throw new Error(`Config ${file} does not exist.`);
|
|
12
|
+
return {};
|
|
13
|
+
}
|
|
14
|
+
logger.info(`Config: ${file}`);
|
|
15
|
+
const mod = await import(pathToFileURL(file).href);
|
|
16
|
+
return mod.default ?? {};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const consoleLogger = {
|
|
20
|
+
info: (msg) => console.log(`[webai] ${msg}`),
|
|
21
|
+
warn: (msg) => console.warn(`[webai] ${msg}`),
|
|
22
|
+
error: (msg) => console.error(`[webai] ${msg}`),
|
|
23
|
+
};
|
package/src/core.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { resolveAgents } from './agents/index.js';
|
|
6
|
+
import { consoleLogger } from './config.js';
|
|
7
|
+
import { injectHtml, SRC_ATTR } from './html.js';
|
|
8
|
+
import { htmlTransformer } from './inject.js';
|
|
9
|
+
import { loopbackUrl, removeEndpoint, writeEndpoint } from './mcp/endpoint.js';
|
|
10
|
+
import { BASE, createMiddleware, createProxyMiddleware, json, pageAllowed, routeOf } from './server.js';
|
|
11
|
+
import { AgentSession, describeAgents } from './session.js';
|
|
12
|
+
|
|
13
|
+
const CLIENT_FILE = fileURLToPath(new URL('./client/overlay.js', import.meta.url));
|
|
14
|
+
|
|
15
|
+
/** The tag that starts the overlay on a page. */
|
|
16
|
+
export const BOOT_TAG = `<script type="module" src="${BASE}/boot.js"></script>`;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* webai for any dev server: the agents' session, the overlay's HTTP API and
|
|
20
|
+
* the overlay's script, as one connect middleware. The framework plugins
|
|
21
|
+
* (`/astro`, `/vite`, `/next`) and the `webai` CLI are thin layers over it.
|
|
22
|
+
*
|
|
23
|
+
* @param {import('./index').CreateWebaiOptions} [options]
|
|
24
|
+
*/
|
|
25
|
+
export function createWebai(options = {}) {
|
|
26
|
+
const root = path.resolve(options.root ?? process.cwd());
|
|
27
|
+
const token = randomBytes(24).toString('hex');
|
|
28
|
+
const stateDir = options.stateDir ?? '.webai';
|
|
29
|
+
const bridge = options.bridge ?? process.env.WEBAI_BRIDGE ?? null;
|
|
30
|
+
const allowRemote = options.allowRemote ?? false;
|
|
31
|
+
const trustProxy = options.trustProxy ?? false;
|
|
32
|
+
let logger = options.logger ?? consoleLogger;
|
|
33
|
+
const log = { info: (m) => logger.info(m), warn: (m) => logger.warn(m), error: (m) => (logger.error ?? logger.warn)(m) };
|
|
34
|
+
|
|
35
|
+
/** What the page's `start()` gets. `reload`: reload after the agent's changes (no hot reload). */
|
|
36
|
+
const client = {
|
|
37
|
+
base: BASE,
|
|
38
|
+
token,
|
|
39
|
+
srcAttr: SRC_ATTR,
|
|
40
|
+
triggers: options.triggers ?? ['shift-click'],
|
|
41
|
+
fab: options.fab ?? true,
|
|
42
|
+
chat: options.chat ?? true,
|
|
43
|
+
reload: options.reload ?? false,
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
let session = null;
|
|
47
|
+
let api;
|
|
48
|
+
// Token for `webai mcp` (a local process, not the page); `mcp: false` turns the tools off.
|
|
49
|
+
const mcpToken = options.mcp === false || bridge ? null : randomBytes(24).toString('hex');
|
|
50
|
+
const stateFolder = path.resolve(root, stateDir);
|
|
51
|
+
if (bridge) {
|
|
52
|
+
// Dev server in a container, agents on the host (logins, ~/.claude, skills).
|
|
53
|
+
api = createProxyMiddleware({ token, bridge, root, stateDir, trustProxy });
|
|
54
|
+
} else {
|
|
55
|
+
// "Other" from another machine on the network = arbitrary command on this one: never editable from the panel.
|
|
56
|
+
const agents = resolveAgents(allowRemote ? { ...options, custom: { ...options.custom, editable: false } } : options);
|
|
57
|
+
// The page's address is only known once a page loads: then `webai mcp` can find us.
|
|
58
|
+
const onOrigin = (origin) => {
|
|
59
|
+
try {
|
|
60
|
+
if (mcpToken) writeEndpoint(stateFolder, { url: loopbackUrl(origin), token: mcpToken });
|
|
61
|
+
} catch (err) {
|
|
62
|
+
log.warn(`webai: MCP endpoint not written: ${err.message}`);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
session = new AgentSession({ root, agents, stateDir, logger: log, onOrigin });
|
|
66
|
+
api = createMiddleware(session, token, { allowRemote, trustProxy, mcpToken });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const boot = `import { start } from '${BASE}/client.js';\nstart(${JSON.stringify(client)});\n`;
|
|
70
|
+
const script = (res, body) => {
|
|
71
|
+
res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-store' });
|
|
72
|
+
res.end(body);
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/** API and scripts under `/__webai/`; everything else goes on to `next`. */
|
|
76
|
+
const middleware = (req, res, next) => {
|
|
77
|
+
const route = routeOf(req);
|
|
78
|
+
if (req.method === 'GET' && route === '/client.js') return script(res, fs.readFileSync(CLIENT_FILE));
|
|
79
|
+
if (req.method === 'GET' && route === '/boot.js') {
|
|
80
|
+
// It carries the token: only for this site's own pages.
|
|
81
|
+
if (!pageAllowed(req, { allowRemote, trustProxy })) return json(res, 403, { error: 'forbidden' });
|
|
82
|
+
return script(res, boot);
|
|
83
|
+
}
|
|
84
|
+
return api(req, res, next);
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
return {
|
|
88
|
+
root,
|
|
89
|
+
token,
|
|
90
|
+
client,
|
|
91
|
+
session,
|
|
92
|
+
middleware,
|
|
93
|
+
/** Middleware that adds the overlay to every HTML page the next handlers send. */
|
|
94
|
+
injector: htmlTransformer((html) => injectHtml(html, BOOT_TAG)),
|
|
95
|
+
setLogger(next) {
|
|
96
|
+
logger = next;
|
|
97
|
+
},
|
|
98
|
+
/** Detects the agents; resolves to a line for the terminal. */
|
|
99
|
+
async ready() {
|
|
100
|
+
const how = client.triggers.join(' / ');
|
|
101
|
+
if (!bridge) {
|
|
102
|
+
await session.detect();
|
|
103
|
+
return `AI overlay active: ${how} on a page element. Agents: ${describeAgents(session)}.`;
|
|
104
|
+
}
|
|
105
|
+
const state = await fetch(new URL(`${BASE}/health`, bridge), { signal: AbortSignal.timeout(1500) })
|
|
106
|
+
.then((r) => r.json())
|
|
107
|
+
.catch(() => null);
|
|
108
|
+
return `AI overlay active: ${how} on a page element. Agents via bridge ${bridge}`
|
|
109
|
+
+ (state ? `: ${state.agents}.` : ', which is not running yet (on the host: npx webai bridge).');
|
|
110
|
+
},
|
|
111
|
+
dispose() {
|
|
112
|
+
session?.dispose();
|
|
113
|
+
if (mcpToken) removeEndpoint(stateFolder, mcpToken);
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
}
|
package/src/history.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
const MAX_VERSIONS = 200;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Versions of the project's files, one per agent answer (and one for your own
|
|
9
|
+
* edits in between), to step back and forward through. Kept in a git repository
|
|
10
|
+
* of its own (`.webai/history.git`, its own index), so the project's repository,
|
|
11
|
+
* its index and its history are never touched. The project's .gitignore applies;
|
|
12
|
+
* `.webai/`, `node_modules/`, `dist/` and `.astro/` are always left out.
|
|
13
|
+
*
|
|
14
|
+
* Going back and then letting the agent change something drops the versions after
|
|
15
|
+
* it, as in an editor's undo; your own edits are never dropped.
|
|
16
|
+
*/
|
|
17
|
+
export class History {
|
|
18
|
+
constructor(root, stateDir) {
|
|
19
|
+
this.root = root;
|
|
20
|
+
this.dir = path.join(stateDir, 'history.git');
|
|
21
|
+
this.file = path.join(stateDir, 'history.json');
|
|
22
|
+
try {
|
|
23
|
+
this.state = JSON.parse(fs.readFileSync(this.file, 'utf8'));
|
|
24
|
+
} catch {
|
|
25
|
+
this.state = { versions: [], current: -1 };
|
|
26
|
+
}
|
|
27
|
+
this.enabled = true;
|
|
28
|
+
try {
|
|
29
|
+
if (!fs.existsSync(path.join(this.dir, 'HEAD'))) {
|
|
30
|
+
fs.mkdirSync(this.dir, { recursive: true });
|
|
31
|
+
execFileSync('git', ['init', '--quiet'], { cwd: this.root, stdio: 'ignore', env: { ...process.env, GIT_DIR: this.dir } });
|
|
32
|
+
}
|
|
33
|
+
fs.mkdirSync(path.join(this.dir, 'info'), { recursive: true });
|
|
34
|
+
fs.writeFileSync(path.join(this.dir, 'info', 'exclude'), '.webai/\nnode_modules/\ndist/\n.astro/\n');
|
|
35
|
+
} catch {
|
|
36
|
+
this.enabled = false; // no git: no history, everything else works
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
git(args) {
|
|
41
|
+
return execFileSync('git', args, {
|
|
42
|
+
cwd: this.root,
|
|
43
|
+
encoding: 'utf8',
|
|
44
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
45
|
+
env: {
|
|
46
|
+
...process.env,
|
|
47
|
+
GIT_DIR: this.dir,
|
|
48
|
+
GIT_WORK_TREE: this.root,
|
|
49
|
+
GIT_INDEX_FILE: path.join(this.dir, 'webai-index'),
|
|
50
|
+
GIT_AUTHOR_NAME: 'webai',
|
|
51
|
+
GIT_AUTHOR_EMAIL: 'webai@localhost',
|
|
52
|
+
GIT_COMMITTER_NAME: 'webai',
|
|
53
|
+
GIT_COMMITTER_EMAIL: 'webai@localhost',
|
|
54
|
+
},
|
|
55
|
+
}).trim();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The tree of the files as they are now. */
|
|
59
|
+
tree() {
|
|
60
|
+
this.git(['add', '-A', '--', '.']);
|
|
61
|
+
return this.git(['write-tree']);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A new version when the files differ from the current one; null when they don't.
|
|
66
|
+
* `keep`: append after the last version instead of dropping the ones after the current.
|
|
67
|
+
*/
|
|
68
|
+
snapshot(label, { keep = false } = {}) {
|
|
69
|
+
if (!this.enabled) return null;
|
|
70
|
+
const tree = this.tree();
|
|
71
|
+
const current = this.state.versions[this.state.current];
|
|
72
|
+
if (current?.tree === tree) return null;
|
|
73
|
+
const sha = this.git(['commit-tree', tree, ...(current ? ['-p', current.sha] : []), '-m', label || 'version']);
|
|
74
|
+
const kept = keep ? this.state.versions : this.state.versions.slice(0, this.state.current + 1);
|
|
75
|
+
const versions = [...kept, { sha, tree, label: String(label).slice(0, 200), ts: Date.now() }].slice(-MAX_VERSIONS);
|
|
76
|
+
// A ref per version keeps its objects from git's garbage collection.
|
|
77
|
+
this.git(['update-ref', `refs/webai/${versions.length - 1}`, sha]);
|
|
78
|
+
this.state = { versions, current: versions.length - 1 };
|
|
79
|
+
this.save();
|
|
80
|
+
return this.list();
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The files as they were in version `index`; your edits since the current version are kept as a version first. */
|
|
84
|
+
restore(index) {
|
|
85
|
+
if (!this.enabled) throw new Error('No version history: git is not available.');
|
|
86
|
+
const target = this.state.versions[index];
|
|
87
|
+
if (!target) throw new Error(`No version ${index}.`);
|
|
88
|
+
const before = this.state.current;
|
|
89
|
+
// Edits since the current version are kept as a version of their own at the end.
|
|
90
|
+
if (this.state.versions[before]?.tree !== this.tree()) this.snapshot('Your edits', { keep: true });
|
|
91
|
+
this.git(['read-tree', '-u', '--reset', target.tree]);
|
|
92
|
+
this.state.current = index;
|
|
93
|
+
this.save();
|
|
94
|
+
return this.list();
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
list() {
|
|
98
|
+
return {
|
|
99
|
+
enabled: this.enabled,
|
|
100
|
+
current: this.state.current,
|
|
101
|
+
versions: this.state.versions.map(({ label, ts }, i) => ({ index: i, label, ts })),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
save() {
|
|
106
|
+
fs.writeFileSync(this.file, JSON.stringify(this.state));
|
|
107
|
+
}
|
|
108
|
+
}
|
package/src/html.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// HTML helpers shared by the CLI, the framework plugins and the browser demo:
|
|
2
|
+
// no Node dependencies.
|
|
3
|
+
|
|
4
|
+
export const SRC_ATTR = 'data-webai-src';
|
|
5
|
+
|
|
6
|
+
const SKIP = new Set(['html', 'head', 'meta', 'link', 'title', 'base', 'script', 'style', 'noscript', 'template', 'br']);
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Adds `data-webai-src="file:line:column"` to every element of a static HTML
|
|
10
|
+
* file, as the Astro plugin does for templates. Attributes are inserted without
|
|
11
|
+
* new lines, so line numbers match the source.
|
|
12
|
+
*/
|
|
13
|
+
export function annotateHtml(html, file = 'index.html') {
|
|
14
|
+
let out = '';
|
|
15
|
+
let last = 0;
|
|
16
|
+
let line = 1;
|
|
17
|
+
let lineStart = 0;
|
|
18
|
+
const count = (from, to) => {
|
|
19
|
+
for (let i = from; i < to; i++) {
|
|
20
|
+
if (html[i] === '\n') {
|
|
21
|
+
line++;
|
|
22
|
+
lineStart = i + 1;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
const re = /<!--[\s\S]*?-->|<(script|style)\b[\s\S]*?<\/\1\s*>|<([a-zA-Z][\w-]*)/g;
|
|
27
|
+
for (let m; (m = re.exec(html)); ) {
|
|
28
|
+
count(last, m.index);
|
|
29
|
+
const tag = m[2]?.toLowerCase();
|
|
30
|
+
const end = m.index + m[0].length;
|
|
31
|
+
out += html.slice(last, end);
|
|
32
|
+
if (tag && !SKIP.has(tag)) out += ` ${SRC_ATTR}="${file}:${line}:${m.index - lineStart + 1}"`;
|
|
33
|
+
count(m.index, end);
|
|
34
|
+
last = end;
|
|
35
|
+
}
|
|
36
|
+
return out + html.slice(last);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** `snippet` before the last `</body>`, or at the end when there is none. */
|
|
40
|
+
export function injectHtml(html, snippet) {
|
|
41
|
+
const at = html.toLowerCase().lastIndexOf('</body>');
|
|
42
|
+
return at < 0 ? html + snippet : html.slice(0, at) + snippet + html.slice(at);
|
|
43
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
|
|
3
|
+
export type Trigger = 'shift-click' | 'alt-click' | 'contextmenu';
|
|
4
|
+
|
|
5
|
+
export interface ClaudeOptions {
|
|
6
|
+
/** Executable, default `claude`. */
|
|
7
|
+
bin?: string;
|
|
8
|
+
model?: string;
|
|
9
|
+
/** Default `acceptEdits`: the agent may edit files; anything else (Bash, MCP tools) asks in the panel. */
|
|
10
|
+
permissionMode?: 'default' | 'acceptEdits' | 'plan' | 'bypassPermissions' | (string & {});
|
|
11
|
+
/** Tools allowed without asking, e.g. `['Bash(npm run check)']`. */
|
|
12
|
+
allowedTools?: string[];
|
|
13
|
+
/**
|
|
14
|
+
* Ask in the panel (Allow / Deny) before a tool that isn't allowed. Default `true`, bridge `false`.
|
|
15
|
+
* `false`: such calls are denied, and Bash isn't offered unless `allowedTools` has an entry for it.
|
|
16
|
+
*/
|
|
17
|
+
interactive?: boolean;
|
|
18
|
+
/** Load skills and subagents from `@jantcz/webai/agents` (`--plugin-dir`). Default `true`. */
|
|
19
|
+
skills?: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* Load settings and MCP servers from the project (`.claude/`, `.mcp.json`).
|
|
22
|
+
* Default `true`, bridge `false`: the container can write to the project too.
|
|
23
|
+
*/
|
|
24
|
+
projectSettings?: boolean;
|
|
25
|
+
extraArgs?: string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface CodexOptions {
|
|
29
|
+
bin?: string;
|
|
30
|
+
model?: string;
|
|
31
|
+
/** Models offered in the panel. */
|
|
32
|
+
models?: string[];
|
|
33
|
+
/** Default `workspace-write`. */
|
|
34
|
+
sandbox?: 'read-only' | 'workspace-write' | (string & {});
|
|
35
|
+
extraArgs?: string[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface GeminiOptions {
|
|
39
|
+
bin?: string;
|
|
40
|
+
model?: string;
|
|
41
|
+
/** Default `auto_edit`. */
|
|
42
|
+
approvalMode?: 'default' | 'auto_edit' | 'plan' | (string & {});
|
|
43
|
+
extraArgs?: string[];
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Agent in a container: `docker compose run --rm <service> <cli> …` per message. */
|
|
47
|
+
export interface DockerTarget {
|
|
48
|
+
/** Service in docker-compose.yml. */
|
|
49
|
+
service: string;
|
|
50
|
+
/** Project root in the container, e.g. `/workspace/examples/astro`. */
|
|
51
|
+
workdir: string;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
type ModelChoice = { value: string; label: string };
|
|
55
|
+
|
|
56
|
+
export interface OpenCodeOptions {
|
|
57
|
+
bin?: string;
|
|
58
|
+
docker?: DockerTarget;
|
|
59
|
+
/** Default `opencode/deepseek-v4.1-flash-free` (free, no account). */
|
|
60
|
+
model?: string;
|
|
61
|
+
models?: ModelChoice[];
|
|
62
|
+
/** OpenCode permissions. Default `{ edit: 'allow', bash: 'deny', webfetch: 'deny' }`. */
|
|
63
|
+
permission?: Record<string, string>;
|
|
64
|
+
extraArgs?: string[];
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface PiOptions {
|
|
68
|
+
bin?: string;
|
|
69
|
+
docker?: DockerTarget;
|
|
70
|
+
/** `provider/id`, e.g. `openrouter/poolside/laguna-s-2.1:free`. */
|
|
71
|
+
model?: string;
|
|
72
|
+
models?: ModelChoice[];
|
|
73
|
+
/** Default `read, edit, write, grep, find, ls` (no `bash`). */
|
|
74
|
+
tools?: string[];
|
|
75
|
+
/** Load skills from `@jantcz/webai/agents`. Default `true`. */
|
|
76
|
+
skills?: boolean;
|
|
77
|
+
extraArgs?: string[];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface CustomOptions {
|
|
81
|
+
/** Command for the "Other" option. Supports `{prompt}` and `{session}`. */
|
|
82
|
+
command?: string;
|
|
83
|
+
/**
|
|
84
|
+
* Whether the command can be changed in the panel. Default `false`: any script
|
|
85
|
+
* on the dev page can read the overlay's token, so an editable command means
|
|
86
|
+
* that script can run anything on this machine. Ignored with `allowRemote`.
|
|
87
|
+
*/
|
|
88
|
+
editable?: boolean;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface AgentEvent {
|
|
92
|
+
type: string;
|
|
93
|
+
[key: string]: unknown;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export type SettingSpec =
|
|
97
|
+
| { value: string; label: string; disabled?: boolean }[]
|
|
98
|
+
| { type: 'text'; label?: string; placeholder?: string; hint?: string; default?: string; readonly?: boolean }
|
|
99
|
+
/** A button; the overlay sends `POST /action { agent, action }`. */
|
|
100
|
+
| { type: 'action'; label: string; action: string; hint?: string };
|
|
101
|
+
|
|
102
|
+
export interface AgentAdapter {
|
|
103
|
+
name: string;
|
|
104
|
+
/** Name shown in the panel, default `name`. */
|
|
105
|
+
label?: string;
|
|
106
|
+
/** Executable for detection (`<bin> --version`). `null` = always available. */
|
|
107
|
+
bin: string | null;
|
|
108
|
+
versionArgs?: string[];
|
|
109
|
+
/** `true`: the overlay generates the conversation ID. `false`: the agent sends it in a `{ type: 'session', id }` event. */
|
|
110
|
+
presetSessionId: boolean;
|
|
111
|
+
/** Stdout is plain lines of text, not JSON. */
|
|
112
|
+
raw?: boolean;
|
|
113
|
+
/** Options switchable in the panel (⚙). */
|
|
114
|
+
settings?: Record<string, SettingSpec>;
|
|
115
|
+
/** Once per server run before first use, returns the created paths. */
|
|
116
|
+
prepare?(ctx: { root: string }): string[];
|
|
117
|
+
wrapPrompt?(prompt: string, ctx: { systemPrompt: string; resume: boolean }): string;
|
|
118
|
+
command(ctx: {
|
|
119
|
+
sessionId: string | null;
|
|
120
|
+
resume: boolean;
|
|
121
|
+
systemPrompt: string;
|
|
122
|
+
settings: Record<string, string>;
|
|
123
|
+
prompt: string;
|
|
124
|
+
root: string;
|
|
125
|
+
}): {
|
|
126
|
+
cmd: string;
|
|
127
|
+
args: string[];
|
|
128
|
+
stdin?: boolean;
|
|
129
|
+
promptInArgs?: boolean;
|
|
130
|
+
env?: Record<string, string>;
|
|
131
|
+
/** Runs after the agent is stopped, e.g. `docker rm -f` of the container. */
|
|
132
|
+
cleanup?: { cmd: string; args: string[] };
|
|
133
|
+
};
|
|
134
|
+
/** `ctx` lives for one run, the adapter can keep state in it. */
|
|
135
|
+
parse(line: any, ctx: { root: string; [key: string]: unknown }): AgentEvent[];
|
|
136
|
+
onExit?(exit: { code: number | null; signal: string | null }, ctx: { root: string; stderr?: string }): AgentEvent[];
|
|
137
|
+
isMissingSession?(stderr: string): boolean;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export interface BuiltInAgentOptions {
|
|
141
|
+
/**
|
|
142
|
+
* Where requests go. `kilo` (default): Kilo Gateway's free models, no key.
|
|
143
|
+
* `openrouter`: needs OPENROUTER_API_KEY (or WEBAI_API_KEY) where the dev server runs.
|
|
144
|
+
* `custom`: any OpenAI-compatible endpoint (`baseUrl`), e.g. a local Ollama.
|
|
145
|
+
*/
|
|
146
|
+
provider?: 'kilo' | 'openrouter' | 'custom';
|
|
147
|
+
/** A model ID; without it the provider's default, switching to the next free model when busy. */
|
|
148
|
+
model?: string;
|
|
149
|
+
/** For `custom`, e.g. `http://localhost:11434/v1`. */
|
|
150
|
+
baseUrl?: string;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export interface WebAiOptions {
|
|
154
|
+
/** How to open the chat on an element. Default `['shift-click']`. */
|
|
155
|
+
triggers?: Trigger[];
|
|
156
|
+
/** Show the floating button. Default `true`. */
|
|
157
|
+
fab?: boolean;
|
|
158
|
+
/**
|
|
159
|
+
* Open the chat panel when an element is picked. Default `true`. With `false` a pick only
|
|
160
|
+
* selects the element (highlight, Esc clears it) and reports it to the MCP tools: for working
|
|
161
|
+
* from your own agent harness through `webai mcp`. The panel is still there behind the button.
|
|
162
|
+
*/
|
|
163
|
+
chat?: boolean;
|
|
164
|
+
/**
|
|
165
|
+
* Let a local agent harness read the browser through MCP (`npx webai mcp`): the picked
|
|
166
|
+
* element, console, live DOM. Default `true`; `false` also removes the endpoint.
|
|
167
|
+
*/
|
|
168
|
+
mcp?: boolean;
|
|
169
|
+
/**
|
|
170
|
+
* Allow the overlay from other machines too (`--host`). Default `false`:
|
|
171
|
+
* the endpoints accept only loopback and Host `localhost`/`127.0.0.1`.
|
|
172
|
+
* With `true` the command for "Other" can't be changed in the panel.
|
|
173
|
+
*/
|
|
174
|
+
allowRemote?: boolean;
|
|
175
|
+
/** Additional adapters besides the built-in ones (claude, codex, gemini, opencode, pi, webai, custom). */
|
|
176
|
+
agents?: AgentAdapter[];
|
|
177
|
+
claude?: ClaudeOptions;
|
|
178
|
+
codex?: CodexOptions;
|
|
179
|
+
gemini?: GeminiOptions;
|
|
180
|
+
opencode?: OpenCodeOptions;
|
|
181
|
+
pi?: PiOptions;
|
|
182
|
+
custom?: CustomOptions;
|
|
183
|
+
/**
|
|
184
|
+
* URL of the bridge on the host (`webai-bridge`) when the dev server runs in a container.
|
|
185
|
+
* Defaults to env `WEBAI_BRIDGE`. Agents then run on the host and agent options
|
|
186
|
+
* come from the bridge config, not from here.
|
|
187
|
+
*/
|
|
188
|
+
bridge?: string;
|
|
189
|
+
/** Where to store sessions and history, relative to the project root. Default `.webai`. */
|
|
190
|
+
stateDir?: string;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function claudeAgent(options?: ClaudeOptions): AgentAdapter;
|
|
194
|
+
export function codexAgent(options?: CodexOptions): AgentAdapter;
|
|
195
|
+
export function geminiAgent(options?: GeminiOptions): AgentAdapter;
|
|
196
|
+
export function customAgent(options?: CustomOptions): AgentAdapter;
|
|
197
|
+
export function opencodeAgent(options?: OpenCodeOptions): AgentAdapter;
|
|
198
|
+
export function piAgent(options?: PiOptions): AgentAdapter;
|
|
199
|
+
export function webaiAgent(options?: BuiltInAgentOptions): AgentAdapter;
|
|
200
|
+
export interface Logger {
|
|
201
|
+
info(message: string): void;
|
|
202
|
+
warn(message: string): void;
|
|
203
|
+
error?(message: string): void;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export interface CreateWebaiOptions extends WebAiOptions {
|
|
207
|
+
/** The project the agent edits. Default: the current directory. */
|
|
208
|
+
root?: string;
|
|
209
|
+
logger?: Logger;
|
|
210
|
+
/** Reload the page after the agent's changes, for servers without hot reload. Default `false`. */
|
|
211
|
+
reload?: boolean;
|
|
212
|
+
/** Requests come through a reverse proxy on this machine (X-Forwarded-For/-Host). Default `false`. */
|
|
213
|
+
trustProxy?: boolean;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
type Middleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => void;
|
|
217
|
+
|
|
218
|
+
export interface Webai {
|
|
219
|
+
root: string;
|
|
220
|
+
token: string;
|
|
221
|
+
/** What the overlay's `start()` gets. */
|
|
222
|
+
client: Record<string, unknown>;
|
|
223
|
+
/** The overlay's API and scripts under `/__webai/`. */
|
|
224
|
+
middleware: Middleware;
|
|
225
|
+
/** Adds the overlay's script to every HTML page the next handlers send. */
|
|
226
|
+
injector: Middleware;
|
|
227
|
+
setLogger(logger: Logger): void;
|
|
228
|
+
/** Detects the agents; resolves to a line for the terminal. */
|
|
229
|
+
ready(): Promise<string>;
|
|
230
|
+
dispose(): void;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** webai for any Node dev server, as connect middleware. */
|
|
234
|
+
export function createWebai(options?: CreateWebaiOptions): Webai;
|
|
235
|
+
/** `<script type="module" src="/__webai/boot.js"></script>` */
|
|
236
|
+
export const BOOT_TAG: string;
|
|
237
|
+
export const BASE: string;
|
|
238
|
+
export const SRC_ATTR: string;
|
|
239
|
+
/** Adds `data-webai-src="file:line:col"` to the elements of a static HTML file. */
|
|
240
|
+
export function annotateHtml(html: string, file?: string): string;
|
|
241
|
+
/** `snippet` before `</body>`. */
|
|
242
|
+
export function injectHtml(html: string, snippet: string): string;
|
|
243
|
+
export function htmlTransformer(transform: (html: string, req: IncomingMessage) => string): Middleware;
|
|
244
|
+
export function loadConfig(root: string, config?: string, logger?: Logger): Promise<WebAiOptions>;
|
package/src/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// @jantcz/webai: click an element on your site, tell an AI agent what to change.
|
|
2
|
+
// The core for any dev server; framework plugins are in `@jantcz/webai/astro`,
|
|
3
|
+
// `/vite` and `/next`, the CLI is `npx @jantcz/webai`.
|
|
4
|
+
|
|
5
|
+
export { claudeAgent, codexAgent, customAgent, geminiAgent, opencodeAgent, piAgent, webaiAgent } from './agents/index.js';
|
|
6
|
+
export { loadConfig } from './config.js';
|
|
7
|
+
export { BOOT_TAG, createWebai } from './core.js';
|
|
8
|
+
export { annotateHtml, injectHtml, SRC_ATTR } from './html.js';
|
|
9
|
+
export { htmlTransformer } from './inject.js';
|
|
10
|
+
export { BASE } from './server.js';
|
package/src/inject.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Connect middleware that passes `transform(html, req)` over every HTML page
|
|
3
|
+
* the next handlers send, whatever they are: a framework's dev server, a
|
|
4
|
+
* reverse proxy or a static file server. Other responses go through untouched,
|
|
5
|
+
* and so do compressed ones (the proxy asks its upstream for uncompressed pages).
|
|
6
|
+
*/
|
|
7
|
+
export function htmlTransformer(transform) {
|
|
8
|
+
return (req, res, next) => {
|
|
9
|
+
if (req.method !== 'GET' || !(req.headers.accept ?? '').includes('text/html')) return next();
|
|
10
|
+
const original = { writeHead: res.writeHead, write: res.write, end: res.end };
|
|
11
|
+
let head = null; // writeHead arguments, held back until we know what the body is
|
|
12
|
+
let chunks = null; // null = not decided yet, false = passing through
|
|
13
|
+
|
|
14
|
+
const restore = () => Object.assign(res, original);
|
|
15
|
+
const flushHead = () => {
|
|
16
|
+
if (head) original.writeHead.apply(res, head);
|
|
17
|
+
head = null;
|
|
18
|
+
};
|
|
19
|
+
// At the first byte of the body: from here on, either buffer the page or pass everything through.
|
|
20
|
+
const decide = () => {
|
|
21
|
+
if (chunks !== null) return;
|
|
22
|
+
if (head) {
|
|
23
|
+
const [status, reason, headers] = typeof head[1] === 'string' ? head : [head[0], undefined, head[1]];
|
|
24
|
+
for (const [k, v] of headerEntries(headers)) res.setHeader(k, v);
|
|
25
|
+
head = reason === undefined ? [status] : [status, reason];
|
|
26
|
+
}
|
|
27
|
+
const type = String(res.getHeader('content-type') ?? '');
|
|
28
|
+
if (/^text\/html\b/i.test(type) && !res.getHeader('content-encoding')) {
|
|
29
|
+
chunks = [];
|
|
30
|
+
} else {
|
|
31
|
+
chunks = false;
|
|
32
|
+
restore();
|
|
33
|
+
flushHead();
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
res.writeHead = (...args) => {
|
|
38
|
+
head = args;
|
|
39
|
+
return res;
|
|
40
|
+
};
|
|
41
|
+
res.write = (chunk, encoding, cb) => {
|
|
42
|
+
decide();
|
|
43
|
+
if (chunks === false) return res.write(chunk, encoding, cb);
|
|
44
|
+
chunks.push(toBuffer(chunk, encoding));
|
|
45
|
+
if (typeof encoding === 'function') encoding();
|
|
46
|
+
else cb?.();
|
|
47
|
+
return true;
|
|
48
|
+
};
|
|
49
|
+
res.end = (chunk, encoding, cb) => {
|
|
50
|
+
if (typeof chunk === 'function') [chunk, cb] = [undefined, chunk];
|
|
51
|
+
else if (typeof encoding === 'function') [encoding, cb] = [undefined, encoding];
|
|
52
|
+
decide();
|
|
53
|
+
if (chunks === false) return res.end(chunk, encoding, cb);
|
|
54
|
+
if (chunk != null) chunks.push(toBuffer(chunk, encoding));
|
|
55
|
+
restore();
|
|
56
|
+
const body = Buffer.from(transform(Buffer.concat(chunks).toString('utf8'), req));
|
|
57
|
+
if (!res.headersSent) {
|
|
58
|
+
res.removeHeader('content-length');
|
|
59
|
+
res.setHeader('content-length', body.length);
|
|
60
|
+
}
|
|
61
|
+
flushHead();
|
|
62
|
+
return res.end(body, cb);
|
|
63
|
+
};
|
|
64
|
+
next();
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function toBuffer(chunk, encoding) {
|
|
69
|
+
return Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, typeof encoding === 'string' ? encoding : 'utf8');
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** writeHead's headers: an object, a flat `[name, value, …]` list or `[[name, value], …]`. */
|
|
73
|
+
function headerEntries(headers) {
|
|
74
|
+
if (!headers) return [];
|
|
75
|
+
if (!Array.isArray(headers)) return Object.entries(headers);
|
|
76
|
+
if (Array.isArray(headers[0])) return headers;
|
|
77
|
+
const out = [];
|
|
78
|
+
for (let i = 0; i < headers.length; i += 2) out.push([headers[i], headers[i + 1]]);
|
|
79
|
+
return out;
|
|
80
|
+
}
|