vibecode-anything 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.
Files changed (62) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +235 -2
  3. package/dist/cli.d.ts +2 -0
  4. package/dist/cli.js +452 -0
  5. package/dist/core/adapters.d.ts +8 -0
  6. package/dist/core/adapters.js +92 -0
  7. package/dist/core/diff.d.ts +10 -0
  8. package/dist/core/diff.js +207 -0
  9. package/dist/core/doctor.d.ts +50 -0
  10. package/dist/core/doctor.js +312 -0
  11. package/dist/core/errors.d.ts +32 -0
  12. package/dist/core/errors.js +81 -0
  13. package/dist/core/exec.d.ts +14 -0
  14. package/dist/core/exec.js +109 -0
  15. package/dist/core/parity.d.ts +9 -0
  16. package/dist/core/parity.js +138 -0
  17. package/dist/core/png.d.ts +7 -0
  18. package/dist/core/png.js +303 -0
  19. package/dist/core/schema.d.ts +17 -0
  20. package/dist/core/schema.js +614 -0
  21. package/dist/core/slices.d.ts +24 -0
  22. package/dist/core/slices.js +294 -0
  23. package/dist/core/store.d.ts +17 -0
  24. package/dist/core/store.js +97 -0
  25. package/dist/core/types.d.ts +751 -0
  26. package/dist/core/types.js +4 -0
  27. package/dist/core/visual.d.ts +34 -0
  28. package/dist/core/visual.js +459 -0
  29. package/dist/core/watch.d.ts +53 -0
  30. package/dist/core/watch.js +285 -0
  31. package/dist/ingestors/api-repo.d.ts +5 -0
  32. package/dist/ingestors/api-repo.js +722 -0
  33. package/dist/ingestors/bridges.d.ts +3 -0
  34. package/dist/ingestors/bridges.js +562 -0
  35. package/dist/ingestors/cli.d.ts +9 -0
  36. package/dist/ingestors/cli.js +266 -0
  37. package/dist/ingestors/image.d.ts +2 -0
  38. package/dist/ingestors/image.js +147 -0
  39. package/dist/ingestors/index.d.ts +5 -0
  40. package/dist/ingestors/index.js +97 -0
  41. package/dist/ingestors/video.d.ts +47 -0
  42. package/dist/ingestors/video.js +605 -0
  43. package/dist/ingestors/web.d.ts +25 -0
  44. package/dist/ingestors/web.js +397 -0
  45. package/dist/mcp/server.d.ts +2 -0
  46. package/dist/mcp/server.js +504 -0
  47. package/dist/oracles/api-repo.d.ts +2 -0
  48. package/dist/oracles/api-repo.js +214 -0
  49. package/dist/oracles/cli.d.ts +2 -0
  50. package/dist/oracles/cli.js +157 -0
  51. package/dist/oracles/image.d.ts +2 -0
  52. package/dist/oracles/image.js +279 -0
  53. package/dist/oracles/index.d.ts +4 -0
  54. package/dist/oracles/index.js +91 -0
  55. package/dist/oracles/video.d.ts +21 -0
  56. package/dist/oracles/video.js +411 -0
  57. package/dist/oracles/web.d.ts +2 -0
  58. package/dist/oracles/web.js +480 -0
  59. package/dist/setup/index.d.ts +7 -0
  60. package/dist/setup/index.js +186 -0
  61. package/package.json +47 -6
  62. package/skills/vibecode-anything/SKILL.md +52 -0
@@ -0,0 +1,480 @@
1
+ import { VibecodeError, errorMessage } from "../core/errors.js";
2
+ import { loadPlaywright } from "../core/adapters.js";
3
+ import { compareRegionsIoU } from "../core/visual.js";
4
+ import { extractTitle, extractAllLandmarks } from "../ingestors/web.js";
5
+ const PLAYWRIGHT_INSTALL_HINT = "npm install -D playwright && npx playwright install chromium";
6
+ function resolvePlaywright(candidate) {
7
+ if (!candidate || typeof candidate !== "object")
8
+ return null;
9
+ const mod = candidate;
10
+ if (mod.chromium && typeof mod.chromium.launch === "function") {
11
+ return mod;
12
+ }
13
+ if (mod.default?.chromium && typeof mod.default.chromium.launch === "function") {
14
+ return mod.default;
15
+ }
16
+ return null;
17
+ }
18
+ async function getPlaywright(deps) {
19
+ const explicit = Object.prototype.hasOwnProperty.call(deps, "playwright") ? deps.playwright : undefined;
20
+ if (explicit === null)
21
+ return null;
22
+ const loaded = explicit !== undefined ? explicit : await loadPlaywright(deps);
23
+ return resolvePlaywright(loaded);
24
+ }
25
+ async function launchBrowser(pw, featureName) {
26
+ try {
27
+ return await pw.chromium.launch({ headless: true });
28
+ }
29
+ catch (err) {
30
+ throw new VibecodeError("ADAPTER_MISSING", `${featureName} requires Playwright Chromium (${errorMessage(err)})`, {
31
+ adapter: "playwright",
32
+ installHint: PLAYWRIGHT_INSTALL_HINT
33
+ });
34
+ }
35
+ }
36
+ function buildUrl(base, routePath) {
37
+ if (/^https?:\/\//i.test(routePath))
38
+ return routePath;
39
+ const baseUrl = /^https?:\/\//i.test(base) ? base : `http://${base}`;
40
+ return new URL(routePath, baseUrl).toString();
41
+ }
42
+ async function fetchRoute(url, timeoutMs = 15000) {
43
+ const ctrl = new AbortController();
44
+ const t = setTimeout(() => ctrl.abort(), timeoutMs);
45
+ try {
46
+ const res = await fetch(url, { signal: ctrl.signal, redirect: "follow" });
47
+ const html = await res.text();
48
+ return { status: res.status, title: extractTitle(html), landmarks: extractAllLandmarks(html), html };
49
+ }
50
+ finally {
51
+ clearTimeout(t);
52
+ }
53
+ }
54
+ function checkLandmarks(expected, actualList) {
55
+ const failures = [];
56
+ const list = actualList || [];
57
+ const have = new Set(list.map((l) => String(l.tag).toLowerCase()));
58
+ for (const lm of expected || []) {
59
+ if (!lm || !lm.tag || lm.required === false)
60
+ continue;
61
+ const tag = String(lm.tag).toLowerCase();
62
+ if (!have.has(tag)) {
63
+ failures.push(`missing landmark <${lm.tag}>`);
64
+ continue;
65
+ }
66
+ if (lm.textContains) {
67
+ const ok = list.some((f) => String(f.tag).toLowerCase() === tag && String(f.text || "").includes(lm.textContains));
68
+ if (!ok)
69
+ failures.push(`landmark <${lm.tag}> missing text ${JSON.stringify(lm.textContains)}`);
70
+ }
71
+ }
72
+ return failures;
73
+ }
74
+ function checkStatus(expectedStatus, actualStatus) {
75
+ if (typeof expectedStatus === "number") {
76
+ return actualStatus === expectedStatus ? null : `status expected ${expectedStatus}, got ${actualStatus}`;
77
+ }
78
+ if (Array.isArray(expectedStatus) && expectedStatus.length > 0) {
79
+ return expectedStatus.includes(actualStatus)
80
+ ? null
81
+ : `status expected ${JSON.stringify(expectedStatus)}, got ${actualStatus}`;
82
+ }
83
+ return null;
84
+ }
85
+ async function verifyRouteWithFetch(invariant, ctx, deps) {
86
+ const input = invariant.input || {};
87
+ const expected = invariant.expected || {};
88
+ const url = buildUrl(ctx.target, input.path || "/");
89
+ let obs;
90
+ try {
91
+ obs = await (deps.fetchRoute || fetchRoute)(url, input.timeoutMs || 15000);
92
+ }
93
+ catch (err) {
94
+ return {
95
+ status: "fail",
96
+ score: 0,
97
+ failures: [`request failed: ${errorMessage(err)}`],
98
+ metrics: { backend: "fetch", url }
99
+ };
100
+ }
101
+ const failures = [];
102
+ const statusErr = checkStatus(expected.status, obs.status);
103
+ if (statusErr)
104
+ failures.push(statusErr);
105
+ if (expected.titleContains && !String(obs.title).includes(expected.titleContains)) {
106
+ failures.push(`title missing ${JSON.stringify(expected.titleContains)} (got ${JSON.stringify(obs.title)})`);
107
+ }
108
+ failures.push(...checkLandmarks(expected.landmarks, obs.landmarks));
109
+ return {
110
+ status: failures.length ? "fail" : "pass",
111
+ score: failures.length ? 0 : 1,
112
+ failures,
113
+ metrics: { backend: "fetch", status: obs.status, title: obs.title, landmarkCount: obs.landmarks.length }
114
+ };
115
+ }
116
+ function dedupeBoxes(boxes) {
117
+ const seen = new Set();
118
+ const out = [];
119
+ for (const b of boxes || []) {
120
+ const key = b.selector || b.id;
121
+ if (!key || seen.has(key))
122
+ continue;
123
+ seen.add(key);
124
+ out.push({ id: key, bbox: b.bbox });
125
+ }
126
+ return out;
127
+ }
128
+ async function verifyRouteWithPlaywright(invariant, ctx, _deps, pw) {
129
+ const input = invariant.input || {};
130
+ const expected = invariant.expected || {};
131
+ const url = buildUrl(ctx.target, input.path || "/");
132
+ const viewport = input.viewport || { width: 1280, height: 720 };
133
+ const browser = await launchBrowser(pw, "web_route verification");
134
+ try {
135
+ const page = await browser.newPage({ viewport });
136
+ try {
137
+ let response = null;
138
+ try {
139
+ response = await page.goto(url, { waitUntil: input.waitUntil || "networkidle", timeout: input.timeoutMs || 15000 });
140
+ }
141
+ catch (err) {
142
+ return { status: "fail", score: 0, failures: [`navigation failed: ${errorMessage(err)}`], metrics: { backend: "playwright" } };
143
+ }
144
+ const failures = [];
145
+ const status = response?.status?.() ?? 200;
146
+ const statusErr = checkStatus(expected.status, status);
147
+ if (statusErr)
148
+ failures.push(statusErr);
149
+ const title = await page.title();
150
+ if (expected.titleContains && !String(title).includes(expected.titleContains)) {
151
+ failures.push(`title missing ${JSON.stringify(expected.titleContains)} (got ${JSON.stringify(title)})`);
152
+ }
153
+ const found = await page.$$eval("header,nav,main,footer,h1,h2,form,table,ul", (nodes) => nodes.map((n) => ({ tag: n.tagName.toLowerCase(), text: (n.textContent || "").trim().slice(0, 120) }))).catch(() => []);
154
+ failures.push(...checkLandmarks(expected.landmarks, found));
155
+ const metrics = { backend: "playwright", status, title, landmarkCount: found.length };
156
+ if (Array.isArray(expected.boundingBoxes) && expected.boundingBoxes.length) {
157
+ const actualBoxes = [];
158
+ for (const item of expected.boundingBoxes) {
159
+ const sel = item.selector;
160
+ if (!sel)
161
+ continue;
162
+ const box = await page.$eval(sel, (el) => {
163
+ const r = el.getBoundingClientRect();
164
+ return { x: r.x / (window.innerWidth || 1), y: r.y / (window.innerHeight || 1), w: r.width / (window.innerWidth || 1), h: r.height / (window.innerHeight || 1) };
165
+ }).catch(() => null);
166
+ if (box &&
167
+ Number.isFinite(box.x) &&
168
+ Number.isFinite(box.y) &&
169
+ Number.isFinite(box.w) &&
170
+ Number.isFinite(box.h) &&
171
+ box.w > 0 &&
172
+ box.h > 0) {
173
+ actualBoxes.push({ selector: sel, bbox: box });
174
+ }
175
+ }
176
+ const cmp = compareRegionsIoU(dedupeBoxes(expected.boundingBoxes), dedupeBoxes(actualBoxes));
177
+ metrics.layoutIoU = cmp.meanIoU;
178
+ const minIoU = invariant.tolerance?.minLayoutIoU ?? 0.75;
179
+ if (cmp.meanIoU < minIoU)
180
+ failures.push(`layoutIoU ${cmp.meanIoU.toFixed(3)} < ${minIoU}`);
181
+ }
182
+ const score = invariant.severity === "soft" && typeof metrics.layoutIoU === "number"
183
+ ? metrics.layoutIoU
184
+ : (failures.length ? 0 : 1);
185
+ return { status: failures.length ? "fail" : "pass", score, failures, metrics };
186
+ }
187
+ finally {
188
+ try {
189
+ await page.close?.();
190
+ }
191
+ catch { /* ignore */ }
192
+ }
193
+ }
194
+ finally {
195
+ try {
196
+ await browser.close();
197
+ }
198
+ catch { /* ignore */ }
199
+ }
200
+ }
201
+ async function verifyRoute(invariant, ctx, deps) {
202
+ if (!ctx.target)
203
+ throw new VibecodeError("TARGET_MISSING", "Missing --target <url> for web verification.");
204
+ const pw = await getPlaywright(deps);
205
+ if (pw) {
206
+ try {
207
+ return await verifyRouteWithPlaywright(invariant, ctx, deps, pw);
208
+ }
209
+ catch (err) {
210
+ if (err instanceof VibecodeError && err.code !== "ADAPTER_MISSING")
211
+ throw err;
212
+ if (Array.isArray(invariant.expected?.boundingBoxes) && invariant.expected.boundingBoxes.length > 0) {
213
+ if (err instanceof VibecodeError)
214
+ throw err;
215
+ }
216
+ // fall through to fetch fallback
217
+ }
218
+ }
219
+ if (Array.isArray(invariant.expected?.boundingBoxes) && invariant.expected.boundingBoxes.length > 0) {
220
+ throw new VibecodeError("ADAPTER_MISSING", "web_route boundingBoxes verification requires Playwright", {
221
+ adapter: "playwright",
222
+ installHint: PLAYWRIGHT_INSTALL_HINT
223
+ });
224
+ }
225
+ return verifyRouteWithFetch(invariant, ctx, deps);
226
+ }
227
+ async function attachTelemetry(page) {
228
+ const network = [];
229
+ const consoleErrors = [];
230
+ const pageErrors = [];
231
+ if (typeof page.on === "function") {
232
+ page.on("response", (res) => {
233
+ try {
234
+ const parsed = new URL(res.url());
235
+ network.push({ method: res.request().method(), pathPattern: parsed.pathname, status: res.status(), contentType: res.headers()?.["content-type"] });
236
+ }
237
+ catch { /* ignore */ }
238
+ });
239
+ page.on("console", (msg) => { if (msg.type?.() === "error")
240
+ consoleErrors.push(msg.text?.() ?? String(msg)); });
241
+ page.on("pageerror", (err) => pageErrors.push(err?.message || String(err)));
242
+ }
243
+ return {
244
+ collect() {
245
+ return {
246
+ network: Array.isArray(page.__networkCalls) ? page.__networkCalls : network,
247
+ consoleErrors: Array.isArray(page.__consoleErrors) ? page.__consoleErrors : consoleErrors,
248
+ pageErrors: Array.isArray(page.__pageErrors) ? page.__pageErrors : pageErrors
249
+ };
250
+ }
251
+ };
252
+ }
253
+ async function verifyFlow(invariant, ctx, deps) {
254
+ if (!ctx.target)
255
+ throw new VibecodeError("TARGET_MISSING", "Missing --target <url> for web flow verification.");
256
+ const pw = await getPlaywright(deps);
257
+ if (!pw) {
258
+ throw new VibecodeError("ADAPTER_MISSING", "web_flow verification requires Playwright", {
259
+ adapter: "playwright",
260
+ installHint: PLAYWRIGHT_INSTALL_HINT
261
+ });
262
+ }
263
+ const input = invariant.input || {};
264
+ const expected = invariant.expected || {};
265
+ const startUrl = buildUrl(ctx.target, input.startPath || "/");
266
+ const viewport = input.viewport || { width: 1280, height: 720 };
267
+ const browser = await launchBrowser(pw, "web_flow verification");
268
+ try {
269
+ const page = await browser.newPage({ viewport });
270
+ try {
271
+ const actionPage = page;
272
+ const telemetry = await attachTelemetry(page);
273
+ const failures = [];
274
+ const navTimeoutMs = input.timeoutMs || 15000;
275
+ try {
276
+ await page.goto(startUrl, { waitUntil: input.waitUntil || "networkidle", timeout: navTimeoutMs });
277
+ }
278
+ catch (err) {
279
+ return {
280
+ status: "fail",
281
+ score: 0,
282
+ failures: [`navigation failed: ${errorMessage(err)}`],
283
+ metrics: { backend: "playwright" }
284
+ };
285
+ }
286
+ for (const step of input.steps || []) {
287
+ try {
288
+ const selector = step.selector ?? "";
289
+ const stepTimeoutMs = step.timeoutMs || input.timeoutMs || 5000;
290
+ if (step.action === "fill")
291
+ await actionPage.fill(selector, String(step.value ?? ""), { timeout: stepTimeoutMs });
292
+ else if (step.action === "click")
293
+ await actionPage.click(selector, { timeout: stepTimeoutMs });
294
+ else if (step.action === "press")
295
+ await actionPage.press(selector, step.key || "Enter", { timeout: stepTimeoutMs });
296
+ else if (step.action === "goto") {
297
+ await page.goto(buildUrl(ctx.target, step.url || step.path || "/"), {
298
+ waitUntil: step.waitUntil || "networkidle",
299
+ timeout: step.timeoutMs || input.timeoutMs || 15000
300
+ });
301
+ }
302
+ else if (step.action === "select") {
303
+ await actionPage.selectOption(selector, String(step.value ?? ""), { timeout: stepTimeoutMs });
304
+ }
305
+ else if (step.action === "waitFor") {
306
+ const timeout = step.timeoutMs || input.timeoutMs || 3000;
307
+ if (typeof page.waitForFunction === "function") {
308
+ await page.waitForFunction((txt) => Boolean(document.body && document.body.innerText.includes(txt)), String(step.text ?? step.value ?? ""), { timeout });
309
+ }
310
+ else if (typeof page.waitForTimeout === "function") {
311
+ await page.waitForTimeout(Math.min(timeout, 50));
312
+ }
313
+ }
314
+ else if (step.action === "waitForSelector") {
315
+ await page.waitForSelector(selector, { timeout: step.timeoutMs || input.timeoutMs || 3000 });
316
+ }
317
+ else {
318
+ failures.push(`unsupported flow step action: ${step.action}`);
319
+ }
320
+ }
321
+ catch (err) {
322
+ failures.push(`step ${step.action} failed: ${errorMessage(err)}`);
323
+ }
324
+ }
325
+ const finalUrl = typeof page.url === "function" ? page.url() : startUrl;
326
+ if (expected.finalUrlIncludes && !String(finalUrl).includes(expected.finalUrlIncludes)) {
327
+ failures.push(`finalUrl ${finalUrl} does not include ${expected.finalUrlIncludes}`);
328
+ }
329
+ let bodyText = "";
330
+ try {
331
+ bodyText = await page.evaluate(() => document.body ? document.body.innerText : "");
332
+ }
333
+ catch { /* ignore */ }
334
+ for (const text of expected.visibleText || []) {
335
+ if (!bodyText.includes(text))
336
+ failures.push(`visibleText missing ${JSON.stringify(text)}`);
337
+ }
338
+ for (const text of expected.hiddenText || []) {
339
+ if (bodyText.includes(text))
340
+ failures.push(`hiddenText present ${JSON.stringify(text)}`);
341
+ }
342
+ const domCounts = {};
343
+ for (const assertion of expected.domAssertions || []) {
344
+ const count = await page.$$eval(assertion.selector, (els) => els.length).catch(() => 0);
345
+ domCounts[assertion.selector] = count;
346
+ if (typeof assertion.count === "number" && count !== assertion.count) {
347
+ failures.push(`domAssertion ${assertion.selector}: expected count ${assertion.count}, found ${count}`);
348
+ }
349
+ else if (count < (assertion.minCount || 1)) {
350
+ failures.push(`domAssertion ${assertion.selector}: found ${count} < ${assertion.minCount || 1}`);
351
+ }
352
+ }
353
+ const telemetryNow = telemetry.collect();
354
+ const networkCalls = telemetryNow.network || [];
355
+ for (const expectedCall of expected.networkCalls || []) {
356
+ const method = String(expectedCall.method || "GET").toUpperCase();
357
+ let re = null;
358
+ if (expectedCall.pathPattern) {
359
+ try {
360
+ re = new RegExp(expectedCall.pathPattern);
361
+ }
362
+ catch {
363
+ failures.push(`invalid pathPattern ${expectedCall.pathPattern}`);
364
+ continue;
365
+ }
366
+ }
367
+ const match = networkCalls.find((c) => String(c.method).toUpperCase() === method && (!re || re.test(c.pathPattern)) && (expectedCall.status === undefined || c.status === expectedCall.status));
368
+ if (!match)
369
+ failures.push(`missing network call ${method} ${expectedCall.pathPattern || ""}${expectedCall.status !== undefined ? " " + expectedCall.status : ""}`);
370
+ }
371
+ if (expected.noConsoleErrors) {
372
+ for (const err of telemetryNow.consoleErrors)
373
+ failures.push(`console error: ${err}`);
374
+ }
375
+ if (expected.noUncaughtExceptions) {
376
+ for (const err of telemetryNow.pageErrors)
377
+ failures.push(`uncaught exception: ${err}`);
378
+ }
379
+ const metrics = {
380
+ backend: "playwright",
381
+ finalUrl,
382
+ visibleTextLength: bodyText.length,
383
+ domCounts,
384
+ networkCalls: networkCalls.length,
385
+ consoleErrors: telemetryNow.consoleErrors.length,
386
+ pageErrors: telemetryNow.pageErrors.length
387
+ };
388
+ return { status: failures.length ? "fail" : "pass", score: failures.length ? 0 : 1, failures, metrics };
389
+ }
390
+ finally {
391
+ try {
392
+ await page.close?.();
393
+ }
394
+ catch { /* ignore */ }
395
+ }
396
+ }
397
+ finally {
398
+ try {
399
+ await browser.close();
400
+ }
401
+ catch { /* ignore */ }
402
+ }
403
+ }
404
+ async function verifyNetwork(invariant, ctx, deps) {
405
+ if (!ctx.target)
406
+ throw new VibecodeError("TARGET_MISSING", "Missing --target <url> for web network verification.");
407
+ const pw = await getPlaywright(deps);
408
+ if (!pw) {
409
+ throw new VibecodeError("ADAPTER_MISSING", "web_network verification requires Playwright", {
410
+ adapter: "playwright",
411
+ installHint: PLAYWRIGHT_INSTALL_HINT
412
+ });
413
+ }
414
+ const input = invariant.input || {};
415
+ const expected = invariant.expected || {};
416
+ const url = buildUrl(ctx.target, input.triggerPath || input.path || "/");
417
+ const browser = await launchBrowser(pw, "web_network verification");
418
+ try {
419
+ const page = await browser.newPage({ viewport: input.viewport || { width: 1280, height: 720 } });
420
+ try {
421
+ const telemetry = await attachTelemetry(page);
422
+ try {
423
+ await page.goto(url, { waitUntil: input.waitUntil || "networkidle", timeout: input.timeoutMs || 15000 });
424
+ }
425
+ catch (err) {
426
+ return {
427
+ status: "fail",
428
+ score: 0,
429
+ failures: [`navigation failed: ${errorMessage(err)}`],
430
+ metrics: { backend: "playwright" }
431
+ };
432
+ }
433
+ const collected = telemetry.collect().network;
434
+ const failures = [];
435
+ for (const expectedCall of expected.networkCalls || []) {
436
+ const method = String(expectedCall.method || "GET").toUpperCase();
437
+ let re = null;
438
+ if (expectedCall.pathPattern) {
439
+ try {
440
+ re = new RegExp(expectedCall.pathPattern);
441
+ }
442
+ catch {
443
+ failures.push(`invalid pathPattern ${expectedCall.pathPattern}`);
444
+ continue;
445
+ }
446
+ }
447
+ const match = collected.find((c) => String(c.method).toUpperCase() === method && (!re || re.test(c.pathPattern)) && (expectedCall.status === undefined || c.status === expectedCall.status));
448
+ if (!match)
449
+ failures.push(`missing network call ${method} ${expectedCall.pathPattern || ""}${expectedCall.status !== undefined ? " " + expectedCall.status : ""}`);
450
+ }
451
+ return {
452
+ status: failures.length ? "fail" : "pass",
453
+ score: failures.length ? 0 : 1,
454
+ failures,
455
+ metrics: { backend: "playwright", networkCalls: collected.length }
456
+ };
457
+ }
458
+ finally {
459
+ try {
460
+ await page.close?.();
461
+ }
462
+ catch { /* ignore */ }
463
+ }
464
+ }
465
+ finally {
466
+ try {
467
+ await browser.close();
468
+ }
469
+ catch { /* ignore */ }
470
+ }
471
+ }
472
+ export async function verifyInvariant(invariant, ctx, deps = {}) {
473
+ if (invariant.type === "web_route")
474
+ return verifyRoute(invariant, ctx, deps);
475
+ if (invariant.type === "web_flow")
476
+ return verifyFlow(invariant, ctx, deps);
477
+ if (invariant.type === "web_network")
478
+ return verifyNetwork(invariant, ctx, deps);
479
+ throw new VibecodeError("UNSUPPORTED_FORMAT", `Unsupported web invariant type: ${invariant.type}`);
480
+ }
@@ -0,0 +1,7 @@
1
+ import type { SetupOptions, SetupReport } from "../core/types.js";
2
+ export declare const SUPPORTED_CLIENTS: string[];
3
+ /**
4
+ * Idempotently register the MCP server + install SKILL.md for coding agents.
5
+ * Never touches anything outside `cwd` / `homeDir` (both injectable for tests).
6
+ */
7
+ export declare function runSetup({ clients, scope, local, dryRun, cwd, homeDir, antigravityDir }?: SetupOptions): Promise<SetupReport>;
@@ -0,0 +1,186 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { VibecodeError, errorMessage } from "../core/errors.js";
6
+ const SERVER_ID = "vibecode-anything";
7
+ const VALID_SCOPES = new Set(["project", "global"]);
8
+ const CLI_PATH = fileURLToPath(new URL("../cli.js", import.meta.url));
9
+ const SKILL_SOURCE = fileURLToPath(new URL("../../skills/vibecode-anything/SKILL.md", import.meta.url));
10
+ function serverEntry(local) {
11
+ return local
12
+ ? { command: process.execPath, args: [CLI_PATH, "mcp"] }
13
+ : { command: SERVER_ID, args: ["mcp"] };
14
+ }
15
+ /**
16
+ * Client layouts. `mcpPath` is the JSON config containing `mcpServers`;
17
+ * `skillPath` is where SKILL.md must land for that client.
18
+ */
19
+ const CLIENTS = {
20
+ "claude-code": ({ scope, cwd, homeDir }) => ({
21
+ mcpPath: scope === "global" ? path.join(homeDir, ".claude.json") : path.join(cwd, ".mcp.json"),
22
+ skillPath: scope === "global"
23
+ ? path.join(homeDir, ".claude", "skills", SERVER_ID, "SKILL.md")
24
+ : path.join(cwd, ".claude", "skills", SERVER_ID, "SKILL.md")
25
+ }),
26
+ cursor: ({ scope, cwd, homeDir }) => ({
27
+ mcpPath: scope === "global" ? path.join(homeDir, ".cursor", "mcp.json") : path.join(cwd, ".cursor", "mcp.json"),
28
+ skillPath: scope === "global"
29
+ ? path.join(homeDir, ".cursor", "skills", SERVER_ID, "SKILL.md")
30
+ : path.join(cwd, ".cursor", "skills", SERVER_ID, "SKILL.md")
31
+ }),
32
+ antigravity: ({ scope, cwd, homeDir, antigravityDir }) => ({
33
+ mcpPath: antigravityDir
34
+ ? path.join(antigravityDir, "mcp_config.json")
35
+ : path.join(homeDir, ".gemini", "antigravity", "mcp_config.json"),
36
+ skillPath: scope === "global"
37
+ ? path.join(homeDir, ".gemini", "antigravity", "skills", SERVER_ID, "SKILL.md")
38
+ : path.join(cwd, ".agents", "skills", SERVER_ID, "SKILL.md")
39
+ })
40
+ };
41
+ export const SUPPORTED_CLIENTS = Object.keys(CLIENTS);
42
+ function normalizeClients(input) {
43
+ const raw = input === undefined || input === null ? ["auto"] : Array.isArray(input) ? input : [input];
44
+ const picked = [];
45
+ for (const item of raw) {
46
+ for (const piece of String(item).split(",")) {
47
+ const client = piece.trim().toLowerCase();
48
+ if (client)
49
+ picked.push(client);
50
+ }
51
+ }
52
+ if (picked.length === 0)
53
+ picked.push("auto");
54
+ if (picked.includes("auto"))
55
+ return [...SUPPORTED_CLIENTS];
56
+ return [...new Set(picked)];
57
+ }
58
+ function describeJsonType(value) {
59
+ if (value === null)
60
+ return "null";
61
+ if (Array.isArray(value))
62
+ return "array";
63
+ return typeof value;
64
+ }
65
+ function readJsonIfExists(file) {
66
+ if (!fs.existsSync(file))
67
+ return { exists: false, value: null, raw: null };
68
+ if (fs.statSync(file).isDirectory()) {
69
+ throw new VibecodeError("CONFIG_INVALID", `Refusing to overwrite ${file}: path is a directory, expected a JSON file. Move or remove the directory and re-run setup.`, { details: { path: file, reason: "is_directory" } });
70
+ }
71
+ const text = fs.readFileSync(file, "utf8");
72
+ if (!text.trim())
73
+ return { exists: true, value: {}, raw: text };
74
+ let parsed;
75
+ try {
76
+ parsed = JSON.parse(text);
77
+ }
78
+ catch (err) {
79
+ const parseError = errorMessage(err);
80
+ throw new VibecodeError("CONFIG_INVALID", `Refusing to overwrite ${file}: existing config is not valid JSON (${parseError}). Fix the JSON syntax or move the file aside, then re-run setup.`, { details: { path: file, reason: "invalid_json", parseError } });
81
+ }
82
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
83
+ const actualType = describeJsonType(parsed);
84
+ throw new VibecodeError("CONFIG_INVALID", `Refusing to overwrite ${file}: expected a top-level JSON object, found ${actualType}. Fix or back up the file before re-running setup.`, { details: { path: file, reason: "non_object_root", actualType } });
85
+ }
86
+ return { exists: true, value: parsed, raw: text };
87
+ }
88
+ /** Deep-merge only our server entry; every other key/server is preserved verbatim. */
89
+ function mergeMcpConfig(existing, server, file) {
90
+ const config = existing || {};
91
+ if (Object.prototype.hasOwnProperty.call(config, "mcpServers") && config.mcpServers !== undefined) {
92
+ if (!config.mcpServers || typeof config.mcpServers !== "object" || Array.isArray(config.mcpServers)) {
93
+ const actualType = describeJsonType(config.mcpServers);
94
+ throw new VibecodeError("CONFIG_INVALID", `Refusing to overwrite ${file}: expected "mcpServers" to be a JSON object, found ${actualType}. Fix or back up the file before re-running setup.`, { details: { path: file, reason: "invalid_mcp_servers", actualType } });
95
+ }
96
+ }
97
+ const prevServers = config.mcpServers || {};
98
+ return { ...config, mcpServers: { ...prevServers, [SERVER_ID]: server } };
99
+ }
100
+ function serialize(value) {
101
+ return JSON.stringify(value, null, 2) + "\n";
102
+ }
103
+ /**
104
+ * Idempotently register the MCP server + install SKILL.md for coding agents.
105
+ * Never touches anything outside `cwd` / `homeDir` (both injectable for tests).
106
+ */
107
+ export async function runSetup({ clients = ["auto"], scope = "project", local = false, dryRun = false, cwd = process.cwd(), homeDir = os.homedir(), antigravityDir } = {}) {
108
+ if (!VALID_SCOPES.has(scope)) {
109
+ throw new VibecodeError("CONTRACT_INVALID", `scope must be one of ${[...VALID_SCOPES].join(", ")} (got "${scope}"). Pass --scope project or --scope global.`);
110
+ }
111
+ const resolvedScope = scope;
112
+ if (!fs.existsSync(SKILL_SOURCE)) {
113
+ throw new VibecodeError("CONTRACT_NOT_FOUND", `Bundled SKILL.md is missing at ${SKILL_SOURCE}`);
114
+ }
115
+ const rootDir = path.resolve(cwd);
116
+ const home = path.resolve(homeDir);
117
+ const requested = normalizeClients(clients);
118
+ const server = serverEntry(local);
119
+ const skillText = fs.readFileSync(SKILL_SOURCE, "utf8");
120
+ const context = { scope: resolvedScope, cwd: rootDir, homeDir: home, antigravityDir };
121
+ const warnings = [];
122
+ const changes = [];
123
+ const pendingWrites = [];
124
+ const written = [];
125
+ const activeClients = [];
126
+ for (const client of requested) {
127
+ const layout = CLIENTS[client];
128
+ if (!layout) {
129
+ warnings.push({
130
+ code: "UNKNOWN_CLIENT",
131
+ message: `Unknown client "${client}". Supported clients: ${SUPPORTED_CLIENTS.join(", ")}, or "auto".`,
132
+ client,
133
+ supported: SUPPORTED_CLIENTS
134
+ });
135
+ continue;
136
+ }
137
+ activeClients.push(client);
138
+ const { mcpPath, skillPath } = layout(context);
139
+ // 1) MCP config (merge, never clobber)
140
+ const existing = readJsonIfExists(mcpPath);
141
+ const merged = mergeMcpConfig(existing.value, server, mcpPath);
142
+ const desired = serialize(merged);
143
+ const mcpAction = !existing.exists ? "create" : existing.raw === desired ? "unchanged" : "update";
144
+ changes.push({ client, kind: "mcp", path: mcpPath, action: mcpAction });
145
+ if (!dryRun && mcpAction !== "unchanged") {
146
+ pendingWrites.push({ path: mcpPath, content: desired });
147
+ }
148
+ // 2) SKILL.md
149
+ if (fs.existsSync(skillPath) && fs.statSync(skillPath).isDirectory()) {
150
+ throw new VibecodeError("CONFIG_INVALID", `Refusing to overwrite ${skillPath}: path is a directory, expected a file. Move or remove the directory and re-run setup.`, { details: { path: skillPath, reason: "is_directory" } });
151
+ }
152
+ const skillCurrent = fs.existsSync(skillPath) ? fs.readFileSync(skillPath, "utf8") : null;
153
+ const skillAction = skillCurrent === null ? "create" : skillCurrent === skillText ? "unchanged" : "update";
154
+ changes.push({ client, kind: "skill", path: skillPath, action: skillAction });
155
+ if (!dryRun && skillAction !== "unchanged") {
156
+ pendingWrites.push({ path: skillPath, content: skillText });
157
+ }
158
+ }
159
+ if (!dryRun) {
160
+ for (const item of pendingWrites) {
161
+ fs.mkdirSync(path.dirname(item.path), { recursive: true });
162
+ fs.writeFileSync(item.path, item.content, "utf8");
163
+ written.push(item.path);
164
+ }
165
+ }
166
+ const summary = {
167
+ created: changes.filter((c) => c.action === "create").length,
168
+ updated: changes.filter((c) => c.action === "update").length,
169
+ unchanged: changes.filter((c) => c.action === "unchanged").length,
170
+ written: written.length,
171
+ warnings: warnings.length
172
+ };
173
+ return {
174
+ ok: warnings.length === 0 || activeClients.length > 0,
175
+ dryRun: Boolean(dryRun),
176
+ scope: resolvedScope,
177
+ local: Boolean(local),
178
+ clients: activeClients,
179
+ server,
180
+ skillSource: SKILL_SOURCE,
181
+ summary,
182
+ changes,
183
+ written,
184
+ warnings
185
+ };
186
+ }