@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.
Files changed (49) hide show
  1. package/LICENSE +135 -0
  2. package/README.md +24 -2
  3. package/agents/.claude-plugin/plugin.json +4 -0
  4. package/agents/README.md +17 -0
  5. package/agents/agents/a11y-reviewer.md +16 -0
  6. package/agents/agents/copy-editor.md +14 -0
  7. package/agents/skills/czech-copy/SKILL.md +18 -0
  8. package/agents/skills/element-edit/SKILL.md +51 -0
  9. package/agents/skills/stock-images/SKILL.md +25 -0
  10. package/agents/skills/verify-change/SKILL.md +19 -0
  11. package/agents/skills/web-styling/SKILL.md +20 -0
  12. package/bin/webai-agent.js +355 -0
  13. package/bin/webai-bridge.js +5 -0
  14. package/bin/webai.js +4 -0
  15. package/package.json +85 -4
  16. package/src/agents/claude.js +161 -0
  17. package/src/agents/codex.js +111 -0
  18. package/src/agents/custom.js +64 -0
  19. package/src/agents/docker.js +46 -0
  20. package/src/agents/gemini.js +102 -0
  21. package/src/agents/index.js +25 -0
  22. package/src/agents/opencode.js +117 -0
  23. package/src/agents/pack.js +99 -0
  24. package/src/agents/pi.js +143 -0
  25. package/src/agents/webai.js +66 -0
  26. package/src/astro/annotate.js +163 -0
  27. package/src/astro/index.d.ts +5 -0
  28. package/src/astro/index.js +40 -0
  29. package/src/bridge.js +62 -0
  30. package/src/cli.js +108 -0
  31. package/src/client/overlay.js +887 -0
  32. package/src/config.js +23 -0
  33. package/src/core.js +102 -0
  34. package/src/history.js +108 -0
  35. package/src/html.js +43 -0
  36. package/src/index.d.ts +228 -0
  37. package/src/index.js +10 -0
  38. package/src/inject.js +80 -0
  39. package/src/next/index.d.ts +8 -0
  40. package/src/next/index.js +59 -0
  41. package/src/next/script.d.ts +3 -0
  42. package/src/next/script.js +13 -0
  43. package/src/prompt.js +17 -0
  44. package/src/proxy.js +68 -0
  45. package/src/server.js +211 -0
  46. package/src/session.js +455 -0
  47. package/src/static.js +64 -0
  48. package/src/vite.d.ts +5 -0
  49. package/src/vite.js +42 -0
@@ -0,0 +1,143 @@
1
+ import path from 'node:path';
2
+ import { cleanStderr, inDocker, relPath } from './docker.js';
3
+ import { PACK_DIR } from './pack.js';
4
+
5
+ /** Default tools: read, search, edit. No `bash`, same as Claude without allowedTools. */
6
+ const TOOLS = ['read', 'edit', 'write', 'grep', 'find', 'ls'];
7
+
8
+ const TOOL_NAMES = { read: 'Read', edit: 'Edit', write: 'Write', grep: 'Grep', find: 'Glob', ls: 'LS', bash: 'Bash' };
9
+
10
+ /**
11
+ * Adapter for Pi (https://pi.dev, `@earendil-works/pi-coding-agent`).
12
+ *
13
+ * `--session-id` both creates and resumes a session, so we pick the ID ourselves
14
+ * and the same flag works for the first and later messages. Output is `--mode json`.
15
+ *
16
+ * With the `docker` option Pi runs in a container: `docker compose run --rm <service>`
17
+ * per message. The model runs on an API key (OpenRouter, MiniMax, …), so the
18
+ * container needs no logins from the host and the tools only see the mounted
19
+ * repo. Sessions survive in the service's volume.
20
+ *
21
+ * @param {object} [opts]
22
+ * @param {string} [opts.bin] default `pi`
23
+ * @param {{ service: string, workdir: string }} [opts.docker] compose service and the project root inside it
24
+ * @param {string} [opts.model] e.g. `openrouter/poolside/laguna-s-2.1:free`
25
+ * @param {{ value: string, label: string }[]} [opts.models] models offered in the panel
26
+ * @param {string[]} [opts.tools] default without `bash`
27
+ * @param {boolean} [opts.skills] load skills from `@jantcz/webai/agents`, default `true`
28
+ * @param {string[]} [opts.extraArgs]
29
+ */
30
+ export function piAgent(opts = {}) {
31
+ const bin = opts.bin ?? 'pi';
32
+ const docker = opts.docker && inDocker(opts.docker);
33
+ const run = (args) => (docker ? docker.command(bin, args) : { cmd: bin, args });
34
+
35
+ return {
36
+ name: 'pi',
37
+ label: docker ? 'Pi (Docker)' : 'Pi',
38
+ bin: docker ? 'docker' : bin,
39
+ versionArgs: run(['--version']).args,
40
+ presetSessionId: true,
41
+
42
+ settings: {
43
+ model: [
44
+ { value: '', label: opts.model ? `Default (${opts.model})` : 'Default from Pi settings' },
45
+ ...(opts.models ?? DEFAULT_MODELS),
46
+ ],
47
+ thinking: [
48
+ { value: '', label: 'Default' },
49
+ ...['off', 'low', 'medium', 'high'].map((v) => ({ value: v, label: v })),
50
+ ],
51
+ },
52
+
53
+ command({ sessionId, systemPrompt, settings = {}, prompt, root }) {
54
+ const args = [
55
+ '--mode', 'json',
56
+ '--session-id', sessionId,
57
+ '--append-system-prompt', systemPrompt,
58
+ '--tools', (opts.tools ?? TOOLS).join(','),
59
+ // Don't load project extensions, settings and MCP from `.pi/`: anyone with repo access can write to the project.
60
+ '--no-approve',
61
+ ];
62
+ const model = settings.model || opts.model;
63
+ if (model) args.push('--model', model);
64
+ if (settings.thinking) args.push('--thinking', settings.thinking);
65
+ if (opts.skills !== false) {
66
+ const skills = path.join(PACK_DIR, 'skills');
67
+ // In the container, the same path relative to the project root (the whole repo is mounted).
68
+ args.push('--skill', docker ? docker.path(skills, root) : skills);
69
+ }
70
+ args.push(...(opts.extraArgs ?? []));
71
+ // `--`: a message starting with "-" is not a flag.
72
+ args.push('--', prompt);
73
+ return { ...run(args), promptInArgs: true };
74
+ },
75
+
76
+ parse(msg, ctx) {
77
+ const base = opts.docker?.workdir ?? ctx.root;
78
+ switch (msg.type) {
79
+ case 'session':
80
+ return [{ type: 'session', id: msg.id }];
81
+ case 'message_update': {
82
+ const ev = msg.assistantMessageEvent;
83
+ return ev?.type === 'text_delta' ? [{ type: 'delta', text: ev.delta }] : [];
84
+ }
85
+ case 'message_end': {
86
+ const m = msg.message;
87
+ if (m?.role !== 'assistant') return [];
88
+ ctx.costUsd = (ctx.costUsd ?? 0) + (m.usage?.cost?.total ?? 0);
89
+ if (m.stopReason === 'error') ctx.error = m.errorMessage ?? 'Model error.';
90
+ const text = (Array.isArray(m.content) ? m.content : [])
91
+ .filter((b) => b.type === 'text')
92
+ .map((b) => b.text)
93
+ .join('')
94
+ .trim();
95
+ return text ? [{ type: 'text', text }] : [];
96
+ }
97
+ case 'tool_execution_start':
98
+ return [{ type: 'tool', id: msg.toolCallId, name: TOOL_NAMES[msg.toolName] ?? msg.toolName, summary: summarize(msg.args, base) }];
99
+ case 'tool_execution_end':
100
+ return msg.isError ? [{ type: 'tool-error', id: msg.toolCallId, text: resultText(msg.result).slice(0, 400) }] : [];
101
+ case 'auto_retry_start':
102
+ return [{ type: 'status', text: `Retrying (${msg.attempt}/${msg.maxAttempts}): ${msg.errorMessage}` }];
103
+ case 'agent_settled':
104
+ return [{
105
+ type: 'done',
106
+ ok: !msg.aborted && !ctx.error,
107
+ error: msg.aborted ? 'Stopped.' : ctx.error,
108
+ costUsd: ctx.costUsd,
109
+ }];
110
+ default:
111
+ return [];
112
+ }
113
+ },
114
+
115
+ onExit({ code, signal }, ctx) {
116
+ if (signal) return [{ type: 'done', ok: false, error: 'Stopped.' }];
117
+ // The session-creation warning is expected (`--session-id` creates it the first time).
118
+ const stderr = cleanStderr(ctx.stderr).replace(/^Warning: No project session found.*\n?/m, '').trim();
119
+ const hint = /no model|api key|not_ready|credentials/i.test(stderr)
120
+ ? '\nSet a provider key (e.g. OPENROUTER_API_KEY in .env) and a model.'
121
+ : '';
122
+ return [{ type: 'done', ok: false, error: `${stderr.slice(-600) || `Pi exited with code ${code}.`}${hint}` }];
123
+ },
124
+ };
125
+ }
126
+
127
+ /** Models for the panel. Prices and availability change, the default list is just a starting point. */
128
+ const DEFAULT_MODELS = [
129
+ { value: 'openrouter/poolside/laguna-s-2.1:free', label: 'Laguna S 2.1 (OpenRouter, free)' },
130
+ { value: 'openrouter/cohere/north-mini-code:free', label: 'North Mini Code (OpenRouter, free)' },
131
+ { value: 'openrouter/minimax/minimax-m3', label: 'MiniMax M3 (OpenRouter, cheap)' },
132
+ ];
133
+
134
+ function summarize(args = {}, base) {
135
+ return relPath(args.path ?? args.file_path, base) || String(args.pattern ?? args.command ?? '').slice(0, 160);
136
+ }
137
+
138
+ function resultText(result) {
139
+ const content = result?.content;
140
+ if (typeof content === 'string') return content;
141
+ if (Array.isArray(content)) return content.map((c) => c.text ?? '').join('\n');
142
+ return '';
143
+ }
@@ -0,0 +1,66 @@
1
+ import { fileURLToPath } from 'node:url';
2
+
3
+ const SCRIPT = fileURLToPath(new URL('../../bin/webai-agent.js', import.meta.url));
4
+
5
+ /** Free models in fallback order, best at tool use first (measured October 2026). */
6
+ const FREE = ['poolside/laguna-s-2.1:free', 'cohere/north-mini-code:free', 'nvidia/nemotron-3-ultra-550b-a55b:free', 'nvidia/nemotron-3-super-120b-a12b:free'];
7
+
8
+ /**
9
+ * Where the built-in agent sends its requests. Kilo Gateway serves free models
10
+ * without a key (from a server; browsers are blocked by CORS, which doesn't
11
+ * apply here). OpenRouter needs OPENROUTER_API_KEY (or WEBAI_API_KEY) in the
12
+ * environment of the dev server; keys never go into the project's files.
13
+ */
14
+ const PROVIDERS = {
15
+ kilo: { label: 'Kilo Gateway: free models, no key', baseUrl: 'https://ai-gateway.kilo.ai/api/v1', model: FREE[0], fallbacks: FREE },
16
+ openrouter: { label: 'OpenRouter (OPENROUTER_API_KEY)', baseUrl: 'https://openrouter.ai/api/v1', model: FREE[0], fallbacks: FREE.slice(0, 3) },
17
+ custom: { label: 'Custom OpenAI-compatible endpoint (e.g. Ollama)', baseUrl: 'http://localhost:11434/v1', model: 'qwen2.5-coder:7b', fallbacks: [] },
18
+ };
19
+
20
+ /**
21
+ * The built-in agent: no coding CLI needed, Node runs `bin/webai-agent.js`, a
22
+ * small loop over any OpenAI-compatible API with file tools on the project
23
+ * (list, search, read, edit, write, delete) and Openverse images. No shell.
24
+ *
25
+ * @param {object} [opts]
26
+ * @param {'kilo' | 'openrouter' | 'custom'} [opts.provider] default `kilo`
27
+ * @param {string} [opts.model]
28
+ * @param {string} [opts.baseUrl] for `custom`
29
+ */
30
+ export function webaiAgent(opts = {}) {
31
+ const provider = (settings) => PROVIDERS[settings.provider || opts.provider || 'kilo'] ?? PROVIDERS.kilo;
32
+ return {
33
+ name: 'webai',
34
+ label: 'Built-in (free models, OpenRouter, Ollama)',
35
+ bin: process.execPath,
36
+ versionArgs: ['--version'],
37
+ presetSessionId: true,
38
+
39
+ settings: {
40
+ provider: Object.entries(PROVIDERS).map(([value, p]) => ({ value, label: p.label })),
41
+ model: { type: 'text', label: 'Model', placeholder: FREE[0], default: '', hint: 'Empty = the provider\'s default; free models switch to the next one when busy.' },
42
+ baseUrl: { type: 'text', label: 'Endpoint URL (custom)', placeholder: PROVIDERS.custom.baseUrl, default: '', hint: 'Only for the custom provider. Ollama: http://localhost:11434/v1' },
43
+ },
44
+
45
+ command({ sessionId, resume, systemPrompt, settings = {} }) {
46
+ const p = provider(settings);
47
+ const model = settings.model?.trim() || opts.model || p.model;
48
+ const baseUrl = (p === PROVIDERS.custom && (settings.baseUrl?.trim() || opts.baseUrl)) || p.baseUrl;
49
+ const args = [SCRIPT, '--session', sessionId, '--base-url', baseUrl, '--model', model, '--system', systemPrompt];
50
+ // A model the user picked stays; the default may hand over to the next free one.
51
+ if (!settings.model?.trim() && !opts.model) args.push('--fallbacks', p.fallbacks.join(','));
52
+ if (resume) args.push('--resume');
53
+ return { cmd: process.execPath, args, stdin: true };
54
+ },
55
+
56
+ // The script already speaks the session's events.
57
+ parse(msg) {
58
+ return msg && typeof msg.type === 'string' ? [msg] : [];
59
+ },
60
+
61
+ onExit({ code, signal }, ctx) {
62
+ if (signal) return [{ type: 'done', ok: false, error: 'Stopped.' }];
63
+ return [{ type: 'done', ok: false, error: ctx.stderr?.trim().slice(-600) || `The built-in agent exited with code ${code}.` }];
64
+ },
65
+ };
66
+ }
@@ -0,0 +1,163 @@
1
+ import { createRequire } from 'node:module';
2
+ import path from 'node:path';
3
+ import { SRC_ATTR } from '../html.js';
4
+
5
+ // Elements that cannot be clicked or whose content is raw text.
6
+ const SKIP = new Set([
7
+ 'html', 'head', 'meta', 'link', 'title', 'base', 'script', 'style',
8
+ 'noscript', 'template', 'slot',
9
+ ]);
10
+
11
+ /**
12
+ * Astro 7 switched to a Rust compiler that ignores the `annotateSourceFile`
13
+ * option (data-astro-source-* attributes). So we annotate ourselves: every HTML
14
+ * element in the template gets `data-webai-src="path:line:column"`.
15
+ *
16
+ * AST offset units differ between @astrojs/compiler-rs versions (0.3: UTF-8
17
+ * bytes, 0.5: UTF-16 like JS strings). We work on a Buffer and verify each
18
+ * position by checking that `<tag` really starts there.
19
+ */
20
+ export async function loadParser(root) {
21
+ const fromRoot = createRequire(path.join(root, 'package.json'));
22
+ const fromAstro = createRequire(fromRoot.resolve('astro/package.json'));
23
+ const mod = await import(fromAstro.resolve('@astrojs/compiler-rs'));
24
+ return mod.parse;
25
+ }
26
+
27
+ export async function annotate(parse, source, relPath) {
28
+ const { ast, diagnostics } = await parse(source, {});
29
+ // Leave a broken template unannotated, Astro reports the error itself.
30
+ if (diagnostics?.some((d) => d.severity === 'error')) return null;
31
+ const buf = Buffer.from(source, 'utf8');
32
+ const lineStarts = [0];
33
+ for (let i = 0; i < buf.length; i++) if (buf[i] === 0x0a) lineStarts.push(i + 1);
34
+
35
+ const elements = [];
36
+ walk(ast.body, (node) => {
37
+ if (node.type !== 'JSXElement') return;
38
+ const open = node.openingElement;
39
+ if (open?.name?.type !== 'JSXIdentifier') return; // Foo.Bar, svg:defs
40
+ const name = open.name.name;
41
+ if (!/^[a-z]/.test(name) || SKIP.has(name)) return; // components and skipped tags
42
+ if (open.attributes.some((a) => a.name?.name === SRC_ATTR || a.name?.name === 'is:raw')) return;
43
+ elements.push({ name, offset: open.start });
44
+ });
45
+
46
+ const toByte = offsetUnits(source, buf, elements);
47
+ const inserts = [];
48
+ for (const { name, offset } of elements) {
49
+ const start = toByte(offset);
50
+ // Position can't be verified: better no annotation than a broken template.
51
+ if (!opensTag(buf, start, name)) continue;
52
+ const { line, col } = position(buf, lineStarts, start);
53
+ inserts.push({ at: start + 1 + Buffer.byteLength(name), text: ` ${SRC_ATTR}="${relPath}:${line}:${col}"` });
54
+ }
55
+ if (!inserts.length) return null;
56
+
57
+ inserts.sort((a, b) => a.at - b.at);
58
+ const parts = [];
59
+ let last = 0;
60
+ for (const { at, text } of inserts) {
61
+ parts.push(buf.subarray(last, at), Buffer.from(text));
62
+ last = at;
63
+ }
64
+ parts.push(buf.subarray(last));
65
+ return Buffer.concat(parts).toString('utf8');
66
+ }
67
+
68
+ /** `<name` starts at the position and the name ends right after it (not `<p` from `<pre`). */
69
+ function opensTag(buf, at, name) {
70
+ const end = at + 1 + Buffer.byteLength(name);
71
+ return buf.toString('utf8', at, end) === `<${name}` && /[\s/>]/.test(String.fromCharCode(buf[end]));
72
+ }
73
+
74
+ /**
75
+ * Decides once per file whether offsets are in bytes or in UTF-16.
76
+ * The deciding element is the first one where the two readings differ (non-ASCII
77
+ * text precedes it) and exactly one of them matches. If they never differ, both are the same.
78
+ */
79
+ function offsetUnits(source, buf, elements) {
80
+ const map = utf16ByteMap(source);
81
+ const fromUtf16 = (o) => map[o] ?? -1;
82
+ for (const { name, offset } of elements) {
83
+ if (fromUtf16(offset) === offset) continue;
84
+ const asBytes = opensTag(buf, offset, name);
85
+ const asUtf16 = opensTag(buf, fromUtf16(offset), name);
86
+ if (asBytes !== asUtf16) return asBytes ? (o) => o : fromUtf16;
87
+ }
88
+ return (o) => o;
89
+ }
90
+
91
+ /** UTF-16 index → UTF-8 byte offset */
92
+ function utf16ByteMap(source) {
93
+ const map = new Uint32Array(source.length + 1);
94
+ let bytes = 0;
95
+ for (let i = 0; i < source.length; i++) {
96
+ map[i] = bytes;
97
+ const c = source.charCodeAt(i);
98
+ if (c < 0x80) bytes += 1;
99
+ else if (c < 0x800) bytes += 2;
100
+ else if (c >= 0xd800 && c <= 0xdbff) {
101
+ bytes += 4; // surrogate pair = 4 bytes, the second half adds nothing
102
+ map[++i] = bytes;
103
+ } else bytes += 3;
104
+ }
105
+ map[source.length] = bytes;
106
+ return map;
107
+ }
108
+
109
+ function position(buf, lineStarts, offset) {
110
+ let lo = 0;
111
+ let hi = lineStarts.length - 1;
112
+ while (lo < hi) {
113
+ const mid = (lo + hi + 1) >> 1;
114
+ if (lineStarts[mid] <= offset) lo = mid;
115
+ else hi = mid - 1;
116
+ }
117
+ // Column in characters, as editors show it.
118
+ return { line: lo + 1, col: buf.toString('utf8', lineStarts[lo], offset).length + 1 };
119
+ }
120
+
121
+ function walk(node, visit) {
122
+ if (Array.isArray(node)) {
123
+ for (const n of node) walk(n, visit);
124
+ return;
125
+ }
126
+ if (!node || typeof node !== 'object') return;
127
+ if (node.type) visit(node);
128
+ for (const key in node) {
129
+ const value = node[key];
130
+ if (value && typeof value === 'object') walk(value, visit);
131
+ }
132
+ }
133
+
134
+ /** Vite plugin that annotates .astro files before Astro compiles them. */
135
+ export function annotatePlugin({ root }) {
136
+ let parse;
137
+ return {
138
+ name: 'webai:astro-annotate',
139
+ apply: 'serve',
140
+ enforce: 'pre',
141
+ transform: {
142
+ order: 'pre',
143
+ async handler(code, id) {
144
+ if (id.includes('?') || !id.endsWith('.astro') || id.includes('/node_modules/')) return;
145
+ if (parse === false) return;
146
+ try {
147
+ parse ??= await loadParser(root);
148
+ } catch (err) {
149
+ parse = false; // Astro without @astrojs/compiler-rs (< 7): overlay works, just without source positions
150
+ this.warn(`webai: annotations disabled, cannot load parser (${err.message})`);
151
+ return;
152
+ }
153
+ const rel = path.relative(root, id).split(path.sep).join('/');
154
+ try {
155
+ const out = await annotate(parse, code, rel);
156
+ return out == null ? undefined : { code: out, map: null };
157
+ } catch {
158
+ return; // Astro reports the parser error during its own compilation
159
+ }
160
+ },
161
+ },
162
+ };
163
+ }
@@ -0,0 +1,5 @@
1
+ import type { AstroIntegration } from 'astro';
2
+ import type { WebAiOptions } from '../index';
3
+
4
+ /** Astro integration, only in `astro dev`. */
5
+ export default function webai(options?: WebAiOptions): AstroIntegration;
@@ -0,0 +1,40 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import { createWebai } from '../core.js';
3
+ import { annotatePlugin } from './annotate.js';
4
+
5
+ /**
6
+ * Astro integration: `integrations: [webai()]` in astro.config. Only in
7
+ * `astro dev`; the build has no trace of it. Templates get their exact source
8
+ * positions from Astro's own compiler.
9
+ *
10
+ * @param {import('../index').WebAiOptions} [options]
11
+ * @returns {import('astro').AstroIntegration}
12
+ */
13
+ export default function webai(options = {}) {
14
+ let w = null;
15
+ return {
16
+ name: '@jantcz/webai',
17
+ hooks: {
18
+ 'astro:config:setup'({ command, config, updateConfig, injectScript }) {
19
+ if (command !== 'dev') return;
20
+ const root = fileURLToPath(config.root);
21
+ w = createWebai({ ...options, root });
22
+ updateConfig({ vite: { plugins: [annotatePlugin({ root })] } });
23
+ injectScript('page', `import { start } from '@jantcz/webai/client'; start(${JSON.stringify(w.client)});`);
24
+ },
25
+
26
+ async 'astro:server:setup'({ server, logger }) {
27
+ if (!w) return;
28
+ w.setLogger(logger);
29
+ server.middlewares.use(w.middleware);
30
+ logger.info(await w.ready());
31
+ },
32
+
33
+ // After a config change Astro restarts the server in the same process: the old agent must not keep running.
34
+ 'astro:server:done'() {
35
+ w?.dispose();
36
+ w = null;
37
+ },
38
+ },
39
+ };
40
+ }
package/src/bridge.js ADDED
@@ -0,0 +1,62 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import http from 'node:http';
4
+ import path from 'node:path';
5
+ import { resolveAgents } from './agents/index.js';
6
+ import { CONFIG_FILE, consoleLogger, loadConfig } from './config.js';
7
+ import { BRIDGE_TOKEN_FILE, createBridgeHandler } from './server.js';
8
+ import { AgentSession, describeAgents } from './session.js';
9
+
10
+ export const DEFAULT_PORT = 4400;
11
+ export { CONFIG_FILE };
12
+
13
+ /**
14
+ * Bridge for developing in Docker: the dev server runs in a container, agents
15
+ * (claude, codex, …) on the host, where their logins and configuration live.
16
+ * The bridge holds the whole conversation; the container only forwards overlay requests.
17
+ *
18
+ * The token is written to `<root>/.webai/bridge-token`. The project is mounted
19
+ * into the container, so the dev server can read it. Agent commands are set by
20
+ * the config on the host; the container sends only the prompt through the API.
21
+ *
22
+ * The container can still write to the project, including `.claude/settings.json`
23
+ * (hooks, allowed commands) or `.mcp.json`. Claude on the host therefore runs only
24
+ * with user settings (`--setting-sources user`, `--strict-mcp-config`).
25
+ */
26
+ export async function startBridge({ root, port = DEFAULT_PORT, host = '127.0.0.1', config, logger = consoleLogger }) {
27
+ root = path.resolve(root);
28
+ const options = await loadConfig(root, config, logger);
29
+ const stateDir = options.stateDir ?? '.webai';
30
+ const agents = resolveAgents({
31
+ ...options,
32
+ // A custom command from the browser would mean an arbitrary command on the host.
33
+ custom: { editable: false, ...options.custom },
34
+ claude: { projectSettings: false, ...options.claude },
35
+ });
36
+ const session = new AgentSession({ root, agents, stateDir, logger });
37
+ await session.detect();
38
+
39
+ const token = randomBytes(24).toString('hex');
40
+ const server = http.createServer(createBridgeHandler(session, token, () => describeAgents(session)));
41
+ await new Promise((resolve, reject) => {
42
+ server.once('error', (err) => (session.dispose(), reject(err)));
43
+ server.listen(port, host, resolve);
44
+ });
45
+ // Only after a successful listen: a failed second bridge must not overwrite the running one's token.
46
+ const tokenFile = path.join(root, stateDir, BRIDGE_TOKEN_FILE);
47
+ fs.mkdirSync(path.dirname(tokenFile), { recursive: true });
48
+ fs.rmSync(tokenFile, { force: true }); // mode only applies to a newly created file
49
+ fs.writeFileSync(tokenFile, token + '\n', { mode: 0o600 });
50
+ logger.info(`Bridge for ${root} on http://${host}:${server.address().port}. Agents: ${describeAgents(session)}.`);
51
+
52
+ const close = () => {
53
+ session.dispose();
54
+ try {
55
+ // Only if the token is still ours (another bridge may have overwritten it meanwhile).
56
+ if (fs.readFileSync(tokenFile, 'utf8').trim() === token) fs.rmSync(tokenFile);
57
+ } catch {}
58
+ server.close();
59
+ server.closeAllConnections();
60
+ };
61
+ return { server, session, close };
62
+ }
package/src/cli.js ADDED
@@ -0,0 +1,108 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import http from 'node:http';
4
+ import path from 'node:path';
5
+ import { parseArgs } from 'node:util';
6
+ import { DEFAULT_PORT as BRIDGE_PORT, startBridge } from './bridge.js';
7
+ import { CONFIG_FILE, consoleLogger, loadConfig } from './config.js';
8
+ import { createWebai } from './core.js';
9
+ import { proxyTo } from './proxy.js';
10
+ import { staticFiles } from './static.js';
11
+
12
+ export const DEFAULT_PORT = 4300;
13
+
14
+ export const HELP = `webai: click an element on your site, tell an AI agent what to change.
15
+
16
+ webai [dir] a folder of static files (default: the current one)
17
+ webai --target <url> a dev server that is already running, e.g. http://localhost:3000
18
+ webai bridge agents on this machine for a dev server in a container
19
+
20
+ Options:
21
+ --port <n> default ${DEFAULT_PORT} (bridge: ${BRIDGE_PORT})
22
+ --host <addr> default 127.0.0.1
23
+ --root <dir> the project the agent edits (default: the folder, or the current one with --target)
24
+ --config <file> options (default export), default <root>/${CONFIG_FILE}
25
+ --allow-remote let other machines use the overlay (in a container: the Docker network)
26
+ --open open the browser
27
+ -h, --help
28
+
29
+ Agents: Claude Code, Codex, Gemini CLI, OpenCode, Pi when installed, and the
30
+ built-in agent (free models, no key). Switch between them in the panel (⚙).`;
31
+
32
+ /** Runs the CLI; resolves to `{ url, close }` once it listens, or `null` after --help. */
33
+ export async function main(argv = process.argv.slice(2), { logger = consoleLogger, print = console.log } = {}) {
34
+ const { values, positionals } = parseArgs({
35
+ args: argv,
36
+ allowPositionals: true,
37
+ options: {
38
+ target: { type: 'string' },
39
+ port: { type: 'string' },
40
+ host: { type: 'string', default: '127.0.0.1' },
41
+ root: { type: 'string' },
42
+ config: { type: 'string' },
43
+ 'allow-remote': { type: 'boolean', default: false },
44
+ open: { type: 'boolean', default: false },
45
+ help: { type: 'boolean', short: 'h' },
46
+ },
47
+ });
48
+ if (values.help) {
49
+ print(HELP);
50
+ return null;
51
+ }
52
+
53
+ if (positionals[0] === 'bridge') {
54
+ const root = path.resolve(values.root ?? positionals[1] ?? '.');
55
+ const { server, close } = await startBridge({ root, port: Number(values.port ?? BRIDGE_PORT), host: values.host, config: values.config, logger });
56
+ return { url: `http://${values.host}:${server.address().port}`, close };
57
+ }
58
+
59
+ const dir = values.target ? null : path.resolve(positionals[0] ?? '.');
60
+ if (dir && !fs.statSync(dir, { throwIfNoEntry: false })?.isDirectory()) throw new Error(`${dir} is not a folder.`);
61
+ const root = path.resolve(values.root ?? dir ?? '.');
62
+ const options = await loadConfig(root, values.config, logger);
63
+ const w = createWebai({ ...options, root, logger, reload: true, allowRemote: values['allow-remote'] || options.allowRemote });
64
+ const handler = values.target ? proxyTo(values.target) : staticFiles(dir);
65
+
66
+ const server = http.createServer((req, res) => chain([w.middleware, w.injector], req, res, () => handler(req, res)));
67
+ if (handler.upgrade) server.on('upgrade', handler.upgrade);
68
+ const port = Number(values.port ?? DEFAULT_PORT);
69
+ await new Promise((resolve, reject) => {
70
+ server.once('error', reject);
71
+ server.listen(port, values.host, resolve);
72
+ });
73
+ const url = `http://${values.host === '0.0.0.0' ? 'localhost' : values.host}:${server.address().port}/`;
74
+ logger.info(`${values.target ? `${values.target} through` : `${dir} on`} ${url}`);
75
+ logger.info(await w.ready());
76
+ if (values.open) openBrowser(url);
77
+
78
+ const close = () => {
79
+ w.dispose();
80
+ server.close();
81
+ server.closeAllConnections();
82
+ };
83
+ return { url, close, server };
84
+ }
85
+
86
+ /** The `webai` command: runs `main`, stops on Ctrl+C, reports errors without a stack trace. */
87
+ export async function run(argv = process.argv.slice(2), { exit = process.exit, onSignal = process.on.bind(process), logger = consoleLogger } = {}) {
88
+ try {
89
+ const running = await main(argv, { logger });
90
+ for (const sig of ['SIGINT', 'SIGTERM']) onSignal(sig, () => (running?.close(), exit(0)));
91
+ return running;
92
+ } catch (err) {
93
+ logger.error(err.code === 'EADDRINUSE' ? `Port ${err.port} is in use. Choose another with --port.` : err.message);
94
+ exit(1);
95
+ return null;
96
+ }
97
+ }
98
+
99
+ /** Connect-style middlewares one after another, then `done`. */
100
+ export function chain(middlewares, req, res, done) {
101
+ const run = (i) => (i < middlewares.length ? middlewares[i](req, res, () => run(i + 1)) : done());
102
+ run(0);
103
+ }
104
+
105
+ function openBrowser(url) {
106
+ const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'explorer' : 'xdg-open';
107
+ spawn(cmd, [url], { stdio: 'ignore', detached: true }).on('error', () => {}).unref();
108
+ }