@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/docs/ADOPTING.md CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  How to put Porthole in an app, from the npm package alone. The package's `examples/` is a whole
4
4
  app that does everything below: `examples/app.mjs` is the app, runtime-agnostic;
5
- `examples/node/server.mjs` and `examples/workers/` run it. DESIGN.md says how it works and
6
- DECISIONS.md why (the P-numbers the code cites).
5
+ `examples/node/server.mjs` and `examples/workers/` run it; `examples/mcp/server.mjs` gives the
6
+ agent its tools. DESIGN.md says how it works and DECISIONS.md why (the P-numbers the code cites).
7
7
 
8
8
  ## 1. Choose how content is shown
9
9
 
@@ -17,32 +17,54 @@ DECISIONS.md why (the P-numbers the code cites).
17
17
  Start opaque if you can; add served pages when content needs storage or an address. A served app
18
18
  keeps the opaque config as its fallback for when the content domain is down.
19
19
 
20
- The config is the source of truth: `presets.inlineWidget()`, `presets.artifact()`,
21
- `presets.mcpApp()`, `presets.url()` with your options. The same config object (or the same
22
- options) must be used by the server (it puts the CSP in headers), the page (`createHost`) and the
23
- agent's manual (`compile(config).guide()`): give it one home and import it everywhere.
20
+ ## 2. Say your display kinds once
24
21
 
25
- ## 2. Opaque displays: the page only
22
+ ```js
23
+ // displays.mjs: imported by the server, the page and the agent's tools
24
+ import { defineDisplays } from "@botiverse/porthole";
25
+
26
+ export const displays = defineDisplays({
27
+ widget: { preset: "inlineWidget", options: { capabilities: { sendPrompt: {}, copyText: {} } } },
28
+ artifact: { preset: "artifact", options: { layout: { kind: "fill" } } }, // a whole-page viewer
29
+ preview: { preset: "url" }, // a running app: served only
30
+ });
31
+ ```
32
+
33
+ `displays.opaque(kind)`, `displays.served(contentSource)`, `displays.configFor(instance, source)`,
34
+ `displays.frameSources(source, { authorizeUrl })` (a CSP built without a server: a dev server, a
35
+ desktop shell) and `displays.guideConfig(kind, "served" | "opaque")` (the agent's manual) all come
36
+ from it. A kind's name is the preset name its documents carry: a stored page names `artifact`
37
+ unless its `document.preset` says otherwise.
38
+
39
+ **Fill:** a whole-page viewer says `layout: { kind: "fill" }`. The frame fills its box, and the
40
+ manual tells the agent so (the page scrolls itself; `position: fixed` works). `MountOptions.fill`
41
+ and `<PortholeFrame fill>` are deprecated: they size the frame but leave the manual saying the
42
+ height follows the content.
43
+
44
+ ## 3. Opaque displays: the page only
26
45
 
27
46
  ```js
28
- import { createHost, presets } from "@botiverse/porthole";
47
+ import { createHost } from "@botiverse/porthole";
29
48
 
30
- const config = presets.inlineWidget({ capabilities: { openLink: {} } });
31
- const host = createHost(config, {
32
- handlers: { openLink: ({ url }) => window.open(url, "_blank", "noopener") },
33
- // A gated call asks the person first, with the call's whole effect (here: the link).
34
- confirm: async (request) => window.confirm(`Open ${JSON.stringify(request.args)}?`),
49
+ const host = createHost(displays.opaque("widget"), {
50
+ handlers: { sendPrompt: ({ text }) => send(text) },
51
+ // A gated call asks the person first, with the call's whole effect.
52
+ confirm: async (request) => window.confirm(`${request.capability}: ${JSON.stringify(request.args)}?`),
35
53
  });
36
- const display = host.mount(container, { displayId: "w1", title: "A chart", scheme: "light" });
54
+ const display = host.mount(box, { displayId: "w1", title: "A chart", scheme: "light" });
37
55
  display.setContent(agentHtml, { partial: true }); // while it streams: drawn inert
38
56
  display.setContent(agentHtml); // once whole: it runs, once
39
57
  display.on("contentError", ({ message }) => tellTheAgent(message));
40
58
  ```
41
59
 
42
- React: wrap the app in `<PortholeProvider>`, then
43
- `<PortholeFrame config={config} displayId={id} title={title} scheme={scheme} content={html} partial={streaming} />`.
60
+ React: `<PortholeProvider>` near the root; `<PortholeFrame config displayId title content partial />`
61
+ per display. The provider takes what every frame shares: `scheme`, `theme` (and `themeKey`;
62
+ `cssVariableTheme(tokens)` reads the values from your page's CSS variables), `nonce` (`"auto"`
63
+ reads the page's), `handlers`, `openLink` (default: a new tab), `notify` (your own toast for what
64
+ a copy button copied), and `renderConfirm` (your own dialog: Porthole keeps the queue, runs your
65
+ yes inside its click, and counts declines). `useRunAgain()` gives a "run again" button.
44
66
 
45
- ## 3. Served pages: the host kit
67
+ ## 4. Served pages: the host kit
46
68
 
47
69
  ### Local development
48
70
 
@@ -59,109 +81,132 @@ Put it on the Public Suffix List when you can, so its labels are sites of their
59
81
  ### The server
60
82
 
61
83
  ```js
62
- import { presets } from "@botiverse/porthole";
63
84
  import { createContentHost, prefixedName, memoryTicketStore } from "@botiverse/porthole/server";
85
+ import { displays } from "./displays.mjs";
64
86
 
65
87
  const APP = "http://localhost:8790";
66
- export const pageConfig = (source) =>
67
- presets.artifact({ layout: { kind: "fill" }, isolation: "domain", contentOrigins: [source] });
68
-
69
88
  const content = createContentHost({
70
- domain: "content.localhost:8790", // "" turns content off
89
+ domain: "content.localhost:8790", // "" turns content off
71
90
  appOrigins: [APP],
72
91
  secret: process.env.PORTHOLE_SECRET, // npx porthole secret
73
92
  tickets: memoryTicketStore(), // one process; d1TicketStore(env.DB) on Workers
74
- configs: (source) => ({ artifact: pageConfig(source) }),
93
+ displays,
75
94
  name: prefixedName("a-"), // page "abc" is served on a-abc.<domain>
76
95
  instance: (proposal) => myInstance(proposal), // what a frame request asks for, as you mean it
77
96
  access: async (instance, viewer) => ((await mayView(viewer, instance)) ? { viewer: viewer.id } : null),
78
97
  source: (id, version) => myStore.page(id, version), // { html } | null
79
98
  entry: { // clean addresses: a-abc.<domain>/ in a new tab
80
- authorizeUrl: `${APP}/porthole/authorize`,
81
- at: (scope, path) => instanceAt(scope, path), // null: nothing there (404)
99
+ at: (scope, path) => instanceAt(scope, path), // null: nothing there (a 404 on the content domain)
100
+ pathOf: (instance) => pathOf(instance), // the reverse: frames come with their link
82
101
  signIn: (returnTo) => Response.redirect(`${APP}/login?next=${encodeURIComponent(returnTo)}`, 303),
83
102
  },
84
103
  });
104
+
105
+ // One mount, under /porthole: POST frames, GET authorize, GET meta, POST/DELETE handoff.
106
+ const routes = content.routes(viewerOf);
107
+ // Every request: the content domain first, then Porthole's routes, then your app.
108
+ const answer = (await content.fetch(request)) ?? (await routes(request)) ?? (await app(request));
85
109
  ```
86
110
 
87
- - **`configs`' keys** are the preset names a stored page names: an artifact page names
88
- `artifact` unless its `document.preset` says otherwise, so key it `artifact`.
89
111
  - **`instance`** gets the client's proposal (`{ scope, document }`) and returns the instance as
90
112
  your app means it, or null. Derive the scope (the origin) from what it names: the client never
91
- chooses an origin.
92
- - **`access`** returns a grant (`{ viewer }`, or `{ anonymous: true }` for a public page) or null.
93
- `authorize` (optional) checks again on every request after, for revocation.
113
+ chooses an origin. **`access`** returns a grant (`{ viewer }`, or `{ anonymous: true }` for a
114
+ public page) or null; `authorize` (optional) checks again on every request after, and
115
+ `content.forget({ scope, subject })` drops its cached answers when you revoke.
116
+ - **`viewerOf(request)`** is your app's own: who is signed in, from its cookie or token, or null.
94
117
  - **`Response.redirect` needs an absolute URL** outside a browser (Node throws on `/login`).
95
118
  - **`reserved`** is only for labels your app itself serves on the content domain (previews of a
96
119
  dev server, `p-*`). Labels nothing serves need nothing: they are a 404 there.
120
+ - **Node:** `nodeServer({ content, app: (request) => answer(request) }).listen(8790)` is the whole
121
+ server, WebSockets included, the health gate started on listen. **Workers:**
122
+ `contentHostFor((env) => options)` makes one host per `env`, and answers a plain 503 naming the
123
+ problem when the settings can't be served.
124
+ - **Health:** `health: { probe: nodeProbe(), onServedChange: (served) => … }` checks the content
125
+ domain over the real network and falls back to opaque frames while it doesn't answer.
97
126
 
98
- Routes: the content domain first, then your app.
127
+ ### The page
99
128
 
100
129
  ```js
101
- // Node (node:http)
102
- import { nodeHost, nodeProbe, toRequest, sendResponse } from "@botiverse/porthole/node";
103
- const porthole = nodeHost(content, { request: (req, res) => app(toRequest(req, "http")).then((r) => sendResponse(res, r)) });
104
- http.createServer(porthole.request).on("upgrade", porthole.upgrade).listen(8790, () => content.start());
105
-
106
- // Any fetch-style runtime (Workers, Hono, Bun, Deno)
107
- const answer = (await content.fetch(request)) ?? (await app(request));
108
-
109
- // Your app's routes
110
- "/api/frames" → content.issue(viewerOf)(request) // POST { instance } → 201 { url, origin }
111
- "/porthole/authorize" → content.authorize(viewerOf)(request) // GET, for clean addresses
112
- "/api/meta" → content.meta() // { served, contentSource, health }
130
+ import { createHost, frameFallback, portholeClient } from "@botiverse/porthole";
131
+ import { displays } from "./displays.mjs";
132
+
133
+ const porthole = portholeClient({ displays }); // the server's /porthole routes
134
+ const meta = await porthole.refresh(); // { served, contentSource, frameSources }
135
+ const display = createHost(porthole.config("artifact"), { locator: porthole })
136
+ .mount(box, { displayId: id, title, scheme: "light", ...(meta?.served ? { instance } : {}) });
137
+ if (!meta?.served) display.setContent(opaqueCopy); // frames not served now: the page, opaque
138
+ display.on("outcome", (outcome) => {
139
+ const fallback = frameFallback(outcome); // null when it loaded
140
+ if (fallback !== null) offer(fallback.title, fallback.message); // "Open this in a new tab", …
141
+ });
142
+ openButton.onclick = () => porthole.openInTab(instance); // the clean address
113
143
  ```
114
144
 
115
- `viewerOf(request)` is your app's own: who is signed in, from its cookie, or null.
145
+ `porthole.config(kind)` is the served config while frames are served, the opaque one while they
146
+ aren't, and null until the meta is known, so a frame never starts opaque and then restarts
147
+ served. A client module that fails to load shows nothing at all: catch its import and say so
148
+ (`examples/app.mjs` does).
116
149
 
117
- ### The page
150
+ React: give the provider the client, and show a kind:
118
151
 
119
- ```html
120
- <script type="module" nonce="…">
121
- // A client module that fails to load shows nothing at all: say so.
122
- import("@botiverse/porthole").then(async ({ createHost, httpLocator }) => {
123
- const meta = await (await fetch("/api/meta")).json();
124
- const host = createHost(meta.served ? servedConfig(meta.contentSource) : opaqueConfig, {
125
- locator: httpLocator("/api/frames"),
126
- });
127
- const display = host.mount(box, {
128
- displayId: id, title, scheme: "light",
129
- instance: { scope: id, document: { kind: "artifact", id, version } },
130
- });
131
- display.on("outcome", (outcome) => { if (outcome.state !== "loaded") offerNewTab(); });
132
- }, (error) => showProblem(`Porthole didn't load: ${error.message}`));
133
- </script>
152
+ ```jsx
153
+ <PortholeProvider client={porthole} scheme={mode} theme={cssVariableTheme(TOKENS)} nonce="auto">
154
+ <PortholeView display="artifact" instance={instance} content={opaqueCopy}
155
+ fallback={({ title, message, link, retry }) => <Fallback {...{ title, message, link, retry }} />} />
156
+ </PortholeProvider>
157
+ // const { link, open, copy } = usePortholeLink(instance); "Open in a new tab", "Copy link"
134
158
  ```
135
159
 
136
- - `servedOrOpaque(meta, servedConfigs, opaqueConfigs)` picks the configs and says nothing until
137
- meta is known, so a frame never starts opaque and then restarts served.
138
- - "Open in a new tab" and "Copy link" use `content.urlOf(scope, path)`, the clean address, never a
139
- ticket URL. Pass it to the page from the server.
140
- - `outcome` says how the frame loaded: `blocked` with a `reason` (`cookies`: the browser keeps no
141
- cookie in a frame, as Safari; `sign-in`; `denied`; `session`) is your cue to offer a new tab.
142
-
143
160
  ### The page's CSP
144
161
 
145
- - `frame-src`: `content.frameSources` (the content origins, and the authorize route).
146
- `embedderCsp(configs)` gives the same as a directive, from configs alone.
162
+ - `frame-src`: `content.frameSources` (the content origins, and the authorize route), also in
163
+ `GET /porthole/meta`; `displays.frameSources(source, { authorizeUrl })` without a server.
147
164
  - **An opaque display inherits your page's CSP.** Its own policy then narrows it, never widens it.
148
165
  If your page sets `default-src`, also allow what agent content uses inline:
149
166
  `img-src data: blob:`, `media-src data: blob:`, `font-src data:`, `style-src 'unsafe-inline'`,
150
167
  `worker-src blob:`. A nonce-based `script-src` works: give `createHost` the nonce
151
168
  (`HostOptions.nonce`) and the shell runs content's scripts under it.
152
- - **`form-action` holds every redirect of a submission.** If your sign-in page posts a form and
153
- then redirect entry continues to the content origin, a `form-action 'self'` blocks the last
154
- hop: leave it out there, or add the content source.
155
169
 
156
- ## 4. Cloudflare Workers
170
+ ### Sign-in
171
+
172
+ - Your sign-in page gets the authorize URL as `next`, and goes back to it when signed in. Check
173
+ it with `entryTarget(next, authorizeUrl)` (or `porthole.entryTarget(next)`): only your own
174
+ authorize route, never another site.
175
+ - **Warning: no `form-action 'self'` on a sign-in page that posts a form.** `form-action` holds
176
+ every redirect of a submission, and redirect entry continues from your sign-in through the
177
+ content origin, so the browser blocks the last hop and the person stays on your sign-in. Leave
178
+ `form-action` out of that page's CSP, or add the content source.
179
+ - **A page that authenticates with a token** (a single-page app holding a bearer token, a desktop
180
+ app) has no cookie for the authorize route to know the viewer by. Use the viewer handoff:
181
+ `entry.handoff: { id: (viewer) => viewer.id, viewer: (id) => lookUp(id) }` on the server, and
182
+ `portholeClient({ displays, headers: () => ({ authorization: `Bearer ${token()}` }), handoff: true })`
183
+ on the page. It posts to `/porthole/handoff` with your own credential, on load and when the
184
+ page regains focus; Porthole answers with a cookie that holds a key it signs (the viewer's id
185
+ and ten minutes), `HttpOnly`, scoped to `/porthole`. That beats storing the app's token in a
186
+ cookie: the key isn't a credential for your API, goes nowhere but Porthole's routes, can't be
187
+ set from another site (the POST needs your credential, and is refused from another origin), and
188
+ expires in ten minutes (an expired one costs only a quiet trip through your sign-in route).
189
+ `entry.spa: { route: "/sign-in" }` sends a signed-out person to your app's route with `next`.
190
+
191
+ ### Url mode: a relay of your own
192
+
193
+ `proxyTo` relays a url-mode app by HTTP. A relay of your own (over your own transport) uses the
194
+ same parts: `upstreamHeaders.request(headers, { origin, target, websocket })` and
195
+ `.response(...)` (the header rewrite, Porthole's cookies kept out), `statusPage({ status, title,
196
+ detail, reason, hostOrigins })` (a page that tells the frame's host why it shows nothing, desktop
197
+ schemes included), and `nodeHost`'s `appSocket` (a WebSocket, Porthole's cookies already removed).
198
+
199
+ ## 5. Cloudflare Workers
157
200
 
158
201
  ```js
159
- import { d1TicketStore } from "@botiverse/porthole/server";
160
- let app = null;
202
+ import { contentHostFor, d1TicketStore } from "@botiverse/porthole/server";
203
+
204
+ const porthole = contentHostFor((env) => ({ domain: env.CONTENT_DOMAIN, appOrigins: [env.APP_ORIGIN],
205
+ secret: env.PORTHOLE_SECRET, tickets: d1TicketStore(env.DB), displays, /* your policy */ }));
161
206
  export default {
162
207
  async fetch(request, env) {
163
- app ??= makeApp({ ...settingsFrom(env), tickets: d1TicketStore(env.DB) }); // once per isolate
164
- return (await app.content.fetch(request)) ?? app.handle(request);
208
+ return (await porthole.fetch(request, env)) ??
209
+ (await porthole.routes(request, env, viewerOf)) ?? app.fetch(request, env);
165
210
  },
166
211
  };
167
212
  ```
@@ -170,34 +215,74 @@ export default {
170
215
  `npx porthole d1-schema > migrations/0001_porthole_tickets.sql`, then
171
216
  `wrangler d1 migrations apply <db>`.
172
217
  - **One secret, `PORTHOLE_SECRET`:** `npx porthole secret`, then `wrangler secret put
173
- PORTHOLE_SECRET` (`.dev.vars` locally). At least 32 bytes; it signs tickets, cookies and
174
- entry codes.
218
+ PORTHOLE_SECRET` (`.dev.vars` locally). At least 32 bytes; it signs tickets, cookies, entry
219
+ codes and handoffs.
175
220
  - **Static assets:** set `"assets": { "run_worker_first": true }`. Otherwise Workers serves your
176
221
  static files before the Worker runs, on every host, content origins included.
177
222
  - No `nodejs_compat` needed. `wrangler dev` passes the Host through, so
178
223
  `*.content.localhost:<port>` works locally.
179
224
 
180
- ## 5. The agent's side
225
+ ## 6. The agent's side
181
226
 
182
- - `compile(config).toolDescription()` is your show tool's description; `compile(config).guide()`
183
- the manual (topics: `widget`, `interactive`, `chart`, and yours). Set `guide.toolName` and
184
- `guide.guideToolName` so they name your tools.
185
- - A tool definition, as an MCP server lists it:
227
+ ### Its tools
228
+
229
+ ```js
230
+ import { admitContent, answerGuide, checkTool, guideTool, showTool } from "@botiverse/porthole";
231
+
232
+ const config = displays.guideConfig("artifact", "served");
233
+ const tools = [showTool(config), guideTool(config), checkTool(config)]; // { name, description, inputSchema }
234
+ // show: const admitted = admitContent(config, args.html); // refuses only what certainly fails
235
+ // admitted.ok ? show(admitted.content) + admitted.note : refuse(admitted.refusal)
236
+ // guide: answerGuide(config, args) // { text } or { error }
237
+ ```
238
+
239
+ Names come from the config (`guide.toolName`, `guide.guideToolName`); the descriptions are the
240
+ manual's own words. `examples/mcp/server.mjs` wires all three as an MCP server.
241
+
242
+ - **`admitContent`** runs `lintContent` and refuses (by default, `refuseOn: "error"`) only what
243
+ would certainly fail or be cut: over the size limit, a document with no body where a fragment
244
+ goes, nested frames, `document.write`. Its refusal says exactly what to change. Everything else
245
+ (hosts outside egress, unpinned libraries, `alert`, forms, the clipboard…) comes back as
246
+ warnings with the result. `refuseOn: "never"` only warns.
247
+ - **`guideChanges(from, to)`** is the notice for the agent when a kind flips between served and
248
+ opaque (null when its manual reads the same).
249
+ - **`errors: "agent"`** sends what content throws (and what the sandbox blocks) back to the agent
250
+ once people see it: listen for `contentError` and pass it on.
251
+
252
+ ### Checking a page before people see it
253
+
254
+ `checkPage` (`@botiverse/porthole/check`) runs the content in the real sandbox at the manual's
255
+ phone and desktop widths, in light and dark, and answers a report whose `text` is a few lines for
256
+ the agent: what it threw, what the sandbox blocked, what failed to load, `console.error`, overflow
257
+ and a cut height, each problem once with where it happened (at most 8; the rest counted).
258
+
259
+ ```js
260
+ import { checkPage, playwrightDriver } from "@botiverse/porthole/check";
261
+ const report = await checkPage({ config, content: html, driver: playwrightDriver(browser) });
262
+ report.ok; report.text;
263
+ ```
264
+
265
+ It needs a browser somewhere: Chromium is best (WebKit mutes a thrown error's message in an
266
+ opaque frame, so the agent reads only "Script error."). Where:
267
+
268
+ - **A server with Chromium** (Node): `playwrightDriver(await chromium.launch())`.
269
+ - **An agent on a person's machine, maybe without Chromium** (Ferry's daemon): run
270
+ `lintContent` there (no browser needed), and send `check_page` to your server, which runs
271
+ `checkPage`; or use Playwright where it is installed (`examples/mcp/server.mjs` falls back to
272
+ the lint, saying so).
273
+ - **Cloudflare Workers:** Browser Rendering, through a CDP session:
186
274
 
187
275
  ```js
188
- { name: "show_page", description: compiled.toolDescription(),
189
- inputSchema: { type: "object", required: ["title", "html"],
190
- properties: { title: { type: "string" }, html: { type: "string", description: "The whole HTML document" } } } }
276
+ import puppeteer from "@cloudflare/puppeteer";
277
+ import { cdpDriver, checkPage } from "@botiverse/porthole/check";
278
+ import page from "@botiverse/porthole/check/page"; // the check page's script, bundled
279
+ const browser = await puppeteer.launch(env.BROWSER);
280
+ const tab = await browser.newPage();
281
+ const report = await checkPage({ config, content, page, driver: cdpDriver(() => tab.createCDPSession()) });
282
+ await browser.close();
191
283
  ```
192
284
 
193
- - **Fill:** a whole-page viewer says `layout: { kind: "fill" }` in its config. The frame then fills
194
- its box, and the manual tells the agent so (the page scrolls itself; `position: fixed` works).
195
- `MountOptions.fill` and `<PortholeFrame fill>` are deprecated: they size the frame but leave the
196
- manual saying the height follows the content.
197
- - `errors: "agent"` sends what content throws (and what the sandbox blocks) back to the agent:
198
- listen for `contentError` and pass it on.
199
-
200
- ## 6. Conformance: prove your integration
285
+ ## 7. Conformance: prove your integration
201
286
 
202
287
  `@botiverse/porthole/conformance` runs Porthole's suite (egress and escape probes, the served
203
288
  cases, redirect entry) against your app's real page, its CSP and session, in Playwright:
@@ -214,8 +299,8 @@ import { defineHostConformance } from "@botiverse/porthole/conformance";
214
299
  defineHostConformance(test, {
215
300
  name: "my-app",
216
301
  open: async (page) => { /* sign in, open the page that shows content */ },
217
- issue: { url: "/api/frames" },
218
- config: () => pageConfig("http://*.content.localhost:8790"),
302
+ issue: { url: "/porthole/frames" },
303
+ displays, contentSource: "http://*.content.localhost:8790",
219
304
  instances: { artifact: (scope, version) => ({ scope, document: { kind: "artifact", id: "conformance", version } }) },
220
305
  entry: { url: (scope) => `http://a-t-${scope}.content.localhost:8790/v/1`, unknown: "derive" },
221
306
  });
@@ -236,13 +321,14 @@ The suite names its own scopes, so an app serves them through a **test mode**
236
321
  (`examples/app.mjs`: `PORTHOLE_CONFORMANCE=1`): the test page under `t-<scope>`, and a private
237
322
  page. **Never ship test mode**: with it, anyone signed in can make content origins of their
238
323
  choosing. `onDemand(make)` memoizes fixtures made the first time a case asks (a page published
239
- on demand); `instances` and `entry.url` may be async.
324
+ on demand); `instances` and `entry.url` may be async. The tests are located at your
325
+ `defineHostConformance` call, so `playwright test porthole.spec.mjs` selects them.
240
326
 
241
327
  The leak probes run opaque displays on your page: where its own CSP closes what a probe needs,
242
328
  the probe reports itself inapplicable, saying which directive. Those are facts about your page's
243
329
  opaque fallback, not failures.
244
330
 
245
- ## 7. Expected, and how to tell
331
+ ## 8. Expected, and how to tell
246
332
 
247
333
  - Chromium logs `Unrecognized Content-Security-Policy directive 'webrtc'` for every frame: the
248
334
  directive closes WebRTC where an engine knows it, and is ignored where it doesn't.
@@ -255,14 +341,15 @@ opaque fallback, not failures.
255
341
  `entry.at` says has nothing) is a 404 on the content domain: it never reaches your sign-in.
256
342
  - Host errors name the content origin and leave out ticket URLs.
257
343
 
258
- ## 8. Reference
344
+ ## 9. Reference
259
345
 
260
346
  | Import | What |
261
347
  | --- | --- |
262
- | `@botiverse/porthole` | `createHost`, `presets`, `compile`, `embedderCsp`, `httpLocator`, `servedOrOpaque` |
263
- | `@botiverse/porthole/react` | `PortholeProvider`, `PortholeFrame` |
264
- | `@botiverse/porthole/server` | `createContentHost`, `prefixedName`, `memoryTicketStore`, `d1TicketStore`, `contentDomain`, `conformancePage`, the callbacks' types |
265
- | `@botiverse/porthole/node` | `nodeHost`, `nodeProbe`, `toRequest`, `sendResponse` |
348
+ | `@botiverse/porthole` | `createHost`, `presets`, `defineDisplays`, `portholeClient`, `frameFallback`, `entryTarget`, `lintContent`, `admitContent`, `showTool`, `guideTool`, `checkTool`, `answerGuide`, `guideChanges`, `compile` |
349
+ | `@botiverse/porthole/react` | `PortholeProvider`, `PortholeFrame`, `PortholeView`, `usePortholeLink`, `cssVariableTheme`, `useRunAgain` |
350
+ | `@botiverse/porthole/server` | `createContentHost` (`routes`, `forget`), `contentHostFor`, `prefixedName`, `memoryTicketStore`, `d1TicketStore`, `upstreamHeaders`, `statusPage`, `conformancePage`, the callbacks' types |
351
+ | `@botiverse/porthole/node` | `nodeServer`, `nodeHost`, `nodeProbe`, `toRequest`, `sendResponse` |
352
+ | `@botiverse/porthole/check` | `checkPage`, `playwrightDriver`, `cdpDriver`; `/check/page`, the check page's script |
266
353
  | `@botiverse/porthole/mcp` | the MCP Apps adapter (views, the sandbox proxy) |
267
354
  | `@botiverse/porthole/conformance` | `defineHostConformance`, `conformanceProjects`, `onDemand`, `conformancePage` |
268
355
 
package/docs/DECISIONS.md CHANGED
@@ -1809,3 +1809,149 @@ artifact-only app lacks, two snippet bugs, no word on the page's CSP, two ways t
1809
1809
  which left the manual wrong), Workers specifics, and local development.
1810
1810
  **Revisit when** a second cold adoption (after 0.3) finds friction these don't cover.
1811
1811
 
1812
+
1813
+ ## P072 · 2026-10-12 · Host kit 0.3: the client, the bootstrap and the relay, so adopters stop writing glue · Accepted
1814
+
1815
+ **Decision.** After 0.2.2 the server's content file is policy and little
1816
+ else; the glue moved to the client, the bootstrap and url mode. Ferry still writes about 1,650
1817
+ lines of glue and workarounds, Raft about 450 (notes/porthole-0.3-audit.md). 0.3 adds, all
1818
+ additive:
1819
+
1820
+ 1. **`defineDisplays(kinds)`** (core): one registry for every kind an app shows.
1821
+
1822
+ ```ts
1823
+ const displays = defineDisplays({
1824
+ widget: { preset: "inlineWidget", options: { capabilities: { sendPrompt: {} } } },
1825
+ page: { preset: "artifact", options: { layout: { kind: "fill" } } },
1826
+ preview:{ preset: "url", options: {} }, // url mode: served only
1827
+ });
1828
+ displays.opaque("widget"); // PortholeConfig
1829
+ displays.served(contentSource); // Record<kind, PortholeConfig> | null, memoized
1830
+ displays.configFor(instance, contentSource | null); // by the document's kind and preset
1831
+ displays.frameSources(contentSource, { authorizeUrl }); // for a CSP built without a ContentHost (Vite, Electron)
1832
+ displays.guideConfig("widget", "served" | "opaque"); // the agent's manual, without real origins
1833
+ ```
1834
+
1835
+ `createContentHost({ displays })` and `defineHostConformance({ displays })` take it in place of
1836
+ `configs` and `config(instance)` (both stay).
1837
+ 2. **Conventional routes and bootstrap** (/server, /node):
1838
+ - `content.routes(viewerOf, { prefix = "/porthole" })`: `POST frames` (issue), `GET authorize`,
1839
+ `GET meta`, `POST handoff` (item 6), one mount. `entry.authorizeUrl` defaults to
1840
+ `${appOrigins[0]}${prefix}/authorize`.
1841
+ - `GET meta` answers `ContentClientMeta`: `{ served, contentSource, frameSources, health }`.
1842
+ - `issue` answers 201 `{ url, origin, link? }`: `link` is the clean address, where
1843
+ `entry.pathOf(instance)` names the instance's path.
1844
+ - `contentHostFor((env) => options)` on Workers: one host per `env`, a fail-closed 503 naming
1845
+ the problem (logged once), `fetch(request, env)` answering the content domain first.
1846
+ - `nodeServer({ content, app, upgrade?, appSocket? })`: the `http.Server`, the gate started on
1847
+ listen and stopped on close.
1848
+ 3. **The client served kit** (core, React):
1849
+ - `portholeClient({ base = "/porthole", headers?, credentials?, displays })`: `meta()`,
1850
+ `subscribe()`, `config(kind)` (served or opaque, null until meta is known), the locator,
1851
+ `link(instance)`, `openInTab(instance)` (a blank tab inside the click, then the link).
1852
+ - React: `<PortholeProvider client>` and `<PortholeView display="page" instance={…}
1853
+ content={…} fallback={({ kind, message, link, retry }) => …} />`, where `kind` is
1854
+ `needs-tab | denied | expired | failed | timeout`, worded as Porthole's pages word them.
1855
+ `usePortholeLink(instance)` gives `{ link, open, copy }`.
1856
+ 4. **React ergonomics:** provider `scheme`, `theme` with `themeKey`, `cssVariableTheme(tokens)`,
1857
+ `nonce: "auto"`, `openLink`, `notify` (skin the copy notice), `renderConfirm(request, answer)`
1858
+ (the app draws the dialog; Porthole keeps the gates, the one-at-a-time queue and decline
1859
+ counting); content errors deduplicated per run; `useRunAgain()` for a "run again" button.
1860
+ 5. **The url-mode relay kit** (/server, /node): `upstreamHeaders.request/response` (the header
1861
+ rewrite `proxyTo` uses, on `Headers` or raw pairs, WebSockets too); `statusPage(…)` (P070's
1862
+ fallback included); `nodeHost`'s `appSocket` gets the request with Porthole's cookies removed;
1863
+ `content.forget({ scope?, subject? })` drops cached `authorize` answers.
1864
+ 6. **Viewer handoff for token-authenticated apps:** `POST handoff`, called by the signed-in app
1865
+ with its own token (`client.handoff()`), sets an `HttpOnly` cookie scoped to the authorize
1866
+ path holding a short-lived viewer key Porthole signs (never the app's token);
1867
+ `entry.handoff: { id(viewer), viewer(id) }` says who a viewer is and turns it back. `entry.spa: { route }` gives the
1868
+ default `signIn` for a single-page app, with `entryTarget(next)` as the open-redirect guard.
1869
+ 7. **If cheap:** `health.onServedChange(served)`, deduplicated; `log` also takes a
1870
+ `{ info, warn, error }` logger; `prefixedNames({ w: …, f: … })` for several prefixes; a
1871
+ `location` on a mount, used once before the locator (pre-located frames).
1872
+
1873
+ **Why.** Each item deletes code both apps (or every adopter with that need) wrote the same way,
1874
+ and three of them already drift: Ferry's desktop CSP lacks the authorize route, its copied status
1875
+ page lacks P070's fallback, and clean addresses are computed two ways.
1876
+ **Rejected.** A framework-specific server adapter (Hono, Express): `routes` is a fetch handler
1877
+ any of them mounts in one line.
1878
+ **Decided in review:**
1879
+ - The default prefix is `/porthole`, overridable (`createContentHost({ prefix })`), and `issue`
1880
+ moves under it (`POST /porthole/frames`), so one mount serves frames, authorize, meta and
1881
+ handoff, and an embedding CSP, a dev proxy or a desktop CSP each need one path. Apps move their
1882
+ old routes themselves (`issue(viewerOf)` and `authorize(viewerOf)` still exist for that).
1883
+ - The handoff cookie lasts 10 minutes, refreshed whenever the app's page loads or regains focus
1884
+ (`portholeClient({ handoff: true })`, at most every 30 s); an expired one costs only a quiet
1885
+ trip through the app's sign-in route. The POST needs the app's own credential (`viewerOf` must
1886
+ name a viewer) and is refused from another origin (`Origin`, or `Sec-Fetch-Site` where there is
1887
+ no `Origin`), so no other site can set or clear it. The key is Porthole-signed (HMAC under the
1888
+ secret, apart from session keys), names the viewer's id and its expiry, and the cookie is
1889
+ `HttpOnly`, `SameSite=Lax`, scoped to the prefix path (`__Secure-` on https). It is no
1890
+ credential for the app's API, unlike the app's token stored in a cookie (which Ferry did), which
1891
+ would ride on every request to the app origin, for as long as the token lives.
1892
+ - Item 7: `health.onServedChange` and logger adapters only.
1893
+
1894
+ **Measured.** The example app on the new routes and client passes the whole suite on three
1895
+ engines; `PortholeView`, its fallback and `renderConfirm` run in the React spec.
1896
+
1897
+ ## P073 · 2026-10-12 · The agent's side: check a page before people see it; tools with names and schemas · Accepted
1898
+
1899
+ **Decision.** Today an agent learns its page broke only after a person
1900
+ looked (Ferry, at its next turn, at most 5 errors) or never (Raft). Porthole already has the
1901
+ parts: the shell's error capture, the conformance harness's `launch` at a width and a scheme, and
1902
+ a browser check behind every line of the manual. 0.3 exposes them:
1903
+
1904
+ 1. **`lintContent(config, content): Finding[]`** (core, pure, any runtime): what can be told
1905
+ without running it, worded as the manual words it, each rule tied to the manual's limit id:
1906
+ over `maxBytes`; a document where a fragment is shown (or the reverse); `document.write`;
1907
+ nested frames and plugins; `navigator.clipboard` and `execCommand("copy")` (use `copyText`);
1908
+ `alert`/`confirm`/`prompt`; a `<form>` that submits; hosts outside egress in `src`, `href`,
1909
+ `fetch` and imports; an unpinned library (`@latest`, a range); `position: fixed` in a flow
1910
+ layout; `target=_blank` without `openLink`. `{ rule, severity, message, line? }`.
1911
+ 2. **`checkPage(options): Promise<CheckReport>`** (`@botiverse/porthole/check`): runs the content
1912
+ in the real sandbox (the harness, the production CSP) at each width and scheme (defaults from
1913
+ the config: the manual's phone and desktop widths, light and dark unless the config is
1914
+ unthemed), and reports per run: errors (thrown, rejected, "Blocked by the sandbox"), CSP
1915
+ blocks, failed loads, `console.error`/`warn`, the height and whether the limit clips it,
1916
+ horizontal overflow, optional screenshots; plus `lint`, `ok` and one agent-readable `text`.
1917
+ Drivers: `playwrightDriver(browser)` (Node), and `cdpDriver(session)` over any CDP session
1918
+ (Puppeteer's, or `@cloudflare/puppeteer`'s on Cloudflare Browser Rendering), so a Worker can
1919
+ check too. The harness ships as a string module, so no file system is needed.
1920
+ 3. **Tool definitions** (core): `showTool(config)`, `guideTool(config)`, `checkTool(config)`, each
1921
+ `{ name, description, inputSchema }` (JSON Schema; names from `guide.toolName` and
1922
+ `guideToolName`, the topics an enum of the built-in and the config's own); `answerGuide(config,
1923
+ args)` validates and answers; `guideChanges(from, to)`, the notice for the agent when a display
1924
+ kind flips between served and opaque (null when the manual doesn't change). An MCP server
1925
+ example in `examples/mcp/` wires show, guide and check.
1926
+ 4. **The manual's own examples pass the check:** a test runs `checkPage` on every
1927
+ `GUIDE_EXAMPLES` entry under every preset, at the manual's widths, in light and dark
1928
+ (OBJECTIVES criterion 5).
1929
+
1930
+ **Why.** It is the one change that improves what agents make rather than what hosts write, and
1931
+ both apps asked for errors to reach the agent before a person does.
1932
+ **Rejected.** Running content on the host's server without a browser (jsdom and the like): it
1933
+ doesn't apply CSP, layout or the sandbox, so it would pass pages that break.
1934
+ **Decided in review:**
1935
+ - The show tool refuses by default (`admitContent`, `refuseOn: "error"`), but only on a narrow
1936
+ set of deterministic errors that would certainly fail or be cut: over the size limit, a whole
1937
+ document where a fragment goes when it can't be taken as its body, nested frames and plugins,
1938
+ `document.write`. Everything heuristic is a warning returned with the result. A host sets the
1939
+ policy (`refuseOn: "never"`). A refusal says exactly what to change, and to call the tool again.
1940
+ - Contrast: later.
1941
+ - `checkPage` must work where the host has no browser: an agent on a person's machine lints
1942
+ locally and sends the check to its server (or uses Playwright where installed); a Worker uses
1943
+ Browser Rendering through `cdpDriver`, with the check page's script imported
1944
+ (`@botiverse/porthole/check/page`). The report's text is short enough for an agent's context:
1945
+ each problem once, with where it happened, at most 8 (`maxProblems`), the rest counted.
1946
+
1947
+ **How it runs.** The check page (bundled from `src/check/page.ts`) is served at a fixed origin
1948
+ the driver answers itself (`https://porthole-check.invalid`: the shell needs a real host origin),
1949
+ mounts the content with `createHost` under its own CSP, opaque (a served config's content with the
1950
+ same CSP; an MCP Apps view as a page with its egress), and puts a small script first in the
1951
+ content that reports errors, rejections, CSP blocks, failed loads, `console.error`/`warn` and the
1952
+ document's width to the page by `postMessage`. Height comes from the display's own resize events.
1953
+
1954
+ **Measured.** Every `GUIDE_EXAMPLES` entry passes under the inline, artifact, whole-page viewer
1955
+ and MCP Apps presets at the manual's widths in light and dark, on three engines
1956
+ (`leak/check.spec.ts`); a broken widget is told each problem once; the CDP driver runs on
1957
+ Chromium.