@botiverse/porthole 0.2.4 → 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 (75) hide show
  1. package/README.md +14 -9
  2. package/dist/check/check.d.ts +83 -0
  3. package/dist/check/check.js +169 -0
  4. package/dist/check/drivers.d.ts +24 -0
  5. package/dist/check/drivers.js +110 -0
  6. package/dist/check/index.d.ts +8 -0
  7. package/dist/check/index.js +8 -0
  8. package/dist/check/lint.d.ts +21 -0
  9. package/dist/check/lint.js +131 -0
  10. package/dist/check/page-source.d.ts +2 -0
  11. package/dist/check/page-source.js +2 -0
  12. package/dist/check/page.d.ts +51 -0
  13. package/dist/check/page.js +150 -0
  14. package/dist/check/tools.d.ts +61 -0
  15. package/dist/check/tools.js +140 -0
  16. package/dist/conformance/host-kit.d.ts +10 -2
  17. package/dist/conformance/host-kit.js +9 -2
  18. package/dist/displays/displays.d.ts +61 -0
  19. package/dist/displays/displays.js +113 -0
  20. package/dist/host/client.d.ts +92 -0
  21. package/dist/host/client.js +259 -0
  22. package/dist/index.d.ts +4 -0
  23. package/dist/index.js +6 -0
  24. package/dist/node/index.d.ts +22 -1
  25. package/dist/node/index.js +46 -1
  26. package/dist/react/frame.d.ts +71 -3
  27. package/dist/react/frame.js +120 -19
  28. package/dist/react/index.d.ts +1 -0
  29. package/dist/react/index.js +1 -0
  30. package/dist/react/view.d.ts +54 -0
  31. package/dist/react/view.js +146 -0
  32. package/dist/server/bootstrap.d.ts +27 -0
  33. package/dist/server/bootstrap.js +63 -0
  34. package/dist/server/host.d.ts +74 -7
  35. package/dist/server/host.js +237 -9
  36. package/dist/server/index.d.ts +4 -2
  37. package/dist/server/index.js +3 -1
  38. package/dist/server/pages.d.ts +19 -0
  39. package/dist/server/pages.js +8 -0
  40. package/dist/server/proxy.d.ts +24 -0
  41. package/dist/server/proxy.js +67 -0
  42. package/dist/server/server.js +14 -1
  43. package/dist/server/types.d.ts +8 -0
  44. package/docs/ADOPTING.md +191 -104
  45. package/docs/DECISIONS.md +146 -0
  46. package/docs/DESIGN.md +58 -0
  47. package/examples/app.mjs +62 -64
  48. package/examples/conformance/page.spec.mjs +23 -0
  49. package/examples/conformance/playwright.config.mjs +1 -1
  50. package/examples/conformance/porthole.spec.mjs +5 -3
  51. package/examples/displays.mjs +19 -0
  52. package/examples/mcp/server.mjs +121 -0
  53. package/package.json +9 -1
  54. package/src/check/check.ts +278 -0
  55. package/src/check/drivers.ts +144 -0
  56. package/src/check/index.ts +15 -0
  57. package/src/check/lint.ts +238 -0
  58. package/src/check/page-source.ts +19 -0
  59. package/src/check/page.ts +204 -0
  60. package/src/check/tools.ts +206 -0
  61. package/src/conformance/host-kit.ts +20 -11
  62. package/src/displays/displays.ts +191 -0
  63. package/src/host/client.ts +364 -0
  64. package/src/index.ts +25 -0
  65. package/src/node/index.ts +66 -2
  66. package/src/react/frame.tsx +191 -33
  67. package/src/react/index.ts +8 -0
  68. package/src/react/view.tsx +232 -0
  69. package/src/server/bootstrap.ts +97 -0
  70. package/src/server/host.ts +331 -15
  71. package/src/server/index.ts +11 -1
  72. package/src/server/pages.ts +28 -0
  73. package/src/server/proxy.ts +86 -0
  74. package/src/server/server.ts +26 -2
  75. package/src/server/types.ts +5 -0
package/README.md CHANGED
@@ -32,6 +32,7 @@ PORTHOLE_SECRET=$(npx porthole secret) node node_modules/@botiverse/porthole/exa
32
32
  - `examples/app.mjs`: the app (policy, routes, page), runtime-agnostic.
33
33
  - `examples/node/server.mjs`, `examples/workers/` (with its D1 migration and `wrangler.jsonc`).
34
34
  - `examples/conformance/`: Porthole's conformance suite run against it, on three engines.
35
+ - `examples/mcp/server.mjs`: the agent's tools (show, guide, check) as an MCP server.
35
36
 
36
37
  ## The smallest opaque display
37
38
 
@@ -50,16 +51,19 @@ display.setContent("<p>Hello from an agent</p>");
50
51
  In React: `<PortholeProvider>` around `<PortholeFrame config displayId title scheme content />` from
51
52
  `@botiverse/porthole/react`.
52
53
 
53
- ## What the agent reads
54
+ ## What the agent gets
54
55
 
55
56
  ```js
56
- import { compile } from "@botiverse/porthole";
57
+ import { admitContent, checkTool, guideTool, showTool } from "@botiverse/porthole";
57
58
 
58
- const compiled = compile(config);
59
- compiled.toolDescription(); // the show tool's description: what it may write, and where it runs
60
- compiled.guide(); // the manual: the sandbox's limits, sizes, colors, examples
59
+ const tools = [showTool(config), guideTool(config), checkTool(config)]; // name, description, JSON Schema
60
+ const admitted = admitContent(config, html); // refuses only what certainly fails, saying what to change
61
61
  ```
62
62
 
63
+ `checkPage` (`@botiverse/porthole/check`) runs a page in the real sandbox at phone and desktop
64
+ width, light and dark, before anyone sees it, and tells the agent what broke in a few lines.
65
+ `examples/mcp/server.mjs` wires the tools as an MCP server.
66
+
63
67
  ## Read next
64
68
 
65
69
  - [docs/ADOPTING.md](docs/ADOPTING.md): getting started, step by step: the server, the page, its
@@ -71,11 +75,12 @@ compiled.guide(); // the manual: the sandbox's limits, sizes, colors,
71
75
 
72
76
  | Import | What |
73
77
  | --- | --- |
74
- | `@botiverse/porthole` | `createHost`, `presets`, `compile`, `httpLocator`, `servedOrOpaque` (browser and server) |
75
- | `@botiverse/porthole/react` | `PortholeProvider`, `PortholeFrame` |
76
- | `@botiverse/porthole/server` | `createContentHost`, `prefixedName`, `d1TicketStore` (any runtime) |
77
- | `@botiverse/porthole/node` | `nodeHost`, `nodeProbe` (Node's http server) |
78
+ | `@botiverse/porthole` | `createHost`, `presets`, `defineDisplays`, `portholeClient`, `lintContent`, the tools (browser and server) |
79
+ | `@botiverse/porthole/react` | `PortholeProvider`, `PortholeFrame`, `PortholeView` |
80
+ | `@botiverse/porthole/server` | `createContentHost` (`routes`), `contentHostFor`, `prefixedName`, `d1TicketStore` (any runtime) |
81
+ | `@botiverse/porthole/node` | `nodeServer`, `nodeHost`, `nodeProbe` (Node's http server) |
78
82
  | `@botiverse/porthole/mcp` | the MCP Apps adapter |
83
+ | `@botiverse/porthole/check` | `checkPage`, `playwrightDriver`, `cdpDriver`: the agent's pre-show check |
79
84
  | `@botiverse/porthole/conformance` | `defineHostConformance`: the suite, against your app (Playwright) |
80
85
 
81
86
  `npx porthole secret` makes a secret; `npx porthole d1-schema` prints the D1 migration.
@@ -0,0 +1,83 @@
1
+ import type { ColorScheme, PortholeConfig } from "../config/schema.ts";
2
+ import { type Finding } from "./lint.ts";
3
+ /**
4
+ * Checks content before people see it (P073): runs it in the real sandbox at each width and
5
+ * scheme, through a driver (a browser the host has: Playwright, or any CDP session, Cloudflare
6
+ * Browser Rendering's included), and says what went wrong, briefly, for the agent.
7
+ *
8
+ * const report = await checkPage({ config, content: html, driver: playwrightDriver(browser) });
9
+ * report.ok; report.text; // "At 320 px, dark: TypeError: … (line 12). …"
10
+ */
11
+ /** A page the check drives: one at a time, sequentially. */
12
+ export interface CheckSession {
13
+ setViewport(width: number, height: number): Promise<void>;
14
+ /** Loads a whole HTML document into the page. */
15
+ load(html: string): Promise<void>;
16
+ /** Evaluates a JavaScript expression in the page (a promise is awaited); JSON back. */
17
+ evaluate<T>(expression: string): Promise<T>;
18
+ /** A PNG of the element `selector` names, where the driver can. */
19
+ screenshot?(selector: string): Promise<Uint8Array>;
20
+ close(): Promise<void>;
21
+ }
22
+ /** How the check gets a page: `playwrightDriver(browser)`, `cdpDriver(session)`. */
23
+ export interface CheckDriver {
24
+ open(): Promise<CheckSession>;
25
+ }
26
+ export interface CheckOptions {
27
+ readonly config: PortholeConfig;
28
+ /** The content as the agent would send it: a fragment, or a whole document. */
29
+ readonly content: string;
30
+ readonly driver: CheckDriver;
31
+ /** Widths, px. Default: the manual's phone and desktop widths (`config.layout`). */
32
+ readonly widths?: readonly number[];
33
+ /** Default: light and dark, or light alone where the app doesn't theme it. */
34
+ readonly schemes?: readonly ColorScheme[];
35
+ /** The host's live theme values per scheme, as `HostOptions.theme` answers. */
36
+ readonly hostTheme?: {
37
+ readonly light?: Readonly<Record<string, string>>;
38
+ readonly dark?: Readonly<Record<string, string>>;
39
+ };
40
+ /** How long content settles before it is measured, ms. Default 1500. */
41
+ readonly settleMs?: number;
42
+ /** A PNG of each run, for an agent that sees. */
43
+ readonly screenshots?: boolean;
44
+ /** The most distinct problems `text` names (default 8): the rest are counted. */
45
+ readonly maxProblems?: number;
46
+ /**
47
+ * The check page's script (`import page from "@botiverse/porthole/check/page"`). Node finds it
48
+ * itself; a bundled runtime (a Worker) passes it.
49
+ */
50
+ readonly page?: string;
51
+ }
52
+ export interface CheckRun {
53
+ readonly width: number;
54
+ readonly scheme: ColorScheme;
55
+ /** The height the content reported, px, and whether the config's limit cuts it. */
56
+ readonly height: number | null;
57
+ readonly clipped: boolean;
58
+ /** Wider than its frame: it scrolls sideways (or is cut). */
59
+ readonly overflowX: boolean;
60
+ readonly errors: readonly string[];
61
+ readonly blocked: readonly {
62
+ readonly url: string;
63
+ readonly directive: string;
64
+ }[];
65
+ readonly failedLoads: readonly {
66
+ readonly url: string;
67
+ readonly tag: string;
68
+ }[];
69
+ readonly console: readonly {
70
+ readonly level: "error" | "warning";
71
+ readonly text: string;
72
+ }[];
73
+ readonly screenshot?: Uint8Array;
74
+ }
75
+ export interface CheckReport {
76
+ /** Nothing failed: no errors, blocks, failed loads, console errors, overflow or cut, no lint error. */
77
+ readonly ok: boolean;
78
+ readonly lint: readonly Finding[];
79
+ readonly runs: readonly CheckRun[];
80
+ /** One short summary for the agent: each problem once, with where it happened. */
81
+ readonly text: string;
82
+ }
83
+ export declare function checkPage(options: CheckOptions): Promise<CheckReport>;
@@ -0,0 +1,169 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { presets } from "../presets/presets.js";
10
+ import { lintContent } from "./lint.js";
11
+ const noun = (config) => config.mode === "artifact" ? "page" : config.mode === "mcp-app" ? "view" : "widget";
12
+ /**
13
+ * The config the check runs content under: opaque (a served config's content is checked with the
14
+ * same CSP); an MCP Apps view as a page with the view's egress (its protocol is its host's).
15
+ */
16
+ function checkedAs(config) {
17
+ const opaque = config.isolation === "opaque" ? config : { ...config, isolation: "opaque", contentOrigins: [] };
18
+ return opaque.mode === "mcp-app"
19
+ ? presets.artifact({ egress: opaque.egress, limits: opaque.limits })
20
+ : opaque;
21
+ }
22
+ /** The check page's script: given, or (Node) the package's own. */
23
+ async function pageScript(given) {
24
+ if (given !== undefined) {
25
+ return given;
26
+ }
27
+ // Not a literal: a bundler for a Worker leaves it alone (a Worker passes `page`).
28
+ const where = new URL(import.meta.url.endsWith(".ts") ? "./page-source.ts" : "./page-source.js", import.meta.url).href;
29
+ const loaded = (await import(__rewriteRelativeImportExtension(where)));
30
+ return loaded.default;
31
+ }
32
+ const escapeScript = (code) => code.replace(/<\/script/giu, "<\\/script");
33
+ export async function checkPage(options) {
34
+ const { config } = options;
35
+ const lint = lintContent(config, options.content);
36
+ if (config.mode === "url") {
37
+ return {
38
+ ok: true,
39
+ lint,
40
+ runs: [],
41
+ text: "A url-mode app runs its own page: nothing to check here.",
42
+ };
43
+ }
44
+ const widths = options.widths ?? [config.layout.narrowWidthPx, config.layout.wideWidthPx];
45
+ const unthemed = config.theme.documents === "never";
46
+ const schemes = options.schemes ?? (unthemed ? ["light"] : ["light", "dark"]);
47
+ const settle = options.settleMs ?? 1_500;
48
+ const fills = config.layout.kind === "fill";
49
+ const shown = checkedAs(config);
50
+ const script = await pageScript(options.page);
51
+ const html = `<!doctype html><html><head><meta charset="utf-8"><title>Porthole check</title><style>body{margin:0;padding:8px}section{margin-bottom:16px}</style></head><body><script>${escapeScript(script)}</script></body></html>`;
52
+ const session = await options.driver.open();
53
+ const runs = [];
54
+ try {
55
+ for (const width of widths) {
56
+ await session.setViewport(width + 40, fills ? 760 : 900);
57
+ await session.load(html);
58
+ for (const scheme of schemes) {
59
+ const spec = {
60
+ config: shown,
61
+ content: options.content,
62
+ widthPx: width,
63
+ ...(fills ? { heightPx: 700 } : {}),
64
+ scheme,
65
+ ...(options.hostTheme?.[scheme] === undefined
66
+ ? {}
67
+ : { hostTheme: options.hostTheme[scheme] }),
68
+ };
69
+ const id = await session.evaluate(`window.portholeCheck.run(${JSON.stringify(spec)})`);
70
+ await session.evaluate(`new Promise((resolve) => setTimeout(resolve, ${settle}))`);
71
+ await session.evaluate(`window.portholeCheck.measure(${id})`);
72
+ const data = await session.evaluate(`window.portholeCheck.result(${id})`);
73
+ const screenshot = options.screenshots === true && session.screenshot !== undefined
74
+ ? await session.screenshot(`#porthole-check-${id}`)
75
+ : undefined;
76
+ await session.evaluate(`window.portholeCheck.end(${id})`);
77
+ const height = data?.height ?? null;
78
+ runs.push({
79
+ width,
80
+ scheme,
81
+ height,
82
+ clipped: !fills && height !== null && height >= config.limits.maxHeightPx,
83
+ overflowX: data?.scrollWidth !== null &&
84
+ data?.scrollWidth !== undefined &&
85
+ data.clientWidth !== null &&
86
+ data.scrollWidth > data.clientWidth + 1,
87
+ errors: unique(data?.errors ?? []),
88
+ blocked: uniqueBy(data?.blocked ?? [], (each) => `${each.url} ${each.directive}`),
89
+ failedLoads: uniqueBy(data?.failedLoads ?? [], (each) => each.url),
90
+ console: uniqueBy(data?.console ?? [], (each) => `${each.level} ${each.text}`),
91
+ ...(screenshot === undefined ? {} : { screenshot }),
92
+ });
93
+ }
94
+ }
95
+ }
96
+ finally {
97
+ await session.close();
98
+ }
99
+ const failed = (run) => run.errors.length > 0 ||
100
+ run.blocked.length > 0 ||
101
+ run.failedLoads.length > 0 ||
102
+ run.console.some((each) => each.level === "error") ||
103
+ run.overflowX ||
104
+ run.clipped;
105
+ const ok = !lint.some((each) => each.severity === "error") && !runs.some(failed);
106
+ return { ok, lint, runs, text: summary(config, lint, runs, options.maxProblems ?? 8) };
107
+ }
108
+ const unique = (values) => [...new Set(values)];
109
+ function uniqueBy(values, key) {
110
+ const seen = new Set();
111
+ return values.filter((each) => {
112
+ const k = key(each);
113
+ if (seen.has(k)) {
114
+ return false;
115
+ }
116
+ seen.add(k);
117
+ return true;
118
+ });
119
+ }
120
+ const clip = (text, most = 200) => text.length > most ? `${text.slice(0, most - 1)}…` : text;
121
+ /**
122
+ * The report in a few lines for the agent: each problem once, with the runs it happened in, at
123
+ * most `most` of them.
124
+ */
125
+ function summary(config, lint, runs, most) {
126
+ const it = noun(config);
127
+ const where = new Map();
128
+ const add = (problem, run) => {
129
+ const list = where.get(problem) ?? [];
130
+ list.push(`${run.width} px ${run.scheme}`);
131
+ where.set(problem, list);
132
+ };
133
+ for (const run of runs) {
134
+ for (const error of run.errors) {
135
+ add(`It threw: ${clip(error)}`, run);
136
+ }
137
+ for (const block of run.blocked) {
138
+ add(`The sandbox blocked ${clip(block.url, 120)} (${block.directive}): nothing loads from there here`, run);
139
+ }
140
+ const blockedUrls = new Set(run.blocked.map((each) => each.url));
141
+ for (const load of run.failedLoads.filter((each) => !blockedUrls.has(each.url))) {
142
+ add(`Failed to load ${clip(load.url, 120)} (<${load.tag}>)`, run);
143
+ }
144
+ for (const line of run.console.filter((each) => each.level === "error")) {
145
+ add(`console.error: ${clip(line.text)}`, run);
146
+ }
147
+ if (run.overflowX) {
148
+ add(`It is wider than its frame and scrolls sideways: nothing fixed wider than ${config.layout.minWidthPx} px; let it wrap`, run);
149
+ }
150
+ if (run.clipped) {
151
+ add(`It is taller than ${config.limits.maxHeightPx} px and is cut: make it shorter`, run);
152
+ }
153
+ }
154
+ const lines = [
155
+ ...lint.map((each) => `${each.severity === "error" ? "Error" : "Warning"}${each.line === undefined ? "" : ` (line ${each.line})`}: ${each.message}`),
156
+ ...[...where].map(([problem, at]) => `${problem} (at ${at.length === runs.length ? "every width and scheme" : at.join(", ")}).`),
157
+ ];
158
+ const ran = `${[...new Set(runs.map((run) => `${run.width} px`))].join(" and ")}, ${[...new Set(runs.map((run) => run.scheme))].join(" and ")}`;
159
+ if (lines.length === 0) {
160
+ return `OK: the ${it} ran at ${ran} with no errors, blocks, failed loads or overflow.`;
161
+ }
162
+ const shown = lines.slice(0, most);
163
+ const more = lines.length - shown.length;
164
+ return [
165
+ `The ${it} has ${lines.length} problem${lines.length === 1 ? "" : "s"} (ran at ${ran}):`,
166
+ ...shown.map((line) => `- ${line}`),
167
+ ...(more > 0 ? [`- and ${more} more.`] : []),
168
+ ].join("\n");
169
+ }
@@ -0,0 +1,24 @@
1
+ import type { Browser } from "@playwright/test";
2
+ import type { CheckDriver } from "./check.ts";
3
+ /**
4
+ * Drivers for `checkPage` (P073): Playwright's browser on Node, or any Chrome DevTools Protocol
5
+ * session (Puppeteer's `page.createCDPSession()`, `@cloudflare/puppeteer` on Cloudflare Browser
6
+ * Rendering from a Worker).
7
+ */
8
+ /** Checks in a page of a Playwright browser (`chromium.launch()`), one page per check. */
9
+ export declare function playwrightDriver(browser: Browser): CheckDriver;
10
+ /** Where the check page is served from: a name no network has, answered by the driver. */
11
+ export declare const CHECK_ORIGIN = "https://porthole-check.invalid";
12
+ /** A Chrome DevTools Protocol session: its commands and its events (Puppeteer's `CDPSession`). */
13
+ export interface CdpSession {
14
+ send(method: string, params?: Record<string, unknown>): Promise<unknown>;
15
+ on(event: "Fetch.requestPaused", listener: (params: {
16
+ readonly requestId: string;
17
+ }) => void): unknown;
18
+ }
19
+ /**
20
+ * Checks over a CDP session to a page (P073): `cdpDriver(() => page.createCDPSession())` with
21
+ * Puppeteer, or `@cloudflare/puppeteer` in a Worker with a Browser Rendering binding. `open` is
22
+ * asked for a session per check; the caller closes its page.
23
+ */
24
+ export declare function cdpDriver(open: () => Promise<CdpSession>): CheckDriver;
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Drivers for `checkPage` (P073): Playwright's browser on Node, or any Chrome DevTools Protocol
3
+ * session (Puppeteer's `page.createCDPSession()`, `@cloudflare/puppeteer` on Cloudflare Browser
4
+ * Rendering from a Worker).
5
+ */
6
+ /** Checks in a page of a Playwright browser (`chromium.launch()`), one page per check. */
7
+ export function playwrightDriver(browser) {
8
+ return {
9
+ async open() {
10
+ const page = await browser.newPage();
11
+ let html = "";
12
+ // The check page needs an origin of its own (a host's): served from a name no network has.
13
+ await page.route(`${CHECK_ORIGIN}/**`, (route) => route.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: html }));
14
+ return {
15
+ setViewport: (width, height) => page.setViewportSize({ width, height }),
16
+ async load(document) {
17
+ html = document;
18
+ await page.goto(`${CHECK_ORIGIN}/`, { waitUntil: "load" });
19
+ },
20
+ evaluate: (expression) => page.evaluate(expression),
21
+ screenshot: async (selector) => new Uint8Array(await page.locator(selector).screenshot()),
22
+ close: () => page.close(),
23
+ };
24
+ },
25
+ };
26
+ }
27
+ /** Where the check page is served from: a name no network has, answered by the driver. */
28
+ export const CHECK_ORIGIN = "https://porthole-check.invalid";
29
+ const toBase64 = (text) => {
30
+ let binary = "";
31
+ for (const byte of new TextEncoder().encode(text)) {
32
+ binary += String.fromCharCode(byte);
33
+ }
34
+ return btoa(binary);
35
+ };
36
+ const base64 = (text) => Uint8Array.from(atob(text), (char) => char.charCodeAt(0));
37
+ /**
38
+ * Checks over a CDP session to a page (P073): `cdpDriver(() => page.createCDPSession())` with
39
+ * Puppeteer, or `@cloudflare/puppeteer` in a Worker with a Browser Rendering binding. `open` is
40
+ * asked for a session per check; the caller closes its page.
41
+ */
42
+ export function cdpDriver(open) {
43
+ return {
44
+ async open() {
45
+ const session = await open();
46
+ await session.send("Page.enable");
47
+ await session.send("Runtime.enable");
48
+ let html = "";
49
+ // The check page needs an origin of its own: the driver answers its address itself.
50
+ await session.send("Fetch.enable", { patterns: [{ urlPattern: `${CHECK_ORIGIN}/*` }] });
51
+ session.on("Fetch.requestPaused", (event) => {
52
+ void session.send("Fetch.fulfillRequest", {
53
+ requestId: event.requestId,
54
+ responseCode: 200,
55
+ responseHeaders: [{ name: "content-type", value: "text/html; charset=utf-8" }],
56
+ body: toBase64(html),
57
+ });
58
+ });
59
+ const evaluate = async (expression) => {
60
+ const answer = (await session.send("Runtime.evaluate", {
61
+ expression,
62
+ awaitPromise: true,
63
+ returnByValue: true,
64
+ }));
65
+ if (answer.exceptionDetails !== undefined) {
66
+ throw new Error(answer.exceptionDetails.exception?.description ??
67
+ answer.exceptionDetails.text ??
68
+ "Evaluation failed");
69
+ }
70
+ return answer.result?.value;
71
+ };
72
+ return {
73
+ async setViewport(width, height) {
74
+ await session.send("Emulation.setDeviceMetricsOverride", {
75
+ width,
76
+ height,
77
+ deviceScaleFactor: 1,
78
+ mobile: false,
79
+ });
80
+ },
81
+ async load(document) {
82
+ html = document;
83
+ await session.send("Page.navigate", { url: `${CHECK_ORIGIN}/` });
84
+ // The page's script runs when it loads: wait until it says so.
85
+ for (let tries = 0; tries < 100; tries += 1) {
86
+ const ready = await evaluate('document.documentElement?.dataset.portholeCheck === "ready"').catch(() => false);
87
+ if (ready) {
88
+ return;
89
+ }
90
+ await new Promise((resolve) => setTimeout(resolve, 50));
91
+ }
92
+ throw new Error("The check page didn't start");
93
+ },
94
+ evaluate,
95
+ async screenshot(selector) {
96
+ const box = await evaluate(`(() => { const r = document.querySelector(${JSON.stringify(selector)})?.getBoundingClientRect(); return r ? { x: r.x, y: r.y, width: r.width, height: r.height } : null; })()`);
97
+ if (box === null) {
98
+ return new Uint8Array();
99
+ }
100
+ const shot = (await session.send("Page.captureScreenshot", {
101
+ format: "png",
102
+ clip: { ...box, scale: 1 },
103
+ }));
104
+ return base64(shot.data);
105
+ },
106
+ close: () => Promise.resolve(),
107
+ };
108
+ },
109
+ };
110
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `@botiverse/porthole/check`: check content before people see it (P073). `checkPage` runs it in
3
+ * the real sandbox through a driver (`playwrightDriver`, `cdpDriver`); `lintContent` and the tool
4
+ * definitions are in the core (`@botiverse/porthole`), since they need no browser.
5
+ */
6
+ export { checkPage, type CheckDriver, type CheckOptions, type CheckReport, type CheckRun, type CheckSession, } from "./check.ts";
7
+ export { cdpDriver, playwrightDriver, type CdpSession } from "./drivers.ts";
8
+ export { lintContent, type Finding, type LintRule } from "./lint.ts";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * `@botiverse/porthole/check`: check content before people see it (P073). `checkPage` runs it in
3
+ * the real sandbox through a driver (`playwrightDriver`, `cdpDriver`); `lintContent` and the tool
4
+ * definitions are in the core (`@botiverse/porthole`), since they need no browser.
5
+ */
6
+ export { checkPage, } from "./check.js";
7
+ export { cdpDriver, playwrightDriver } from "./drivers.js";
8
+ export { lintContent } from "./lint.js";
@@ -0,0 +1,21 @@
1
+ import type { PortholeConfig } from "../config/schema.ts";
2
+ /**
3
+ * What can be told about content without running it (P073), worded as the manual words it, so
4
+ * the agent fixes it before anyone sees it. Pure: any runtime. Errors are only what certainly
5
+ * fails or is cut (`refuseOn: "error"` refuses those); the rest are warnings.
6
+ */
7
+ export type LintRule = "size" | "document" | "nested-frame" | "document-write" | "clipboard" | "dialog" | "form" | "egress" | "unpinned" | "position-fixed" | "new-window";
8
+ export interface Finding {
9
+ readonly rule: LintRule;
10
+ readonly severity: "error" | "warning";
11
+ /** What to change, for the agent. */
12
+ readonly message: string;
13
+ /** Where (1-based), where a line says it. */
14
+ readonly line?: number;
15
+ }
16
+ /**
17
+ * A whole document sent where a fragment is shown (an inline widget), as the fragment it means:
18
+ * its head's styles and scripts, then its body. Null where it has no body to take.
19
+ */
20
+ export declare function fragmentOf(content: string): string | null;
21
+ export declare function lintContent(config: PortholeConfig, content: string): Finding[];
@@ -0,0 +1,131 @@
1
+ import { anyHttps, declaredCapabilities, egressOrigins, } from "../compile/policy.js";
2
+ import { sizeWords } from "../guide/limits.js";
3
+ import { originMatchesSource } from "../isolation/served.js";
4
+ const lineOf = (text, index) => text.slice(0, index).split("\n").length;
5
+ const noun = (config) => config.mode === "artifact" ? "page" : config.mode === "mcp-app" ? "view" : "widget";
6
+ /** A whole document's markers: what a fragment must not have. */
7
+ const DOCUMENT = /<!doctype\b|<html[\s>]|<head[\s>]|<body[\s>]/iu;
8
+ /**
9
+ * A whole document sent where a fragment is shown (an inline widget), as the fragment it means:
10
+ * its head's styles and scripts, then its body. Null where it has no body to take.
11
+ */
12
+ export function fragmentOf(content) {
13
+ const head = /<head[^>]*>([\s\S]*?)<\/head>/iu.exec(content)?.[1] ?? "";
14
+ const kept = [...head.matchAll(/<(style|script)\b[\s\S]*?<\/\1>|<link\b[^>]*>/giu)]
15
+ .map((each) => each[0])
16
+ .join("\n");
17
+ const body = /<body[^>]*>([\s\S]*?)(?:<\/body>|$)/iu.exec(content)?.[1] ??
18
+ content
19
+ .replace(/<!doctype[^>]*>/iu, "")
20
+ .replace(/<\/?html[^>]*>/giu, "")
21
+ .replace(/<head[^>]*>[\s\S]*?<\/head>/iu, "");
22
+ return body.trim() === "" ? null : `${kept}${kept === "" ? "" : "\n"}${body.trim()}`;
23
+ }
24
+ /** Where content reaches out, by the kind of egress each would need. */
25
+ const REACHES = [
26
+ { kind: "script", pattern: /<script\b[^>]*\bsrc\s*=\s*["']?(https?:\/\/[^"'\s>]+)/giu },
27
+ { kind: "script", pattern: /\bimport\s*(?:[\w{}\s*,]+from\s*)?\(?\s*["'](https?:\/\/[^"']+)/gu },
28
+ { kind: "style", pattern: /<link\b[^>]*\bhref\s*=\s*["']?(https?:\/\/[^"'\s>]+)/giu },
29
+ { kind: "style", pattern: /@import\s+(?:url\()?["']?(https?:\/\/[^"')\s]+)/giu },
30
+ { kind: "img", pattern: /<img\b[^>]*\bsrc\s*=\s*["']?(https?:\/\/[^"'\s>]+)/giu },
31
+ { kind: "img", pattern: /url\(\s*["']?(https?:\/\/[^"')\s]+)/giu },
32
+ {
33
+ kind: "media",
34
+ pattern: /<(?:video|audio|source)\b[^>]*\bsrc\s*=\s*["']?(https?:\/\/[^"'\s>]+)/giu,
35
+ },
36
+ { kind: "connect", pattern: /\bfetch\s*\(\s*["'`](https?:\/\/[^"'`]+)/gu },
37
+ {
38
+ kind: "connect",
39
+ pattern: /\bnew\s+(?:WebSocket|EventSource)\s*\(\s*["'`]((?:https?|wss?):\/\/[^"'`]+)/gu,
40
+ },
41
+ ];
42
+ const CDN_PACKAGE = /^https:\/\/(?:cdn\.jsdelivr\.net\/npm|unpkg\.com|esm\.sh)\/((?:@[^/]+\/)?[^/@]+)(@[^/]*)?/u;
43
+ export function lintContent(config, content) {
44
+ if (config.mode === "url") {
45
+ return [];
46
+ }
47
+ const findings = [];
48
+ const add = (rule, severity, message, index) => findings.push({
49
+ rule,
50
+ severity,
51
+ message,
52
+ ...(index === undefined ? {} : { line: lineOf(content, index) }),
53
+ });
54
+ const it = noun(config);
55
+ const declared = new Set(declaredCapabilities(config));
56
+ const bytes = new TextEncoder().encode(content).byteLength;
57
+ if (bytes > config.limits.maxBytes) {
58
+ add("size", "error", `It is ${sizeWords(bytes)}; a ${it} may be at most ${sizeWords(config.limits.maxBytes)}: make it smaller (less data inline, no embedded fonts or images it doesn't need).`);
59
+ }
60
+ if (config.mode === "inline") {
61
+ const at = content.search(DOCUMENT);
62
+ if (at >= 0) {
63
+ if (fragmentOf(content) === null) {
64
+ add("document", "error", "Send an HTML fragment (styles, markup, scripts), not a whole document: this one has no body to show.", at);
65
+ }
66
+ else {
67
+ add("document", "warning", "Send an HTML fragment, not a whole document (no <!doctype>, <html>, <head> or <body>): it was taken as its body, with its head's styles and scripts.", at);
68
+ }
69
+ }
70
+ }
71
+ const frame = /<(iframe|frame|object|embed)\b/iu.exec(content);
72
+ if (frame !== null) {
73
+ add("nested-frame", "error", `Remove the <${frame[1]?.toLowerCase()}>: nested frames and plugins are taken out of a ${it} and never run. Draw it inline instead.`, frame.index);
74
+ }
75
+ const write = /\bdocument\s*\.\s*write(?:ln)?\s*\(/u.exec(content);
76
+ if (write !== null) {
77
+ add("document-write", "error", "Remove document.write: it throws here. Build elements with document.createElement, or set innerHTML.", write.index);
78
+ }
79
+ const clipboard = /\bnavigator\s*\.\s*clipboard\b|\bexecCommand\s*\(\s*["'](?:copy|cut)["']/u.exec(content);
80
+ if (clipboard !== null) {
81
+ add("clipboard", "warning", declared.has("copyText")
82
+ ? "The clipboard is closed to content: a copy button calls copyText(text) from its click."
83
+ : "The clipboard is closed to content: copying from a button doesn't work here.", clipboard.index);
84
+ }
85
+ const dialog = /(?:^|[^.\w$])(?:window\s*\.\s*)?(alert|confirm|prompt)\s*\(/u.exec(content);
86
+ if (dialog !== null) {
87
+ add("dialog", "warning", `${dialog[1]}() shows nothing here (confirm returns false, prompt null): show it in the ${it}'s own markup.`, dialog.index);
88
+ }
89
+ const form = /<form\b/iu.exec(content);
90
+ if (form !== null) {
91
+ add("form", "warning", 'Forms never submit here, and some browsers fire no submit event: use <button type="button"> and a click handler.', form.index);
92
+ }
93
+ const reported = new Set();
94
+ for (const { kind, pattern } of REACHES) {
95
+ for (const match of content.matchAll(pattern)) {
96
+ const address = match[1] ?? "";
97
+ let origin;
98
+ try {
99
+ origin = new URL(address.replace(/^ws/u, "http")).origin;
100
+ }
101
+ catch {
102
+ continue;
103
+ }
104
+ const open = (kind !== "script" &&
105
+ kind !== "style" &&
106
+ kind !== "connect" &&
107
+ address.startsWith("https:") &&
108
+ anyHttps(config, kind)) ||
109
+ egressOrigins(config, kind).some((source) => source === origin || originMatchesSource(origin, source));
110
+ if (!open && !reported.has(`${kind} ${origin}`)) {
111
+ reported.add(`${kind} ${origin}`);
112
+ add("egress", "warning", `Nothing loads from ${origin} here (${kind}): ${kind === "script" || kind === "style" ? "write it inline, or use a library from an allowed CDN" : kind === "connect" ? "the content can't call it; work from data in the content" : "put it inline as a data: URL"}.`, match.index);
113
+ }
114
+ const pinned = CDN_PACKAGE.exec(address);
115
+ if (pinned !== null && (pinned[2] === undefined || !/^@\d+\.\d+\.\d+/u.test(pinned[2]))) {
116
+ add("unpinned", "warning", `Pin an exact version of ${pinned[1]} (${pinned[1]}@1.2.3 in its URL), never @latest or a range: the code then can't change under the ${it}.`, match.index);
117
+ }
118
+ }
119
+ }
120
+ if (config.layout.kind !== "fill") {
121
+ const fixed = /position\s*:\s*fixed/iu.exec(content);
122
+ if (fixed !== null) {
123
+ add("position-fixed", "warning", `No position: fixed: the frame grows with the ${it}'s content, so a fixed element covers it. Use position: sticky or normal flow.`, fixed.index);
124
+ }
125
+ }
126
+ const opens = /target\s*=\s*["']?_blank|\bwindow\s*\.\s*open\s*\(/u.exec(content);
127
+ if (opens !== null && !declared.has("openLink")) {
128
+ add("new-window", "warning", "Nothing opens a new window here (window.open returns null, target=_blank does nothing): show it inline.", opens.index);
129
+ }
130
+ return findings;
131
+ }
@@ -0,0 +1,2 @@
1
+ declare const source: string;
2
+ export default source;