@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
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,102 @@
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 { BASE, createMiddleware, createProxyMiddleware, json, pageAllowed, routeOf } from './server.js';
10
+ import { AgentSession, describeAgents } from './session.js';
11
+
12
+ const CLIENT_FILE = fileURLToPath(new URL('./client/overlay.js', import.meta.url));
13
+
14
+ /** The tag that starts the overlay on a page. */
15
+ export const BOOT_TAG = `<script type="module" src="${BASE}/boot.js"></script>`;
16
+
17
+ /**
18
+ * webai for any dev server: the agents' session, the overlay's HTTP API and
19
+ * the overlay's script, as one connect middleware. The framework plugins
20
+ * (`/astro`, `/vite`, `/next`) and the `webai` CLI are thin layers over it.
21
+ *
22
+ * @param {import('./index').CreateWebaiOptions} [options]
23
+ */
24
+ export function createWebai(options = {}) {
25
+ const root = path.resolve(options.root ?? process.cwd());
26
+ const token = randomBytes(24).toString('hex');
27
+ const stateDir = options.stateDir ?? '.webai';
28
+ const bridge = options.bridge ?? process.env.WEBAI_BRIDGE ?? null;
29
+ const allowRemote = options.allowRemote ?? false;
30
+ const trustProxy = options.trustProxy ?? false;
31
+ let logger = options.logger ?? consoleLogger;
32
+ const log = { info: (m) => logger.info(m), warn: (m) => logger.warn(m), error: (m) => (logger.error ?? logger.warn)(m) };
33
+
34
+ /** What the page's `start()` gets. `reload`: reload after the agent's changes (no hot reload). */
35
+ const client = {
36
+ base: BASE,
37
+ token,
38
+ srcAttr: SRC_ATTR,
39
+ triggers: options.triggers ?? ['shift-click'],
40
+ fab: options.fab ?? true,
41
+ reload: options.reload ?? false,
42
+ };
43
+
44
+ let session = null;
45
+ let api;
46
+ if (bridge) {
47
+ // Dev server in a container, agents on the host (logins, ~/.claude, skills).
48
+ api = createProxyMiddleware({ token, bridge, root, stateDir, trustProxy });
49
+ } else {
50
+ // "Other" from another machine on the network = arbitrary command on this one: never editable from the panel.
51
+ const agents = resolveAgents(allowRemote ? { ...options, custom: { ...options.custom, editable: false } } : options);
52
+ session = new AgentSession({ root, agents, stateDir, logger: log });
53
+ api = createMiddleware(session, token, { allowRemote, trustProxy });
54
+ }
55
+
56
+ const boot = `import { start } from '${BASE}/client.js';\nstart(${JSON.stringify(client)});\n`;
57
+ const script = (res, body) => {
58
+ res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-store' });
59
+ res.end(body);
60
+ };
61
+
62
+ /** API and scripts under `/__webai/`; everything else goes on to `next`. */
63
+ const middleware = (req, res, next) => {
64
+ const route = routeOf(req);
65
+ if (req.method === 'GET' && route === '/client.js') return script(res, fs.readFileSync(CLIENT_FILE));
66
+ if (req.method === 'GET' && route === '/boot.js') {
67
+ // It carries the token: only for this site's own pages.
68
+ if (!pageAllowed(req, { allowRemote, trustProxy })) return json(res, 403, { error: 'forbidden' });
69
+ return script(res, boot);
70
+ }
71
+ return api(req, res, next);
72
+ };
73
+
74
+ return {
75
+ root,
76
+ token,
77
+ client,
78
+ session,
79
+ middleware,
80
+ /** Middleware that adds the overlay to every HTML page the next handlers send. */
81
+ injector: htmlTransformer((html) => injectHtml(html, BOOT_TAG)),
82
+ setLogger(next) {
83
+ logger = next;
84
+ },
85
+ /** Detects the agents; resolves to a line for the terminal. */
86
+ async ready() {
87
+ const how = client.triggers.join(' / ');
88
+ if (!bridge) {
89
+ await session.detect();
90
+ return `AI overlay active: ${how} on a page element. Agents: ${describeAgents(session)}.`;
91
+ }
92
+ const state = await fetch(new URL(`${BASE}/health`, bridge), { signal: AbortSignal.timeout(1500) })
93
+ .then((r) => r.json())
94
+ .catch(() => null);
95
+ return `AI overlay active: ${how} on a page element. Agents via bridge ${bridge}`
96
+ + (state ? `: ${state.agents}.` : ', which is not running yet (on the host: npx webai bridge).');
97
+ },
98
+ dispose() {
99
+ session?.dispose();
100
+ },
101
+ };
102
+ }
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,228 @@
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, but not run shell commands. */
10
+ permissionMode?: 'default' | 'acceptEdits' | 'plan' | 'bypassPermissions' | (string & {});
11
+ /** Extra allowed tools, e.g. `['Bash(npm run check)']`. Without a Bash entry, Bash isn't offered to the agent at all. */
12
+ allowedTools?: string[];
13
+ /** Load skills and subagents from `@jantcz/webai/agents` (`--plugin-dir`). Default `true`. */
14
+ skills?: boolean;
15
+ /**
16
+ * Load settings and MCP servers from the project (`.claude/`, `.mcp.json`).
17
+ * Default `true`, bridge `false`: the container can write to the project too.
18
+ */
19
+ projectSettings?: boolean;
20
+ extraArgs?: string[];
21
+ }
22
+
23
+ export interface CodexOptions {
24
+ bin?: string;
25
+ model?: string;
26
+ /** Models offered in the panel. */
27
+ models?: string[];
28
+ /** Default `workspace-write`. */
29
+ sandbox?: 'read-only' | 'workspace-write' | (string & {});
30
+ extraArgs?: string[];
31
+ }
32
+
33
+ export interface GeminiOptions {
34
+ bin?: string;
35
+ model?: string;
36
+ /** Default `auto_edit`. */
37
+ approvalMode?: 'default' | 'auto_edit' | 'plan' | (string & {});
38
+ extraArgs?: string[];
39
+ }
40
+
41
+ /** Agent in a container: `docker compose run --rm <service> <cli> …` per message. */
42
+ export interface DockerTarget {
43
+ /** Service in docker-compose.yml. */
44
+ service: string;
45
+ /** Project root in the container, e.g. `/workspace/examples/astro`. */
46
+ workdir: string;
47
+ }
48
+
49
+ type ModelChoice = { value: string; label: string };
50
+
51
+ export interface OpenCodeOptions {
52
+ bin?: string;
53
+ docker?: DockerTarget;
54
+ /** Default `opencode/deepseek-v4.1-flash-free` (free, no account). */
55
+ model?: string;
56
+ models?: ModelChoice[];
57
+ /** OpenCode permissions. Default `{ edit: 'allow', bash: 'deny', webfetch: 'deny' }`. */
58
+ permission?: Record<string, string>;
59
+ extraArgs?: string[];
60
+ }
61
+
62
+ export interface PiOptions {
63
+ bin?: string;
64
+ docker?: DockerTarget;
65
+ /** `provider/id`, e.g. `openrouter/poolside/laguna-s-2.1:free`. */
66
+ model?: string;
67
+ models?: ModelChoice[];
68
+ /** Default `read, edit, write, grep, find, ls` (no `bash`). */
69
+ tools?: string[];
70
+ /** Load skills from `@jantcz/webai/agents`. Default `true`. */
71
+ skills?: boolean;
72
+ extraArgs?: string[];
73
+ }
74
+
75
+ export interface CustomOptions {
76
+ /** Command for the "Other" option. Supports `{prompt}` and `{session}`. */
77
+ command?: string;
78
+ /**
79
+ * Whether the command can be changed in the panel. Default `false`: any script
80
+ * on the dev page can read the overlay's token, so an editable command means
81
+ * that script can run anything on this machine. Ignored with `allowRemote`.
82
+ */
83
+ editable?: boolean;
84
+ }
85
+
86
+ export interface AgentEvent {
87
+ type: string;
88
+ [key: string]: unknown;
89
+ }
90
+
91
+ export type SettingSpec =
92
+ | { value: string; label: string; disabled?: boolean }[]
93
+ | { type: 'text'; label?: string; placeholder?: string; hint?: string; default?: string; readonly?: boolean }
94
+ /** A button; the overlay sends `POST /action { agent, action }`. */
95
+ | { type: 'action'; label: string; action: string; hint?: string };
96
+
97
+ export interface AgentAdapter {
98
+ name: string;
99
+ /** Name shown in the panel, default `name`. */
100
+ label?: string;
101
+ /** Executable for detection (`<bin> --version`). `null` = always available. */
102
+ bin: string | null;
103
+ versionArgs?: string[];
104
+ /** `true`: the overlay generates the conversation ID. `false`: the agent sends it in a `{ type: 'session', id }` event. */
105
+ presetSessionId: boolean;
106
+ /** Stdout is plain lines of text, not JSON. */
107
+ raw?: boolean;
108
+ /** Options switchable in the panel (⚙). */
109
+ settings?: Record<string, SettingSpec>;
110
+ /** Once per server run before first use, returns the created paths. */
111
+ prepare?(ctx: { root: string }): string[];
112
+ wrapPrompt?(prompt: string, ctx: { systemPrompt: string; resume: boolean }): string;
113
+ command(ctx: {
114
+ sessionId: string | null;
115
+ resume: boolean;
116
+ systemPrompt: string;
117
+ settings: Record<string, string>;
118
+ prompt: string;
119
+ root: string;
120
+ }): {
121
+ cmd: string;
122
+ args: string[];
123
+ stdin?: boolean;
124
+ promptInArgs?: boolean;
125
+ env?: Record<string, string>;
126
+ /** Runs after the agent is stopped, e.g. `docker rm -f` of the container. */
127
+ cleanup?: { cmd: string; args: string[] };
128
+ };
129
+ /** `ctx` lives for one run, the adapter can keep state in it. */
130
+ parse(line: any, ctx: { root: string; [key: string]: unknown }): AgentEvent[];
131
+ onExit?(exit: { code: number | null; signal: string | null }, ctx: { root: string; stderr?: string }): AgentEvent[];
132
+ isMissingSession?(stderr: string): boolean;
133
+ }
134
+
135
+ export interface BuiltInAgentOptions {
136
+ /**
137
+ * Where requests go. `kilo` (default): Kilo Gateway's free models, no key.
138
+ * `openrouter`: needs OPENROUTER_API_KEY (or WEBAI_API_KEY) where the dev server runs.
139
+ * `custom`: any OpenAI-compatible endpoint (`baseUrl`), e.g. a local Ollama.
140
+ */
141
+ provider?: 'kilo' | 'openrouter' | 'custom';
142
+ /** A model ID; without it the provider's default, switching to the next free model when busy. */
143
+ model?: string;
144
+ /** For `custom`, e.g. `http://localhost:11434/v1`. */
145
+ baseUrl?: string;
146
+ }
147
+
148
+ export interface WebAiOptions {
149
+ /** How to open the chat on an element. Default `['shift-click']`. */
150
+ triggers?: Trigger[];
151
+ /** Show the floating button. Default `true`. */
152
+ fab?: boolean;
153
+ /**
154
+ * Allow the overlay from other machines too (`--host`). Default `false`:
155
+ * the endpoints accept only loopback and Host `localhost`/`127.0.0.1`.
156
+ * With `true` the command for "Other" can't be changed in the panel.
157
+ */
158
+ allowRemote?: boolean;
159
+ /** Additional adapters besides the built-in ones (claude, codex, gemini, opencode, pi, webai, custom). */
160
+ agents?: AgentAdapter[];
161
+ claude?: ClaudeOptions;
162
+ codex?: CodexOptions;
163
+ gemini?: GeminiOptions;
164
+ opencode?: OpenCodeOptions;
165
+ pi?: PiOptions;
166
+ custom?: CustomOptions;
167
+ /**
168
+ * URL of the bridge on the host (`webai-bridge`) when the dev server runs in a container.
169
+ * Defaults to env `WEBAI_BRIDGE`. Agents then run on the host and agent options
170
+ * come from the bridge config, not from here.
171
+ */
172
+ bridge?: string;
173
+ /** Where to store sessions and history, relative to the project root. Default `.webai`. */
174
+ stateDir?: string;
175
+ }
176
+
177
+ export function claudeAgent(options?: ClaudeOptions): AgentAdapter;
178
+ export function codexAgent(options?: CodexOptions): AgentAdapter;
179
+ export function geminiAgent(options?: GeminiOptions): AgentAdapter;
180
+ export function customAgent(options?: CustomOptions): AgentAdapter;
181
+ export function opencodeAgent(options?: OpenCodeOptions): AgentAdapter;
182
+ export function piAgent(options?: PiOptions): AgentAdapter;
183
+ export function webaiAgent(options?: BuiltInAgentOptions): AgentAdapter;
184
+ export interface Logger {
185
+ info(message: string): void;
186
+ warn(message: string): void;
187
+ error?(message: string): void;
188
+ }
189
+
190
+ export interface CreateWebaiOptions extends WebAiOptions {
191
+ /** The project the agent edits. Default: the current directory. */
192
+ root?: string;
193
+ logger?: Logger;
194
+ /** Reload the page after the agent's changes, for servers without hot reload. Default `false`. */
195
+ reload?: boolean;
196
+ /** Requests come through a reverse proxy on this machine (X-Forwarded-For/-Host). Default `false`. */
197
+ trustProxy?: boolean;
198
+ }
199
+
200
+ type Middleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => void;
201
+
202
+ export interface Webai {
203
+ root: string;
204
+ token: string;
205
+ /** What the overlay's `start()` gets. */
206
+ client: Record<string, unknown>;
207
+ /** The overlay's API and scripts under `/__webai/`. */
208
+ middleware: Middleware;
209
+ /** Adds the overlay's script to every HTML page the next handlers send. */
210
+ injector: Middleware;
211
+ setLogger(logger: Logger): void;
212
+ /** Detects the agents; resolves to a line for the terminal. */
213
+ ready(): Promise<string>;
214
+ dispose(): void;
215
+ }
216
+
217
+ /** webai for any Node dev server, as connect middleware. */
218
+ export function createWebai(options?: CreateWebaiOptions): Webai;
219
+ /** `<script type="module" src="/__webai/boot.js"></script>` */
220
+ export const BOOT_TAG: string;
221
+ export const BASE: string;
222
+ export const SRC_ATTR: string;
223
+ /** Adds `data-webai-src="file:line:col"` to the elements of a static HTML file. */
224
+ export function annotateHtml(html: string, file?: string): string;
225
+ /** `snippet` before `</body>`. */
226
+ export function injectHtml(html: string, snippet: string): string;
227
+ export function htmlTransformer(transform: (html: string, req: IncomingMessage) => string): Middleware;
228
+ 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
+ }
@@ -0,0 +1,8 @@
1
+ import type { WebAiOptions } from '../index';
2
+
3
+ /** Only in `next dev`. `port`: the overlay's server beside Next.js, default 4399. */
4
+ export function withWebai<C extends object>(
5
+ nextConfig?: C | ((phase: string, ctx: object) => C | Promise<C>),
6
+ options?: WebAiOptions & { port?: number },
7
+ ): (phase: string, ctx: object) => Promise<C>;
8
+ export const DEFAULT_PORT: number;
@@ -0,0 +1,59 @@
1
+ import http from 'node:http';
2
+ import { createWebai } from '../core.js';
3
+ import { BASE } from '../server.js';
4
+
5
+ export const DEFAULT_PORT = 4399;
6
+ const KEY = Symbol.for('@jantcz/webai/next');
7
+
8
+ /**
9
+ * Next.js: `export default withWebai(nextConfig)` in next.config.mjs, plus
10
+ * `<WebaiScript />` from `@jantcz/webai/next/script` in the root layout.
11
+ * Only in `next dev`. Next.js has no hook for middleware of its own, so the
12
+ * overlay's API runs on a small server beside it (`port`, default 4399), and a
13
+ * rewrite sends `/__webai/*` there: the page and the API stay on one origin.
14
+ *
15
+ * @param {object | ((phase: string, ctx: object) => object | Promise<object>)} [nextConfig]
16
+ * @param {import('../index').WebAiOptions & { port?: number }} [options]
17
+ */
18
+ export function withWebai(nextConfig = {}, options = {}) {
19
+ return async (phase, ctx) => {
20
+ const config = typeof nextConfig === 'function' ? await nextConfig(phase, ctx) : nextConfig;
21
+ if (phase !== 'phase-development-server') return config;
22
+ const port = options.port ?? DEFAULT_PORT;
23
+ await startSidecar(port, options);
24
+ const ours = [{ source: `${BASE}/:path*`, destination: `http://127.0.0.1:${port}${BASE}/:path*` }];
25
+ return {
26
+ ...config,
27
+ async rewrites() {
28
+ const theirs = (await config.rewrites?.()) ?? [];
29
+ return Array.isArray(theirs) ? [...ours, ...theirs] : { ...theirs, beforeFiles: [...ours, ...(theirs.beforeFiles ?? [])] };
30
+ },
31
+ };
32
+ };
33
+ }
34
+
35
+ /**
36
+ * Next.js loads its config in more than one process; the first one serves the
37
+ * overlay, the others find the port taken and leave it to that one.
38
+ */
39
+ export async function startSidecar(port, options = {}) {
40
+ globalThis[KEY] ??= new Promise((resolve) => {
41
+ // Requests come through Next.js on this machine: the browser's host is in X-Forwarded-Host.
42
+ // Fast Refresh shows the changes, no reload needed.
43
+ const w = createWebai({ ...options, trustProxy: true });
44
+ const server = http.createServer((req, res) => w.middleware(req, res, () => {
45
+ res.writeHead(404);
46
+ res.end();
47
+ }));
48
+ server.once('error', (err) => {
49
+ w.dispose();
50
+ resolve(err.code === 'EADDRINUSE' ? null : Promise.reject(err));
51
+ });
52
+ server.listen(port, '127.0.0.1', async () => {
53
+ server.unref();
54
+ console.log(`[webai] ${await w.ready()}`);
55
+ resolve({ server, webai: w });
56
+ });
57
+ });
58
+ return globalThis[KEY];
59
+ }
@@ -0,0 +1,3 @@
1
+ /** The overlay's script for the root layout; nothing outside `next dev`. */
2
+ export function WebaiScript(): unknown;
3
+ export default WebaiScript;