@botiverse/porthole 0.4.1 → 0.5.1

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 (77) hide show
  1. package/README.md +3 -1
  2. package/dist/bridge/bridge.d.ts +24 -2
  3. package/dist/bridge/bridge.js +102 -17
  4. package/dist/bridge/navigation.d.ts +11 -0
  5. package/dist/bridge/navigation.js +30 -0
  6. package/dist/bridge/refusal.d.ts +53 -0
  7. package/dist/bridge/refusal.js +121 -0
  8. package/dist/bridge/types.d.ts +51 -6
  9. package/dist/check/lint.js +2 -2
  10. package/dist/check/page-source.js +1 -1
  11. package/dist/check/page.js +10 -0
  12. package/dist/compile/policy.d.ts +5 -0
  13. package/dist/compile/policy.js +18 -1
  14. package/dist/config/capabilities.d.ts +30 -2
  15. package/dist/config/capabilities.js +13 -0
  16. package/dist/config/schema.d.ts +7 -0
  17. package/dist/config/validate.js +14 -3
  18. package/dist/conformance/harness/page.js +1 -0
  19. package/dist/conformance/harness-source.js +1 -1
  20. package/dist/displays/displays.d.ts +1 -1
  21. package/dist/guide/guide.js +58 -8
  22. package/dist/host/create-host.js +18 -3
  23. package/dist/host/types.d.ts +25 -1
  24. package/dist/index.d.ts +5 -3
  25. package/dist/index.js +4 -1
  26. package/dist/libraries/files.generated.d.ts +1 -0
  27. package/dist/libraries/files.generated.js +8 -0
  28. package/dist/libraries/libraries.d.ts +36 -0
  29. package/dist/libraries/libraries.js +40 -0
  30. package/dist/mcp/adapter.js +49 -5
  31. package/dist/presets/presets.d.ts +15 -0
  32. package/dist/presets/presets.js +27 -2
  33. package/dist/protocol/live-data.d.ts +27 -0
  34. package/dist/protocol/live-data.js +98 -0
  35. package/dist/protocol/mcp-apps.d.ts +15 -0
  36. package/dist/protocol/mcp-apps.js +17 -0
  37. package/dist/protocol/shell-adapter.js +49 -4
  38. package/dist/react/dialog.js +2 -0
  39. package/dist/react/frame.d.ts +30 -1
  40. package/dist/react/frame.js +63 -1
  41. package/dist/server/libraries.d.ts +7 -0
  42. package/dist/server/libraries.js +27 -0
  43. package/dist/server/server.js +2 -1
  44. package/dist/shell/runtime.d.ts +5 -1
  45. package/dist/shell/runtime.js +196 -6
  46. package/docs/ADOPTING.md +89 -3
  47. package/docs/DECISIONS.md +221 -0
  48. package/docs/DESIGN.md +28 -10
  49. package/package.json +3 -1
  50. package/src/bridge/bridge.ts +136 -16
  51. package/src/bridge/navigation.ts +34 -0
  52. package/src/bridge/refusal.ts +151 -0
  53. package/src/bridge/types.ts +57 -4
  54. package/src/check/lint.ts +2 -1
  55. package/src/check/page.ts +12 -0
  56. package/src/compile/policy.ts +19 -1
  57. package/src/config/capabilities.ts +26 -1
  58. package/src/config/schema.ts +7 -0
  59. package/src/config/validate.ts +21 -3
  60. package/src/conformance/harness/page.ts +1 -0
  61. package/src/displays/displays.ts +1 -1
  62. package/src/guide/guide.ts +71 -7
  63. package/src/host/create-host.ts +19 -3
  64. package/src/host/types.ts +23 -1
  65. package/src/index.ts +22 -0
  66. package/src/libraries/files.generated.ts +8 -0
  67. package/src/libraries/libraries.ts +64 -0
  68. package/src/mcp/adapter.ts +63 -5
  69. package/src/presets/presets.ts +46 -3
  70. package/src/protocol/live-data.ts +138 -0
  71. package/src/protocol/mcp-apps.ts +19 -0
  72. package/src/protocol/shell-adapter.ts +50 -5
  73. package/src/react/dialog.tsx +2 -0
  74. package/src/react/frame.tsx +93 -0
  75. package/src/server/libraries.ts +28 -0
  76. package/src/server/server.ts +2 -1
  77. package/src/shell/runtime.ts +196 -6
@@ -1,5 +1,6 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { createContext, useCallback, useContext, useEffect, useEffectEvent, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, } from "react";
3
+ import { isRefused, reasonOf, Refused } from "../bridge/refusal.js";
3
4
  import { writeClipboard } from "../host/clipboard.js";
4
5
  import { createHost } from "../host/create-host.js";
5
6
  import { ConfirmDialog } from "./dialog.js";
@@ -45,6 +46,25 @@ export function PortholeProvider(props) {
45
46
  const confirm = useCallback((request, proceed) => own.current !== undefined
46
47
  ? own.current(request, proceed)
47
48
  : new Promise((resolve) => setQueue((waiting) => [...waiting, { request, resolve, proceed }])), []);
49
+ // The host's consent and cache as of the last render (P079), read when a frame asks.
50
+ const ownConsent = useRef(props.consent);
51
+ const ownCached = useRef(props.cached);
52
+ useLayoutEffect(() => {
53
+ ownConsent.current = props.consent;
54
+ ownCached.current = props.cached;
55
+ });
56
+ const consent = useCallback((request) => {
57
+ const given = ownConsent.current;
58
+ if (isRefused(given)) {
59
+ throw given;
60
+ }
61
+ return given?.(request) ?? false;
62
+ }, []);
63
+ // A Refused for every frame below, by value (an inline one starts nothing again).
64
+ const refusesAll = useByValue(isRefused(props.consent) ? reasonOf(props.consent) : undefined);
65
+ const cached = useCallback((args, context) => ownCached.current?.(args, context), []);
66
+ const consents = props.consent !== undefined;
67
+ const caches = props.cached !== undefined;
48
68
  // The default copyText: the host's page writes the clipboard (in the frame's click, which
49
69
  // activated this page too) and shows the person what went on it, or offers to copy it.
50
70
  const [notice, setNotice] = useState(null);
@@ -111,6 +131,9 @@ export function PortholeProvider(props) {
111
131
  heights,
112
132
  confirm,
113
133
  copyText,
134
+ ...(consents ? { consent } : {}),
135
+ ...(refusesAll === undefined ? {} : { refusesAll }),
136
+ ...(caches ? { cached } : {}),
114
137
  ...(hostInfo === undefined ? {} : { hostInfo }),
115
138
  ...(locates ? { locate } : {}),
116
139
  ...(nonce === undefined ? {} : { nonce }),
@@ -124,6 +147,11 @@ export function PortholeProvider(props) {
124
147
  heights,
125
148
  confirm,
126
149
  copyText,
150
+ consents,
151
+ consent,
152
+ refusesAll,
153
+ caches,
154
+ cached,
127
155
  hostInfo,
128
156
  locates,
129
157
  locate,
@@ -265,13 +293,17 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
265
293
  const config = useByValue(frame.config);
266
294
  const instance = useByValue(frame.instance);
267
295
  const fills = config.mode === "url" || frame.fill === true || config.layout.kind === "fill";
296
+ // A consent that refuses everything (P080), this frame's or else the provider's, by value: a
297
+ // display made with it needs no data handlers, so a change makes the display again.
298
+ const ownRefusal = useByValue(isRefused(frame.consent) ? reasonOf(frame.consent) : undefined);
299
+ const refusesAll = frame.consent === undefined ? page.refusesAll : ownRefusal;
268
300
  // The latest props, read when the display calls back (never during render).
269
301
  const latest = useEffectEvent(() => frame);
270
302
  // The provider's scheme and theme, read when used: a flip or a new themeKey (a new context
271
303
  // value) re-themes the running display, never makes it again (#9, P074). What a display is
272
304
  // made with comes from the provider's stable parts below.
273
305
  const latestPage = useEffectEvent(() => page);
274
- const { handlers: pageHandlers, copyText: pageCopyText, confirm: pageConfirm, hostInfo, locate, nonce, } = page;
306
+ const { handlers: pageHandlers, copyText: pageCopyText, confirm: pageConfirm, consent: pageConsent, cached: pageCached, hostInfo, locate, nonce, } = page;
275
307
  const notify = useEffectEvent((event, detail) => {
276
308
  switch (event) {
277
309
  case "initialized":
@@ -303,6 +335,9 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
303
335
  case "navigated":
304
336
  frame.onNavigated?.();
305
337
  return;
338
+ case "navigationBlocked":
339
+ frame.onNavigationBlocked?.(detail);
340
+ return;
306
341
  case "refused": {
307
342
  const { capability, refusal } = detail;
308
343
  frame.onRefused?.(capability, refusal);
@@ -351,6 +386,8 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
351
386
  }
352
387
  }
353
388
  const asks = first.confirm !== undefined || pageConfirm !== undefined;
389
+ const asksConsent = first.consent !== undefined || pageConsent !== undefined;
390
+ const caches = first.cached !== undefined || pageCached !== undefined;
354
391
  let display;
355
392
  try {
356
393
  display = createHost(config, {
@@ -367,6 +404,27 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
367
404
  }, proceed),
368
405
  }
369
406
  : {}),
407
+ ...(refusesAll !== undefined
408
+ ? { consent: new Refused(refusesAll.code, refusesAll.message) }
409
+ : asksConsent
410
+ ? {
411
+ consent: (request) => {
412
+ const given = latest().consent ?? pageConsent ?? (() => false);
413
+ if (isRefused(given)) {
414
+ throw given;
415
+ }
416
+ return given({
417
+ ...request,
418
+ display: { ...request.display, id: latest().displayId, title: latest().title },
419
+ });
420
+ },
421
+ }
422
+ : {}),
423
+ ...(caches
424
+ ? {
425
+ cached: (args, context) => (latest().cached ?? pageCached)?.(args, named(context)),
426
+ }
427
+ : {}),
370
428
  theme: (each) => (latest().theme ?? latestPage().theme)?.(each) ?? {},
371
429
  ...(hostInfo === undefined ? {} : { hostInfo }),
372
430
  ...(locate === undefined ? {} : { locator: { locate } }),
@@ -391,6 +449,7 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
391
449
  "resize",
392
450
  "error",
393
451
  "navigated",
452
+ "navigationBlocked",
394
453
  "refused",
395
454
  "muted",
396
455
  "outcome",
@@ -423,6 +482,9 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
423
482
  pageHandlers,
424
483
  pageCopyText,
425
484
  pageConfirm,
485
+ pageConsent,
486
+ pageCached,
487
+ refusesAll,
426
488
  hostInfo,
427
489
  locate,
428
490
  nonce,
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Porthole's vendored libraries (P079), as every content origin serves them under `LIBRARY_PATH`:
3
+ * fixed files, the same for everyone, so no ticket or cookie is asked for and they may be cached
4
+ * for good (a path's bytes never change). Same-site only: content origins load them, no one else.
5
+ * Null for any other path (the reserved prefix's 404 answers it).
6
+ */
7
+ export declare function libraryFile(pathname: string, method: string): Response | null;
@@ -0,0 +1,27 @@
1
+ import { LIBRARY_FILES } from "../libraries/files.generated.js";
2
+ import { LIBRARY_PATH } from "../libraries/libraries.js";
3
+ /**
4
+ * Porthole's vendored libraries (P079), as every content origin serves them under `LIBRARY_PATH`:
5
+ * fixed files, the same for everyone, so no ticket or cookie is asked for and they may be cached
6
+ * for good (a path's bytes never change). Same-site only: content origins load them, no one else.
7
+ * Null for any other path (the reserved prefix's 404 answers it).
8
+ */
9
+ export function libraryFile(pathname, method) {
10
+ if (!pathname.startsWith(LIBRARY_PATH) || (method !== "GET" && method !== "HEAD")) {
11
+ return null;
12
+ }
13
+ const body = Object.hasOwn(LIBRARY_FILES, pathname) ? LIBRARY_FILES[pathname] : undefined;
14
+ if (body === undefined) {
15
+ return null;
16
+ }
17
+ return new Response(method === "HEAD" ? null : body, {
18
+ headers: {
19
+ "content-type": pathname.endsWith(".js")
20
+ ? "text/javascript; charset=utf-8"
21
+ : "text/plain; charset=utf-8",
22
+ "cache-control": "public, max-age=31536000, immutable",
23
+ "cross-origin-resource-policy": "same-site",
24
+ "x-content-type-options": "nosniff",
25
+ },
26
+ });
27
+ }
@@ -5,6 +5,7 @@ import { base32, createKeys, newTicket, ticketId } from "./keys.js";
5
5
  import { randomBytes } from "./crypto.js";
6
6
  import { isHostLabel, reservedLabels } from "./naming.js";
7
7
  import { enterPage, pageScript, SESSION_PATH, statusPage } from "./pages.js";
8
+ import { libraryFile } from "./libraries.js";
8
9
  import { memoryTicketStore } from "./tickets.js";
9
10
  /**
10
11
  * Paths on a content origin. Porthole's own live under `/__porthole/`; on a url-mode app's origin
@@ -938,7 +939,7 @@ export function createServer(options) {
938
939
  if (url.pathname === ENTRY_PATH && authorizeUrl !== null) {
939
940
  return await redeem(request, url, label);
940
941
  }
941
- const script = pageScript(url.pathname);
942
+ const script = pageScript(url.pathname) ?? libraryFile(url.pathname, method);
942
943
  if (script !== null) {
943
944
  return script;
944
945
  }
@@ -16,7 +16,11 @@
16
16
  * shadow DOM through `setHTMLUnsafe`, `parseHTMLUnsafe`, `document.write`);
17
17
  * 5. keeps content off the clipboard: the async Clipboard API refuses, `execCommand` won't copy or
18
18
  * cut, and copy and cut events never reach content, so what a person copies is what they
19
- * selected (P051). Copy buttons go through the host (`copyText`, P052).
19
+ * selected (P051). Copy buttons go through the host (`copyText`, P052);
20
+ * 6. cancels every navigation the frame starts to another document (P079), before it sends a
21
+ * request: a navigation carries data out in its URL, and the embedding page's `frame-src`,
22
+ * the wall for that, must let served frames reach their own content origins. (Opaque frames
23
+ * get no navigate events: there `frame-src` is the wall.)
20
24
  * A whole document (an artifact page, an MCP Apps view) is never written in: it is parsed inert,
21
25
  * imported, and its scripts run in order, as a fragment's are.
22
26
  *
@@ -16,7 +16,11 @@
16
16
  * shadow DOM through `setHTMLUnsafe`, `parseHTMLUnsafe`, `document.write`);
17
17
  * 5. keeps content off the clipboard: the async Clipboard API refuses, `execCommand` won't copy or
18
18
  * cut, and copy and cut events never reach content, so what a person copies is what they
19
- * selected (P051). Copy buttons go through the host (`copyText`, P052).
19
+ * selected (P051). Copy buttons go through the host (`copyText`, P052);
20
+ * 6. cancels every navigation the frame starts to another document (P079), before it sends a
21
+ * request: a navigation carries data out in its URL, and the embedding page's `frame-src`,
22
+ * the wall for that, must let served frames reach their own content origins. (Opaque frames
23
+ * get no navigate events: there `frame-src` is the wall.)
20
24
  * A whole document (an artifact page, an MCP Apps view) is never written in: it is parsed inert,
21
25
  * imported, and its scripts run in order, as a fragment's are.
22
26
  *
@@ -72,6 +76,41 @@ export const SHELL_RUNTIME = String.raw `(() => {
72
76
  }
73
77
  }
74
78
 
79
+ // No navigation to another document (P079): a frame that navigates itself carries data out in
80
+ // the URL, and the embedding page's frame-src, the other wall, lets served frames reach every
81
+ // content origin. (An opaque frame gets no navigate events, as the spec says for opaque
82
+ // origins, measured: there frame-src is the wall, P033.) The navigate event comes before any request for every
83
+ // navigation this document starts (location, a link, window.open(…, "_self"), a refresh), and
84
+ // cancelling it stops it. Ours is the first listener, and reads the event through the platform's
85
+ // own getters, kept now, so content can neither stop it nor lie to it. Same-document ones (an
86
+ // anchor) go on, and so do reloads: the same address, on the frame's own origin (or none, in a
87
+ // srcdoc frame), which history can change only within that origin. The host's own (a new
88
+ // frame) are none of this document's. Each one stopped is told to the host (P080), as an error
89
+ // report: below, once the shell can speak.
90
+ let navigationBlocked = (_url) => {};
91
+ const navigationApi = window.navigation;
92
+ const getterOf = (proto, name) => {
93
+ const descriptor = proto ? Object.getOwnPropertyDescriptor(proto, name) : undefined;
94
+ return descriptor && typeof descriptor.get === "function" ? descriptor.get : null;
95
+ };
96
+ const navigateProto = typeof NavigateEvent === "function" ? NavigateEvent.prototype : null;
97
+ const destinationOf = getterOf(navigateProto, "destination");
98
+ const navigationTypeOf = getterOf(navigateProto, "navigationType");
99
+ const destinationProto = typeof NavigationDestination === "function" ? NavigationDestination.prototype : null;
100
+ const sameDocumentOf = getterOf(destinationProto, "sameDocument");
101
+ const urlOf = getterOf(destinationProto, "url");
102
+ const preventNavigation = Event.prototype.preventDefault;
103
+ const applyOf = Reflect.apply;
104
+ if (navigationApi && typeof navigationApi.addEventListener === "function" && destinationOf !== null && sameDocumentOf !== null && navigationTypeOf !== null) {
105
+ navigationApi.addEventListener("navigate", (event) => {
106
+ const destination = applyOf(destinationOf, event, []);
107
+ if (!applyOf(sameDocumentOf, destination, []) && applyOf(navigationTypeOf, event, []) !== "reload") {
108
+ applyOf(preventNavigation, event, []);
109
+ navigationBlocked(urlOf === null ? "" : String(applyOf(urlOf, destination, [])));
110
+ }
111
+ }, true);
112
+ }
113
+
75
114
  // No nested frames (each would be a fresh realm with WebRTC intact), no resource hints and no
76
115
  // refreshes (they reach the network outside the CSP's fetch directives). Removed as they are
77
116
  // added: a mutation observer's microtask runs before a child frame's document loads.
@@ -442,13 +481,27 @@ export const SHELL_RUNTIME = String.raw `(() => {
442
481
  reported += 1;
443
482
  send({ method: "notifications/message", params: { level: "error", logger: "porthole", data: String(message).slice(0, 2000) } });
444
483
  };
445
- const send = (message) => {
446
- if (plan.protocol === "shell" && window.parent !== window) {
447
- // Nothing secret is ever said from here, so any parent may hear it; what it hears is the
448
- // content's word, which the host gates before it acts on it.
484
+ // Nothing secret is ever said from here, so any parent may hear it; what it hears is the
485
+ // content's word, which the host gates before it acts on it.
486
+ const post = (message) => {
487
+ if (window.parent !== window) {
449
488
  window.parent.postMessage(Object.assign({ jsonrpc: "2.0" }, message), "*");
450
489
  }
451
490
  };
491
+ const send = (message) => {
492
+ if (plan.protocol === "shell") {
493
+ post(message);
494
+ }
495
+ };
496
+ // A navigation the guard above stopped (P080): one of the run's error reports, told even where
497
+ // the content speaks for itself (an MCP Apps view), in Porthole's own notification.
498
+ navigationBlocked = (url) => {
499
+ if (!declared("reportError") || reported >= plan.maxErrorReports || url === "") {
500
+ return;
501
+ }
502
+ reported += 1;
503
+ post({ method: "porthole/navigation-blocked", params: { url: url.slice(0, 4096) } });
504
+ };
452
505
 
453
506
  // A parsed tree's scripts are held (each replaced by a numbered marker) and run later, in order,
454
507
  // as the page's parser would run them: each made again, live, in its marker's place, and each
@@ -710,6 +763,132 @@ export const SHELL_RUNTIME = String.raw `(() => {
710
763
  });
711
764
  }
712
765
 
766
+ // Data (P079): readData reads a resource the host names, subscribeData follows one, through
767
+ // MCP's resources/* requests, which the host gates (the viewer's consent, a rate). A value is the
768
+ // first content's: JSON parsed when it says it is JSON, else its text.
769
+ let resourceUpdated = (_uri) => {};
770
+ const valueOf = (result) => {
771
+ const first = result && Array.isArray(result.contents) ? result.contents[0] : undefined;
772
+ if (first === null || typeof first !== "object") {
773
+ return undefined;
774
+ }
775
+ if (typeof first.text === "string") {
776
+ if (/(^|[/+])json(\s*;|$)/i.test(String(first.mimeType || ""))) {
777
+ try {
778
+ return JSON.parse(first.text);
779
+ } catch (_) {}
780
+ }
781
+ return first.text;
782
+ }
783
+ return typeof first.blob === "string" ? first.blob : undefined;
784
+ };
785
+ const staleOf = (result) => Boolean(result && result._meta && result._meta["porthole/stale"] === true);
786
+ const later = (error) => setTimeout(() => {
787
+ throw error;
788
+ });
789
+ if (declared("readData")) {
790
+ lock(window, "readData", (uri) => request("resources/read", { uri: String(uri) }).then(valueOf));
791
+ }
792
+ if (declared("subscribeData")) {
793
+ // One subscription per URI, however many follow it; a read at a time, one more if it changed
794
+ // meanwhile; a late follower gets the last value at once.
795
+ const followed = new Map();
796
+ const tell = (entry, result) => {
797
+ entry.last = result;
798
+ const value = valueOf(result);
799
+ const info = { stale: staleOf(result), uri: entry.uri };
800
+ for (const listener of Array.from(entry.listeners)) {
801
+ try {
802
+ listener.onData(value, info);
803
+ } catch (error) {
804
+ later(error);
805
+ }
806
+ }
807
+ };
808
+ const fail = (entry, error) => {
809
+ for (const listener of Array.from(entry.listeners)) {
810
+ if (typeof listener.onError === "function") {
811
+ try {
812
+ listener.onError(error);
813
+ } catch (thrown) {
814
+ later(thrown);
815
+ }
816
+ }
817
+ }
818
+ };
819
+ const refresh = (entry) => {
820
+ if (entry.reading) {
821
+ entry.again = true;
822
+ return;
823
+ }
824
+ entry.reading = true;
825
+ request("resources/read", { uri: entry.uri })
826
+ .then((result) => {
827
+ if (followed.get(entry.uri) === entry) {
828
+ tell(entry, result);
829
+ }
830
+ }, (error) => fail(entry, error))
831
+ .then(() => {
832
+ entry.reading = false;
833
+ if (entry.again && followed.get(entry.uri) === entry) {
834
+ entry.again = false;
835
+ refresh(entry);
836
+ }
837
+ });
838
+ };
839
+ resourceUpdated = (uri) => {
840
+ const entry = followed.get(uri);
841
+ if (entry !== undefined) {
842
+ refresh(entry);
843
+ }
844
+ };
845
+ lock(window, "subscribeData", (uri, onData, onError) => {
846
+ if (typeof onData !== "function") {
847
+ throw new TypeError("subscribeData(uri, onData, onError): onData must be a function");
848
+ }
849
+ const key = String(uri);
850
+ const listener = { onData, onError };
851
+ let entry = followed.get(key);
852
+ if (entry === undefined) {
853
+ const made = { uri: key, listeners: new Set(), reading: false, again: false, last: undefined };
854
+ entry = made;
855
+ followed.set(key, made);
856
+ request("resources/subscribe", { uri: key }).then(() => {
857
+ if (followed.get(key) === made) {
858
+ refresh(made);
859
+ }
860
+ }, (error) => {
861
+ if (followed.get(key) === made) {
862
+ followed.delete(key);
863
+ }
864
+ fail(made, error);
865
+ });
866
+ } else if (entry.last !== undefined) {
867
+ const known = entry;
868
+ Promise.resolve().then(() => {
869
+ if (known.listeners.has(listener)) {
870
+ try {
871
+ onData(valueOf(known.last), { stale: staleOf(known.last), uri: key });
872
+ } catch (error) {
873
+ later(error);
874
+ }
875
+ }
876
+ });
877
+ }
878
+ entry.listeners.add(listener);
879
+ const mine = entry;
880
+ return () => {
881
+ if (!mine.listeners.delete(listener) || mine.listeners.size > 0) {
882
+ return;
883
+ }
884
+ if (followed.get(key) === mine) {
885
+ followed.delete(key);
886
+ request("resources/unsubscribe", { uri: key }).catch(() => {});
887
+ }
888
+ };
889
+ });
890
+ }
891
+
713
892
  window.addEventListener("error", (event) => {
714
893
  const error = event.error;
715
894
  const where = event.lineno ? " (line " + event.lineno + ")" : "";
@@ -861,7 +1040,13 @@ export const SHELL_RUNTIME = String.raw `(() => {
861
1040
  if (waiting !== undefined) {
862
1041
  pending.delete(data.id);
863
1042
  if (data.error) {
864
- waiting.reject(new Error(String(data.error.message || "refused")));
1043
+ // A refusal says why (P080): its code, and a sentence to show the person.
1044
+ const why = data.error.data !== null && typeof data.error.data === "object" ? data.error.data : {};
1045
+ const error = new Error(String(typeof why.message === "string" && why.message !== "" ? why.message : data.error.message || "refused"));
1046
+ if (typeof why.code === "string") {
1047
+ error.code = why.code;
1048
+ }
1049
+ waiting.reject(error);
865
1050
  } else {
866
1051
  waiting.resolve(data.result);
867
1052
  }
@@ -879,6 +1064,11 @@ export const SHELL_RUNTIME = String.raw `(() => {
879
1064
  case "ui/notifications/host-context-changed":
880
1065
  applyTheme(params);
881
1066
  break;
1067
+ case "notifications/resources/updated":
1068
+ if (typeof params.uri === "string") {
1069
+ resourceUpdated(params.uri);
1070
+ }
1071
+ break;
882
1072
  case "ui/resource-teardown":
883
1073
  case "ping":
884
1074
  if (data.id !== undefined) {
package/docs/ADOPTING.md CHANGED
@@ -46,13 +46,14 @@ height follows the content.
46
46
 
47
47
  Egress is what content may load and send out: scripts, styles, fonts, images, audio and video, and
48
48
  data (fetch, WebSocket). Every preset starts closed, and a kind opens more only through its
49
- `options.egress`. There are three levels:
49
+ `options.egress`. There are three levels, and Porthole's own libraries for served content:
50
50
 
51
51
  | Level | Config (`options`) | What it opens | The risk it re-opens | Typical host | The agent's manual says | Why | Tested by |
52
52
  | --- | --- | --- | --- | --- | --- | --- | --- |
53
53
  | **Closed** (the default) | nothing to write | Nothing from outside the frame: content runs on what it carries (inline code, `data:` and `blob:` URLs). | None. | Widgets that draw their own SVG and CSS; any host that hasn't decided yet. | `Network: none. Nothing loads from outside` (and `write everything inline`) | [P006](DECISIONS.md#p006--2026-10-11--egress-is-closed-by-default-including-channels-a-frame-csp-doesnt-cover--accepted), [P022](DECISIONS.md#p022--2026-10-11--every-preset-starts-with-egress-closed-library-cdns-are-a-one-line-opt-in--accepted) | probes `1.connect`, `2.resources`, `3.webrtc`, `4.*` (nested frames), `5.*` (navigating out), `8.*` (resource hints), `10.self`; served `served.domain.egress` |
54
54
  | **Library CDNs** (`LIBRARY_CDNS`, plus script hosts of your own) | `egress: LIBRARY_CDNS`; more script hosts: `egress: { ...LIBRARY_CDNS, script: [...LIBRARY_CDNS.script, "https://cdn.example.com"] }` | Scripts, styles, fonts, images and data from cdnjs, jsDelivr, unpkg and esm.sh; Google Fonts; scripts only from three libraries' own CDNs (Tailwind's Play CDN, jQuery, Plotly). Nothing else. | Code you don't control runs in the frame (a compromised or look-alike package), still inside the sandbox and egress; and a path requested from a CDN is a narrow channel out, read by the CDN's operator. The manual tells agents to pin versions. | Ferry's widgets, Raft Artifacts' pages: agents load Chart.js, ECharts, d3, Mermaid, Tailwind, jQuery, Plotly. | `scripts, styles, fonts, images and data (fetch, WebSocket) from https://cdnjs.cloudflare.com` …, `scripts from https://cdn.tailwindcss.com, https://code.jquery.com, https://cdn.plot.ly` and `pin an exact version` | [P078](DECISIONS.md#p078--2026-10-13--library_cdns-adds-tailwinds-jquerys-and-plotlys-own-cdns-for-scripts-only--accepted), [P022](DECISIONS.md#p022--2026-10-11--every-preset-starts-with-egress-closed-library-cdns-are-a-one-line-opt-in--accepted), [P048](DECISIONS.md#p048--2026-10-11--artifact-pages-reach-library-cdns-only-by-the-hosts-config--accepted) | `leak/cdn.spec.ts` (a CDN library loads only when the config opens it, opaque and served; another origin never; the libraries' own CDNs serve scripts and nothing else); probes `1.connect`, `2.resources` (an allowed origin loads, no other does) |
55
55
  | **Passive from any https site** (`anyHttps`, on top of either) | `egress: { ...LIBRARY_CDNS, anyHttps: ["img"] }`; closed but for them: `egress: { anyHttps: ["img"] }` | The passive kinds you name (`img`, `media`, `font`) from any https site. Never scripts, styles, data, workers or frames, and never `http:`: a config naming another kind is refused. | Any site an image names learns that someone viewed the content, and from which address; content can send data out in an image URL to a server of its choosing (the channel P006 closes); whoever owns an image controls what it shows, inside the frame. | A host showing content that already exists, with hotlinked media: Raft's HTML attachment previews, reports whose `<img>` point at other sites (the case P059 was written for). | `images from any https site` (`fonts, images, audio and video from any https site` for all three) | [P059](DECISIONS.md#p059--2026-10-11--passive-content-may-load-from-any-https-site-by-the-hosts-explicit-choice--accepted), [P062](DECISIONS.md#p062--2026-10-11--serveddomainegress-holds-a-host-to-its-own-configs-egress--accepted) | `leak/cdn.spec.ts` (a hotlinked image loads; a script, a stylesheet and a fetch to the same site never reach it; without the flag, nothing does); served `served.domain.egress` (the image must reach an https canary; scripts, styles, fetches and frames never), `leak/served/any-https.spec.ts` |
56
+ | **Porthole's libraries** (`egress.libraries`, served kinds only; on in `presets.liveWidget`) | `egress: { libraries: true }` with `isolation: "domain"` | Chart.js 4.5.1 and D3 7.9.0 as scripts, from the frame's own origin (`/__porthole/lib/…`, served by `/server` on every content origin). Nothing from outside. | None from outside: the requests reach your content server, which serves fixed, pinned files. | Live widgets, which read your data and must have no network of their own (P079). | `Libraries, served from this frame's own address` with a `<script>` line for each | [P079](DECISIONS.md#p079--2026-10-15--live-widgets-no-network-of-their-own-portholes-libraries-on-their-origin-the-hosts-data-behind-the-viewers-consent-and-frames-that-never-navigate-away--accepted) | `test/libraries.test.ts`; `leak/served/live.spec.ts` (they load and draw; an external script, a stylesheet, an image and every fetch reach no oracle) |
56
57
 
57
58
  How to decide: **start closed; add `LIBRARY_CDNS` if agents use libraries; add passive `anyHttps`
58
59
  only for existing content with hotlinks**, and only the kinds it hotlinks (usually `img`). An
@@ -85,6 +86,90 @@ export const displays = defineDisplays({
85
86
  directive. The manual names exactly the origins the CSP allows (`test/agreement.test.ts`), and
86
87
  DESIGN.md § "Egress hardening, each with its test" is the long form.
87
88
 
89
+ ### Live widgets: content that reads your data
90
+
91
+ A live widget shows your data, current, read as the person viewing it, with no network of its own
92
+ ([P079](DECISIONS.md#p079--2026-10-15--live-widgets-no-network-of-their-own-portholes-libraries-on-their-origin-the-hosts-data-behind-the-viewers-consent-and-frames-that-never-navigate-away--accepted)).
93
+ Its only way out is your host: `readData` (MCP `resources/read`) and `subscribeData` (MCP
94
+ `resources/subscribe`, `resources/unsubscribe`, `notifications/resources/updated`).
95
+
96
+ ```js
97
+ import { defineDisplays, Refused } from "@botiverse/porthole";
98
+
99
+ export const displays = defineDisplays({
100
+ // No egress option exists for it; served, it loads Porthole's Chart.js and D3 from its origin.
101
+ tile: { preset: "liveWidget", options: { capabilities: { openLink: {} } } },
102
+ });
103
+
104
+ createHost(displays.configFor(instance, contentSource), {
105
+ locator,
106
+ handlers: {
107
+ // As the viewer: your own access rules, never the author's. Return MCP's read result; refuse
108
+ // what you don't serve with a Refused, whose code and sentence the widget shows (P080).
109
+ readData: async ({ uri }, { displayId }) => {
110
+ if (!servedUri(uri)) throw new Refused("not_allowed", "This widget can read issues only.");
111
+ return {
112
+ contents: [{ uri, mimeType: "application/json", text: JSON.stringify(await load(uri)) }],
113
+ };
114
+ },
115
+ // Call changed() when it changes (the content reads it again), or changed(result) to send it.
116
+ subscribeData: ({ uri }, { changed, signal }) => {
117
+ const stop = realtime.on(uri, () => changed());
118
+ signal.addEventListener("abort", stop);
119
+ },
120
+ },
121
+ // Asked once per display, before its first data call: may this widget read this viewer's data?
122
+ // Remember the answer per viewer and widget; a no refuses every data call (`denied`).
123
+ consent: async ({ display }) => allowedBefore(display) ?? (await askTheViewer(display)),
124
+ // Optional: your last copy, shown at once (stale), then the fresh read.
125
+ cached: ({ uri }) => lastCopy(uri),
126
+ });
127
+ ```
128
+
129
+ - **Your handlers decide what a URI may name.** Answer only the resources you mean widgets to read
130
+ (a whitelist of URI shapes), with the viewer's rights. The content's URI is its word.
131
+ - **Consent is your UI.** Without a `consent` function every data call is refused (fail closed).
132
+ React: `PortholeProvider` and `PortholeFrame` take `consent` and `cached`. A consent function
133
+ that throws a `Refused` gives that answer, kept like `false`; anything else it throws is no
134
+ answer yet (the next call asks again).
135
+ - **A page where data must not run** (beside a frame that reaches the network, below): pass a
136
+ `Refused` as `consent` and no data handlers. Every data call is refused with it, nothing is asked,
137
+ and the widget shows your sentence:
138
+
139
+ ```js
140
+ createHost(displays.configFor(instance, contentSource), {
141
+ locator,
142
+ consent: new Refused("not_allowed", "Live data shows on the dashboard."),
143
+ });
144
+ ```
145
+
146
+ Any other capability you declare still needs its handler.
147
+ - **Refusals tell the widget why** (P080). A refused call's JSON-RPC error carries
148
+ `data: { code, message }`; the shell's `readData` rejects (and `subscribeData`'s `onError` is
149
+ called) with an `Error` whose `code` and `message` are those. `code` is `consent_required` (no
150
+ answer yet), `denied` (the viewer said no), `rate_limited`, `not_allowed` (not here, or not this
151
+ URI) or `failed` (your handler threw); `message` is your `Refused`'s sentence, else Porthole's.
152
+ The manual tells the agent to draw the widget without the data, with that sentence. A handler's
153
+ other errors are `failed` in Porthole's words: their messages stay yours.
154
+ - **Rates stay gates**: 120 reads and 60 subscriptions a minute per display by default; change them
155
+ with the capability's `gates` (keep `"consent"` in the list).
156
+ - **Your page's CSP**: send `displays.embedderCsp(source, …)` (`frame-src` of your content origins
157
+ and the authorize route, nothing else). It keeps a frame from navigating to an outside site; the
158
+ shell keeps a served frame from navigating to another content origin (P079), and tells you:
159
+ `display.on("navigationBlocked", ({ url }) => …)` (React `onNavigationBlocked`) gets the address
160
+ whole, and `contentError` a sentence naming it without its query, for the agent (P080). Only
161
+ where the config declares `reportError`, and only served frames: an opaque frame's navigations
162
+ get no events (you hear `navigated` when one replaces its document).
163
+ - **Keep live widgets off pages with frames that reach the network.** A frame can `postMessage` any
164
+ frame on its page, and nothing in it can stop that: a url-mode app (a dev server's preview) or an
165
+ `anyHttps` display beside a live widget could be handed what it read. Displays with closed egress
166
+ or `LIBRARY_CDNS` are fine beside it.
167
+ - **Opaque live widgets** (no content domain) work, without libraries: the manual tells the agent
168
+ to draw with SVG and CSS. An opaque frame's only wall against navigating itself away is your
169
+ page's `frame-src` (the shell's guard gets no events in an opaque origin), so show them on pages
170
+ that frame no content origins (`frame-src 'none'`), which is what `defineDisplays` gives a page
171
+ without a content domain.
172
+
88
173
  ## 3. Opaque displays: the page only
89
174
 
90
175
  ```js
@@ -344,8 +429,9 @@ in the config also has the manual name them). The descriptions are the manual's
344
429
  warnings with the result. `refuseOn: "never"` only warns.
345
430
  - **`guideChanges(from, to)`** is the notice for the agent when a kind flips between served and
346
431
  opaque (null when its manual reads the same).
347
- - **`errors: "agent"`** sends what content throws (and what the sandbox blocks) back to the agent
348
- once people see it: listen for `contentError` and pass it on.
432
+ - **`errors: "agent"`** sends what content throws (and what the sandbox blocks, and a navigation
433
+ the shell stopped, P080) back to the agent once people see it: listen for `contentError` and pass
434
+ it on.
349
435
 
350
436
  ### Checking a page before people see it
351
437