@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
package/src/session.js
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { History } from './history.js';
|
|
6
|
+
import { buildPrompt } from './prompt.js';
|
|
7
|
+
|
|
8
|
+
const MAX_EVENTS = 1000;
|
|
9
|
+
|
|
10
|
+
const SYSTEM_PROMPT = `You are connected to a browser overlay of a website running in development.
|
|
11
|
+
The user points at an element on the rendered page and asks for a change.
|
|
12
|
+
Each message carries the element's CSS selector, its text and an HTML excerpt,
|
|
13
|
+
and, when the framework provides it, its source location (file:line:col from
|
|
14
|
+
the data-webai-src attribute). Without a source location, find the element in
|
|
15
|
+
the sources by its text, classes and structure first.
|
|
16
|
+
Make the change directly in the source files, keep the edit minimal and in
|
|
17
|
+
the style of the surrounding code. The page reloads by itself, never start
|
|
18
|
+
a dev server or a build. When done, answer briefly (one or two sentences)
|
|
19
|
+
in the user's language, saying what you changed and where.`;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Conversations with agents. Each agent (Claude, Codex, …) has its own session;
|
|
23
|
+
* switching between them doesn't discard context: going back to an agent resumes
|
|
24
|
+
* its last conversation. The event history is shared so the chat in the panel
|
|
25
|
+
* stays continuous, and it is mirrored to `.webai/`, so it survives a page reload
|
|
26
|
+
* and a dev server restart.
|
|
27
|
+
*/
|
|
28
|
+
export { buildPrompt };
|
|
29
|
+
|
|
30
|
+
export class AgentSession {
|
|
31
|
+
constructor({ root, agents, stateDir, logger }) {
|
|
32
|
+
this.root = root;
|
|
33
|
+
this.agents = agents; // { name: adapter }
|
|
34
|
+
this.logger = logger;
|
|
35
|
+
this.dir = path.resolve(root, stateDir);
|
|
36
|
+
this.events = [];
|
|
37
|
+
this.seq = 0;
|
|
38
|
+
this.listeners = new Set();
|
|
39
|
+
this.proc = null;
|
|
40
|
+
this.available = {}; // name -> version, or null when the CLI is missing
|
|
41
|
+
this.state = { sessions: {} };
|
|
42
|
+
this.settings = { agent: Object.keys(agents)[0] };
|
|
43
|
+
this.prepared = new Set(); // agents whose prepare() has already run
|
|
44
|
+
this.onExit = () => this.dispose();
|
|
45
|
+
process.on('exit', this.onExit);
|
|
46
|
+
this.load();
|
|
47
|
+
this.history = new History(root, this.dir);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A version of the files; tells the panels when there is a new one. */
|
|
51
|
+
version(label, { reload = false } = {}) {
|
|
52
|
+
try {
|
|
53
|
+
const list = this.history.snapshot(label);
|
|
54
|
+
if (list) this.emit({ type: 'history', current: list.current, count: list.versions.length, reload });
|
|
55
|
+
} catch (err) {
|
|
56
|
+
this.logger?.warn?.(`webai: version history: ${err.message}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Back or forward to a version of the files (not while the agent works). */
|
|
61
|
+
restoreVersion(index) {
|
|
62
|
+
if (this.busy) throw Object.assign(new Error('The agent is still working.'), { status: 409 });
|
|
63
|
+
const list = this.history.restore(Number(index));
|
|
64
|
+
const v = list.versions[list.current];
|
|
65
|
+
this.emit({ type: 'status', text: `Version ${list.current + 1} of ${list.versions.length}: ${v.label}` });
|
|
66
|
+
this.emit({ type: 'history', current: list.current, count: list.versions.length, reload: true });
|
|
67
|
+
return list;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
get busy() {
|
|
71
|
+
return this.proc != null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
get agent() {
|
|
75
|
+
return this.agents[this.settings.agent];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The current agent's session. */
|
|
79
|
+
get current() {
|
|
80
|
+
const name = this.settings.agent;
|
|
81
|
+
this.state.sessions[name] ??= this.freshSession();
|
|
82
|
+
return this.state.sessions[name];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
freshSession() {
|
|
86
|
+
return { sessionId: this.agent.presetSessionId ? randomUUID() : null, started: false, totalCostUsd: 0 };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
load() {
|
|
90
|
+
const read = (file) => {
|
|
91
|
+
try {
|
|
92
|
+
return JSON.parse(fs.readFileSync(path.join(this.dir, file), 'utf8'));
|
|
93
|
+
} catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
const settings = read('settings.json');
|
|
98
|
+
if (settings) this.settings = this.sanitize(settings);
|
|
99
|
+
const saved = read('session.json');
|
|
100
|
+
if (saved?.sessions) this.state = saved;
|
|
101
|
+
|
|
102
|
+
const file = path.join(this.dir, 'transcript.jsonl');
|
|
103
|
+
let lines;
|
|
104
|
+
try {
|
|
105
|
+
lines = fs.readFileSync(file, 'utf8').split('\n').filter(Boolean);
|
|
106
|
+
} catch {
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
for (const line of lines.slice(-MAX_EVENTS)) {
|
|
110
|
+
try {
|
|
111
|
+
const ev = JSON.parse(line);
|
|
112
|
+
this.events.push(ev);
|
|
113
|
+
this.seq = Math.max(this.seq, ev.seq);
|
|
114
|
+
} catch {} // truncated line after a crash: skip it, the rest of the history is valid
|
|
115
|
+
}
|
|
116
|
+
// The file only grows; on startup trim it to what gets loaded anyway.
|
|
117
|
+
if (lines.length > MAX_EVENTS) fs.writeFileSync(file, this.events.map((ev) => JSON.stringify(ev) + '\n').join(''));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Detects which CLIs are installed. An unavailable agent cannot be selected. */
|
|
121
|
+
async detect() {
|
|
122
|
+
await Promise.all(
|
|
123
|
+
Object.entries(this.agents).map(async ([name, agent]) => {
|
|
124
|
+
this.available[name] = agent.bin ? await probe(agent.bin, agent.versionArgs ?? ['--version'], this.root) : 'custom command';
|
|
125
|
+
}),
|
|
126
|
+
);
|
|
127
|
+
if (!this.available[this.settings.agent]) {
|
|
128
|
+
const first = Object.keys(this.agents).find((n) => this.available[n]);
|
|
129
|
+
if (first) this.settings.agent = first;
|
|
130
|
+
}
|
|
131
|
+
return this.available;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
write(file, data) {
|
|
135
|
+
fs.mkdirSync(this.dir, { recursive: true });
|
|
136
|
+
fs.writeFileSync(path.join(this.dir, file), JSON.stringify(data, null, 2));
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
saveState() {
|
|
140
|
+
this.write('session.json', this.state);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Text deltas only stream to clients; the history gets the finished block. */
|
|
144
|
+
emit(ev) {
|
|
145
|
+
ev = { ...ev, seq: ++this.seq, ts: Date.now() };
|
|
146
|
+
if (ev.type !== 'delta') {
|
|
147
|
+
this.events.push(ev);
|
|
148
|
+
if (this.events.length > MAX_EVENTS) this.events.shift();
|
|
149
|
+
fs.mkdirSync(this.dir, { recursive: true });
|
|
150
|
+
fs.appendFileSync(path.join(this.dir, 'transcript.jsonl'), JSON.stringify(ev) + '\n');
|
|
151
|
+
}
|
|
152
|
+
for (const fn of this.listeners) fn(ev);
|
|
153
|
+
// After the agent's answer, what it changed is a version named after your message.
|
|
154
|
+
if (ev.type === 'done' && this.pendingVersion) {
|
|
155
|
+
const label = this.pendingVersion;
|
|
156
|
+
this.pendingVersion = null;
|
|
157
|
+
this.version(label, { reload: true });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
subscribe(fn) {
|
|
162
|
+
this.listeners.add(fn);
|
|
163
|
+
return () => this.listeners.delete(fn);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Accepts only registered agents and values the given adapter offers. */
|
|
167
|
+
sanitize(input) {
|
|
168
|
+
const out = { agent: this.agents[input?.agent] ? input.agent : this.settings?.agent ?? Object.keys(this.agents)[0] };
|
|
169
|
+
for (const [name, agent] of Object.entries(this.agents)) {
|
|
170
|
+
const picked = {};
|
|
171
|
+
for (const [key, spec] of Object.entries(agent.settings ?? {})) {
|
|
172
|
+
const value = input?.[name]?.[key];
|
|
173
|
+
if (!value || typeof value !== 'string' || spec.readonly) continue;
|
|
174
|
+
if (spec.type === 'text') picked[key] = value.trim().slice(0, 1000);
|
|
175
|
+
else if (spec.some((c) => c.value === value && !c.disabled)) picked[key] = value;
|
|
176
|
+
}
|
|
177
|
+
out[name] = picked;
|
|
178
|
+
}
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
setSettings(input) {
|
|
183
|
+
if (this.busy && input.agent && input.agent !== this.settings.agent) {
|
|
184
|
+
throw Object.assign(new Error('Cannot switch agents while one is working.'), { status: 409 });
|
|
185
|
+
}
|
|
186
|
+
if (input.agent && this.available[input.agent] === null) {
|
|
187
|
+
throw Object.assign(new Error(`${this.agents[input.agent].label} is not installed.`), { status: 400 });
|
|
188
|
+
}
|
|
189
|
+
const before = this.settings.agent;
|
|
190
|
+
const merged = { ...this.settings, agent: input.agent ?? before };
|
|
191
|
+
for (const name of Object.keys(this.agents)) {
|
|
192
|
+
if (input[name]) merged[name] = { ...this.settings[name], ...input[name] };
|
|
193
|
+
}
|
|
194
|
+
const previous = JSON.stringify(this.settings);
|
|
195
|
+
this.settings = this.sanitize(merged);
|
|
196
|
+
this.write('settings.json', this.settings);
|
|
197
|
+
if (JSON.stringify(this.settings) !== previous) {
|
|
198
|
+
// Settings changes from the browser (mainly the custom command) should show in the terminal too.
|
|
199
|
+
this.logger?.info(`Overlay settings: ${JSON.stringify(this.settings)}`);
|
|
200
|
+
}
|
|
201
|
+
if (this.settings.agent !== before) {
|
|
202
|
+
const resumed = this.current.started;
|
|
203
|
+
this.emit({
|
|
204
|
+
type: 'status',
|
|
205
|
+
text: `Switched to ${this.agent.label}. ${resumed ? 'Resuming its previous conversation.' : "Starting its own conversation, it doesn't know the other agents' context."}`,
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
return this.settings;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
snapshot() {
|
|
212
|
+
const agents = Object.entries(this.agents).map(([name, a]) => ({
|
|
213
|
+
name,
|
|
214
|
+
label: a.label ?? name,
|
|
215
|
+
version: this.available[name],
|
|
216
|
+
settings: a.settings ?? {},
|
|
217
|
+
}));
|
|
218
|
+
return {
|
|
219
|
+
agent: this.agent.label ?? this.settings.agent,
|
|
220
|
+
agents,
|
|
221
|
+
settings: this.settings,
|
|
222
|
+
session: { id: this.current.sessionId, started: this.current.started, totalCostUsd: this.current.totalCostUsd ?? 0 },
|
|
223
|
+
busy: this.busy,
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
send({ message, element, page }) {
|
|
228
|
+
if (this.busy) throw new Error('The agent is still working on the previous message.');
|
|
229
|
+
if (this.available[this.settings.agent] === null) throw new Error(`${this.agent.label} is not installed.`);
|
|
230
|
+
const settings = this.settings[this.settings.agent];
|
|
231
|
+
// The files before the agent touches them: the first version, or your edits since the last.
|
|
232
|
+
this.version(this.history.state.versions.length ? 'Your edits' : 'Start');
|
|
233
|
+
this.pendingVersion = message;
|
|
234
|
+
this.emit({ type: 'user', text: message, element, page, agent: this.settings.agent, settings });
|
|
235
|
+
this.run(buildPrompt({ message, element, page }), false);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
run(prompt, retried) {
|
|
239
|
+
const agent = this.agent;
|
|
240
|
+
const session = this.current;
|
|
241
|
+
const resume = session.started && session.sessionId != null;
|
|
242
|
+
this.prepare(agent);
|
|
243
|
+
const text = agent.wrapPrompt?.(prompt, { systemPrompt: SYSTEM_PROMPT, resume }) ?? prompt;
|
|
244
|
+
let spec;
|
|
245
|
+
try {
|
|
246
|
+
spec = agent.command({
|
|
247
|
+
sessionId: session.sessionId,
|
|
248
|
+
resume,
|
|
249
|
+
systemPrompt: SYSTEM_PROMPT,
|
|
250
|
+
settings: this.settings[this.settings.agent] ?? {},
|
|
251
|
+
prompt: text,
|
|
252
|
+
root: this.root,
|
|
253
|
+
});
|
|
254
|
+
} catch (err) {
|
|
255
|
+
this.emit({ type: 'done', ok: false, error: err.message });
|
|
256
|
+
return;
|
|
257
|
+
}
|
|
258
|
+
const { cmd, args, stdin, promptInArgs, env, cleanup } = spec;
|
|
259
|
+
this.emit({ type: 'status', text: `${agent.label} is working…`, busy: true });
|
|
260
|
+
const ctx = { root: this.root };
|
|
261
|
+
|
|
262
|
+
const proc = spawn(cmd, stdin || promptInArgs ? args : [...args, text], {
|
|
263
|
+
cwd: this.root,
|
|
264
|
+
env: { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1', ...env },
|
|
265
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
266
|
+
// Own process group: stop() also kills children (sh -c, pipelines).
|
|
267
|
+
detached: process.platform !== 'win32',
|
|
268
|
+
});
|
|
269
|
+
proc.cleanup = cleanup; // cleanup outside the process (container), see killGroup
|
|
270
|
+
this.proc = proc;
|
|
271
|
+
let stderr = '';
|
|
272
|
+
let buffer = '';
|
|
273
|
+
let finished = false;
|
|
274
|
+
// After "New" or stop() the old process's output no longer belongs to the conversation.
|
|
275
|
+
const current = () => this.proc === proc;
|
|
276
|
+
// An adapter or disk write error must not crash the dev server.
|
|
277
|
+
const guard = (fn) => (...a) => {
|
|
278
|
+
try {
|
|
279
|
+
fn(...a);
|
|
280
|
+
} catch (err) {
|
|
281
|
+
if (!current()) return;
|
|
282
|
+
this.proc = null;
|
|
283
|
+
killGroup(proc, 'SIGTERM');
|
|
284
|
+
this.emit({ type: 'done', ok: false, error: `Error processing output: ${err.message}` });
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
const handleLine = (line) => {
|
|
289
|
+
if (!current() || (!line && !agent.raw)) return;
|
|
290
|
+
let msg = line;
|
|
291
|
+
if (!agent.raw) {
|
|
292
|
+
try {
|
|
293
|
+
msg = JSON.parse(line);
|
|
294
|
+
} catch {
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
for (let ev of agent.parse(msg, ctx)) {
|
|
299
|
+
if (ev.type === 'session') {
|
|
300
|
+
// The agent confirmed (or assigned) the conversation ID, resume it next time.
|
|
301
|
+
session.sessionId = ev.id ?? session.sessionId;
|
|
302
|
+
session.started = true;
|
|
303
|
+
this.saveState();
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
if (ev.type === 'done') {
|
|
307
|
+
finished = true;
|
|
308
|
+
ev = this.priceTurn(ev, session);
|
|
309
|
+
}
|
|
310
|
+
this.emit(ev);
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
proc.stdout.setEncoding('utf8');
|
|
315
|
+
proc.stdout.on('data', guard((chunk) => {
|
|
316
|
+
buffer += chunk;
|
|
317
|
+
let nl;
|
|
318
|
+
while ((nl = buffer.indexOf('\n')) >= 0) {
|
|
319
|
+
const line = buffer.slice(0, nl);
|
|
320
|
+
buffer = buffer.slice(nl + 1);
|
|
321
|
+
handleLine(agent.raw ? line : line.trim());
|
|
322
|
+
}
|
|
323
|
+
}));
|
|
324
|
+
// Otherwise the last line without \n would stay in the buffer.
|
|
325
|
+
proc.stdout.on('end', guard(() => {
|
|
326
|
+
if (buffer) handleLine(agent.raw ? buffer : buffer.trim());
|
|
327
|
+
buffer = '';
|
|
328
|
+
}));
|
|
329
|
+
proc.stderr.setEncoding('utf8');
|
|
330
|
+
proc.stderr.on('data', (chunk) => (stderr += chunk));
|
|
331
|
+
|
|
332
|
+
proc.on('error', (err) => {
|
|
333
|
+
if (!current()) return;
|
|
334
|
+
this.proc = null;
|
|
335
|
+
this.emit({ type: 'done', ok: false, error: `Failed to start "${cmd}": ${err.message}` });
|
|
336
|
+
});
|
|
337
|
+
proc.on('close', guard((code, signal) => {
|
|
338
|
+
if (!current()) return;
|
|
339
|
+
this.proc = null;
|
|
340
|
+
if (!retried && resume && agent.isMissingSession?.(stderr)) {
|
|
341
|
+
// The session disappeared from disk (deleted history, another machine): start a new one.
|
|
342
|
+
Object.assign(session, this.freshSession());
|
|
343
|
+
this.saveState();
|
|
344
|
+
this.emit({ type: 'status', text: 'Previous session not found, starting a new one.' });
|
|
345
|
+
this.run(prompt, true);
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
// Claude exits cleanly with code 0 on SIGINT, so the signal may not be visible.
|
|
349
|
+
const stopped = signal != null || this.stopping === proc;
|
|
350
|
+
if (!finished && agent.onExit) {
|
|
351
|
+
ctx.stderr = stderr;
|
|
352
|
+
for (const ev of agent.onExit({ code, signal: stopped ? signal ?? 'SIGINT' : null }, ctx)) this.emit(ev);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
if (!finished) {
|
|
356
|
+
const error = stopped ? 'Stopped.' : stderr.trim().slice(-800) || `Agent exited with code ${code}.`;
|
|
357
|
+
this.emit({ type: 'done', ok: false, error });
|
|
358
|
+
}
|
|
359
|
+
}));
|
|
360
|
+
|
|
361
|
+
if (stdin) proc.stdin.end(text);
|
|
362
|
+
else proc.stdin.end();
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Once per server run: links the skills the agent looks for in the project. */
|
|
366
|
+
prepare(agent) {
|
|
367
|
+
if (!agent.prepare || this.prepared.has(agent.name)) return;
|
|
368
|
+
this.prepared.add(agent.name);
|
|
369
|
+
try {
|
|
370
|
+
const created = agent.prepare({ root: this.root });
|
|
371
|
+
if (created.length) {
|
|
372
|
+
this.emit({ type: 'status', text: `Skills for ${agent.label}: ${created.join(', ')}` });
|
|
373
|
+
this.logger?.info(`Created for ${agent.label}: ${created.join(', ')}`);
|
|
374
|
+
}
|
|
375
|
+
} catch (err) {
|
|
376
|
+
this.emit({ type: 'status', text: `Failed to prepare skills for ${agent.label}: ${err.message}` });
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** Claude reports the cumulative session cost; derive the cost of one message from it. */
|
|
381
|
+
priceTurn(ev, session) {
|
|
382
|
+
if (ev.totalCostUsd == null || ev.costUsd != null) return ev;
|
|
383
|
+
const costUsd = Math.max(0, ev.totalCostUsd - (session.totalCostUsd ?? 0));
|
|
384
|
+
session.totalCostUsd = ev.totalCostUsd;
|
|
385
|
+
this.saveState();
|
|
386
|
+
return { ...ev, costUsd };
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
stop() {
|
|
390
|
+
if (!this.proc) return false;
|
|
391
|
+
const proc = this.proc;
|
|
392
|
+
this.stopping = proc;
|
|
393
|
+
killGroup(proc, 'SIGINT');
|
|
394
|
+
setTimeout(() => proc.exitCode == null && proc.signalCode == null && killGroup(proc, 'SIGTERM'), 3000).unref();
|
|
395
|
+
return true;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** Server shutdown: the agent runs in its own process group and wouldn't exit by itself. */
|
|
399
|
+
dispose() {
|
|
400
|
+
// Synchronous: also called from process.on('exit'), where async work never finishes.
|
|
401
|
+
if (this.proc) killGroup(this.proc, 'SIGTERM', { sync: true });
|
|
402
|
+
this.proc = null;
|
|
403
|
+
process.off('exit', this.onExit);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** New conversation for all agents. */
|
|
407
|
+
reset() {
|
|
408
|
+
this.stop();
|
|
409
|
+
this.proc = null; // this discards the exiting process's output (see current() in run)
|
|
410
|
+
this.state = { sessions: {} };
|
|
411
|
+
this.saveState();
|
|
412
|
+
this.events = [];
|
|
413
|
+
fs.rmSync(path.join(this.dir, 'transcript.jsonl'), { force: true });
|
|
414
|
+
this.emit({ type: 'reset' });
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function killGroup(proc, sig, { sync = false } = {}) {
|
|
419
|
+
try {
|
|
420
|
+
// Negative PID = the whole process group (spawn with detached).
|
|
421
|
+
process.kill(process.platform === 'win32' ? proc.pid : -proc.pid, sig);
|
|
422
|
+
} catch {}
|
|
423
|
+
// Agent in a container: killing the `docker compose run` client doesn't stop the container.
|
|
424
|
+
if (proc.cleanup && !proc.cleaned) {
|
|
425
|
+
proc.cleaned = true;
|
|
426
|
+
const { cmd, args } = proc.cleanup;
|
|
427
|
+
if (sync) spawnSync(cmd, args, { stdio: 'ignore', timeout: 10000 });
|
|
428
|
+
else spawn(cmd, args, { stdio: 'ignore' }).on('error', () => {});
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
function probe(bin, args, cwd) {
|
|
433
|
+
return new Promise((resolve) => {
|
|
434
|
+
let out = '';
|
|
435
|
+
// cwd: `docker compose` looks for the compose file from the project root upwards.
|
|
436
|
+
const proc = spawn(bin, args, { cwd, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
437
|
+
// An agent in Docker starts a container, hence the longer timeout.
|
|
438
|
+
const timer = setTimeout(() => proc.kill(), 15000);
|
|
439
|
+
proc.stdout.on('data', (c) => (out += c));
|
|
440
|
+
proc.on('error', () => (clearTimeout(timer), resolve(null)));
|
|
441
|
+
proc.on('close', (code) => {
|
|
442
|
+
clearTimeout(timer);
|
|
443
|
+
if (code !== 0) return resolve(null);
|
|
444
|
+
const line = out.trim().split('\n')[0];
|
|
445
|
+
resolve(line.match(/\d+\.\d+[\w.-]*/)?.[0] ?? (line || bin));
|
|
446
|
+
});
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** "Claude Code ✓, Codex ✗, …" for the startup log. */
|
|
451
|
+
export function describeAgents(session) {
|
|
452
|
+
return Object.entries(session.agents)
|
|
453
|
+
.map(([name, a]) => `${a.label ?? name} ${session.available[name] ? '✓' : '✗'}`)
|
|
454
|
+
.join(', ');
|
|
455
|
+
}
|
package/src/static.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { annotateHtml } from './html.js';
|
|
4
|
+
|
|
5
|
+
const MIME = {
|
|
6
|
+
html: 'text/html; charset=utf-8', htm: 'text/html; charset=utf-8', css: 'text/css; charset=utf-8',
|
|
7
|
+
js: 'text/javascript; charset=utf-8', mjs: 'text/javascript; charset=utf-8', json: 'application/json',
|
|
8
|
+
svg: 'image/svg+xml', txt: 'text/plain; charset=utf-8', md: 'text/markdown; charset=utf-8', xml: 'application/xml',
|
|
9
|
+
webmanifest: 'application/manifest+json', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif',
|
|
10
|
+
webp: 'image/webp', avif: 'image/avif', ico: 'image/x-icon', woff: 'font/woff', woff2: 'font/woff2', ttf: 'font/ttf',
|
|
11
|
+
otf: 'font/otf', mp4: 'video/mp4', webm: 'video/webm', mp3: 'audio/mpeg', pdf: 'application/pdf', wasm: 'application/wasm',
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export const mimeType = (file) => MIME[path.extname(file).slice(1).toLowerCase()] ?? 'application/octet-stream';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Serves a folder of static files. HTML pages get `data-webai-src` positions
|
|
18
|
+
* (file:line:col), so the agent knows exactly where an element is. Nothing is
|
|
19
|
+
* cached: every reload shows the files as they are now.
|
|
20
|
+
*/
|
|
21
|
+
export function staticFiles(dir) {
|
|
22
|
+
dir = path.resolve(dir);
|
|
23
|
+
return (req, res) => {
|
|
24
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return send(res, 405, 'Method not allowed');
|
|
25
|
+
let rel;
|
|
26
|
+
try {
|
|
27
|
+
rel = decodeURIComponent(new URL(req.url, 'http://x').pathname);
|
|
28
|
+
} catch {
|
|
29
|
+
return send(res, 400, 'Bad request');
|
|
30
|
+
}
|
|
31
|
+
// Dotfiles (.env, .git, .webai) stay private, and nothing outside the folder is served.
|
|
32
|
+
if (rel.split('/').some((part) => part.startsWith('.'))) return send(res, 404, `Not found: ${rel}`);
|
|
33
|
+
let file = path.join(dir, rel);
|
|
34
|
+
// Defense in depth: the dotfile check above already rejects every `..` segment, so this can't trigger.
|
|
35
|
+
/* node:coverage ignore next */
|
|
36
|
+
if (!inside(dir, file)) return send(res, 403, 'Forbidden');
|
|
37
|
+
if (fs.statSync(file, { throwIfNoEntry: false })?.isDirectory()) {
|
|
38
|
+
if (!rel.endsWith('/')) return redirect(res, `${rel}/`);
|
|
39
|
+
file = path.join(file, 'index.html');
|
|
40
|
+
}
|
|
41
|
+
// Clean URLs: /about → about.html
|
|
42
|
+
if (!fs.existsSync(file) && !path.extname(file) && fs.existsSync(`${file}.html`)) file = `${file}.html`;
|
|
43
|
+
if (!fs.statSync(file, { throwIfNoEntry: false })?.isFile()) return send(res, 404, `Not found: ${rel}`);
|
|
44
|
+
if (!inside(fs.realpathSync(dir), fs.realpathSync(file))) return send(res, 403, 'Forbidden'); // a symlink out
|
|
45
|
+
|
|
46
|
+
const type = mimeType(file);
|
|
47
|
+
let body = fs.readFileSync(file);
|
|
48
|
+
if (type.startsWith('text/html')) body = annotateHtml(body.toString('utf8'), path.relative(dir, file).split(path.sep).join('/'));
|
|
49
|
+
res.writeHead(200, { 'Content-Type': type, 'Cache-Control': 'no-store' });
|
|
50
|
+
res.end(req.method === 'HEAD' ? undefined : body);
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const inside = (dir, file) => file === dir || file.startsWith(dir + path.sep);
|
|
55
|
+
|
|
56
|
+
function send(res, status, text) {
|
|
57
|
+
res.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
58
|
+
res.end(`<!doctype html><title>${status}</title><p>${text.replace(/[<>&]/g, (c) => `&#${c.charCodeAt(0)};`)}</p>`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function redirect(res, location) {
|
|
62
|
+
res.writeHead(301, { Location: encodeURI(location) });
|
|
63
|
+
res.end();
|
|
64
|
+
}
|
package/src/vite.d.ts
ADDED
package/src/vite.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { createWebai } from './core.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Vite plugin: `plugins: [webai()]` in vite.config, for React, Vue, Svelte,
|
|
5
|
+
* SvelteKit, Solid, Qwik… on Vite's dev server. Only in `vite dev`. The
|
|
6
|
+
* overlay goes into every HTML page the dev server sends, SPA or server-rendered.
|
|
7
|
+
*
|
|
8
|
+
* @param {import('./index').WebAiOptions & { root?: string }} [options]
|
|
9
|
+
* @returns {import('vite').Plugin}
|
|
10
|
+
*/
|
|
11
|
+
export default function webai(options = {}) {
|
|
12
|
+
let w = null;
|
|
13
|
+
return {
|
|
14
|
+
name: '@jantcz/webai',
|
|
15
|
+
apply: 'serve',
|
|
16
|
+
// For other plugins (and tests): the running instance, `null` before the config is resolved.
|
|
17
|
+
api: {
|
|
18
|
+
get webai() {
|
|
19
|
+
return w;
|
|
20
|
+
},
|
|
21
|
+
},
|
|
22
|
+
configResolved(config) {
|
|
23
|
+
w = createWebai({ ...options, root: options.root ?? config.root });
|
|
24
|
+
w.setLogger(viteLogger(config.logger));
|
|
25
|
+
},
|
|
26
|
+
configureServer(server) {
|
|
27
|
+
// Before Vite's own middlewares: the HTML they send passes the injector.
|
|
28
|
+
server.middlewares.use(w.middleware);
|
|
29
|
+
server.middlewares.use(w.injector);
|
|
30
|
+
w.ready().then((line) => server.config.logger.info(`[webai] ${line}`, { timestamp: true }));
|
|
31
|
+
server.httpServer?.once('close', () => w.dispose());
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function viteLogger(logger) {
|
|
37
|
+
return {
|
|
38
|
+
info: (msg) => logger.info(`[webai] ${msg}`, { timestamp: true }),
|
|
39
|
+
warn: (msg) => logger.warn(`[webai] ${msg}`, { timestamp: true }),
|
|
40
|
+
error: (msg) => logger.error(`[webai] ${msg}`, { timestamp: true }),
|
|
41
|
+
};
|
|
42
|
+
}
|