@botiverse/porthole 0.5.1 → 0.7.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 (167) hide show
  1. package/README.md +41 -0
  2. package/dist/bridge/bridge.d.ts +13 -0
  3. package/dist/bridge/bridge.js +208 -13
  4. package/dist/bridge/navigation.d.ts +1 -6
  5. package/dist/bridge/navigation.js +11 -0
  6. package/dist/bridge/refusal.d.ts +5 -1
  7. package/dist/bridge/refusal.js +16 -0
  8. package/dist/bridge/types.d.ts +41 -4
  9. package/dist/check/check.d.ts +19 -3
  10. package/dist/check/check.js +55 -8
  11. package/dist/check/files.d.ts +26 -0
  12. package/dist/check/files.js +307 -0
  13. package/dist/check/instrument.d.ts +3 -0
  14. package/dist/check/lint.js +31 -12
  15. package/dist/check/page-source.js +1 -1
  16. package/dist/check/page.js +14 -0
  17. package/dist/check/tools.d.ts +23 -0
  18. package/dist/check/tools.js +27 -3
  19. package/dist/compile/policy.d.ts +34 -0
  20. package/dist/compile/policy.js +74 -0
  21. package/dist/config/capabilities.d.ts +62 -3
  22. package/dist/config/capabilities.js +20 -0
  23. package/dist/config/schema.d.ts +32 -0
  24. package/dist/config/validate.d.ts +1 -1
  25. package/dist/config/validate.js +74 -5
  26. package/dist/conformance/harness-source.js +1 -1
  27. package/dist/conformance/index.d.ts +1 -0
  28. package/dist/conformance/index.js +2 -0
  29. package/dist/conformance/runtime.d.ts +58 -0
  30. package/dist/conformance/runtime.js +314 -0
  31. package/dist/files/paths.d.ts +99 -0
  32. package/dist/files/paths.js +263 -0
  33. package/dist/files/types.d.ts +24 -0
  34. package/dist/files/types.js +83 -0
  35. package/dist/guide/gates.d.ts +3 -0
  36. package/dist/guide/gates.js +19 -0
  37. package/dist/guide/guide.d.ts +2 -0
  38. package/dist/guide/guide.js +44 -32
  39. package/dist/guide/limits.js +4 -4
  40. package/dist/guide/runtime.d.ts +13 -0
  41. package/dist/guide/runtime.js +202 -0
  42. package/dist/host/create-host.js +45 -0
  43. package/dist/host/locate.js +8 -0
  44. package/dist/host/locator.js +7 -0
  45. package/dist/host/types.d.ts +18 -0
  46. package/dist/index.d.ts +13 -4
  47. package/dist/index.js +16 -3
  48. package/dist/isolation/types.d.ts +8 -0
  49. package/dist/presets/presets.d.ts +6 -0
  50. package/dist/presets/presets.js +1 -0
  51. package/dist/protocol/adapter.d.ts +4 -0
  52. package/dist/protocol/mcp-apps.d.ts +6 -0
  53. package/dist/protocol/mcp-apps.js +6 -0
  54. package/dist/protocol/runtime-calls.d.ts +28 -0
  55. package/dist/protocol/runtime-calls.js +113 -0
  56. package/dist/protocol/shell-adapter.js +52 -3
  57. package/dist/react/dialog.js +31 -0
  58. package/dist/react/frame.d.ts +13 -0
  59. package/dist/react/frame.js +6 -0
  60. package/dist/runtime/contract.d.ts +193 -0
  61. package/dist/runtime/contract.js +216 -0
  62. package/dist/runtime/db.d.ts +153 -0
  63. package/dist/runtime/db.js +398 -0
  64. package/dist/runtime/declaration.d.ts +86 -0
  65. package/dist/runtime/declaration.js +266 -0
  66. package/dist/runtime/levels.d.ts +33 -0
  67. package/dist/runtime/levels.js +41 -0
  68. package/dist/runtime/requests.d.ts +125 -0
  69. package/dist/runtime/requests.js +199 -0
  70. package/dist/runtime/segments.d.ts +8 -0
  71. package/dist/runtime/segments.js +14 -0
  72. package/dist/runtime/types.generated.d.ts +1 -0
  73. package/dist/runtime/types.generated.js +19 -0
  74. package/dist/server/files.d.ts +57 -0
  75. package/dist/server/files.js +338 -0
  76. package/dist/server/host.d.ts +44 -2
  77. package/dist/server/host.js +42 -2
  78. package/dist/server/index.d.ts +5 -2
  79. package/dist/server/index.js +5 -1
  80. package/dist/server/keys.d.ts +8 -0
  81. package/dist/server/keys.js +34 -0
  82. package/dist/server/pseudonym.d.ts +9 -0
  83. package/dist/server/pseudonym.js +20 -0
  84. package/dist/server/server.d.ts +0 -5
  85. package/dist/server/server.js +468 -24
  86. package/dist/server/types.d.ts +118 -5
  87. package/dist/shell/document.d.ts +27 -0
  88. package/dist/shell/document.js +46 -2
  89. package/dist/shell/legacy.d.ts +21 -0
  90. package/dist/shell/legacy.js +63 -0
  91. package/dist/shell/plan.d.ts +17 -1
  92. package/dist/shell/plan.js +13 -2
  93. package/dist/shell/runtime.d.ts +2 -1
  94. package/dist/shell/runtime.js +114 -46
  95. package/dist/shell/use.d.ts +15 -0
  96. package/dist/shell/use.js +235 -0
  97. package/docs/ADOPTING.md +142 -5
  98. package/docs/ARCHITECTURE.md +34 -5
  99. package/docs/DECISIONS.md +716 -7
  100. package/docs/DESIGN.md +97 -3
  101. package/package.json +3 -1
  102. package/src/bridge/bridge.ts +281 -17
  103. package/src/bridge/navigation.ts +12 -0
  104. package/src/bridge/refusal.ts +16 -0
  105. package/src/bridge/types.ts +46 -4
  106. package/src/check/check.ts +100 -14
  107. package/src/check/files.ts +384 -0
  108. package/src/check/instrument.ts +3 -0
  109. package/src/check/lint.ts +33 -12
  110. package/src/check/page.ts +14 -0
  111. package/src/check/tools.ts +52 -3
  112. package/src/compile/policy.ts +92 -0
  113. package/src/config/capabilities.ts +49 -2
  114. package/src/config/schema.ts +32 -0
  115. package/src/config/validate.ts +107 -5
  116. package/src/conformance/index.ts +7 -0
  117. package/src/conformance/runtime.ts +573 -0
  118. package/src/files/paths.ts +323 -0
  119. package/src/files/types.ts +101 -0
  120. package/src/guide/gates.ts +25 -0
  121. package/src/guide/guide.ts +78 -52
  122. package/src/guide/limits.ts +4 -4
  123. package/src/guide/runtime.ts +244 -0
  124. package/src/host/create-host.ts +55 -0
  125. package/src/host/locate.ts +10 -0
  126. package/src/host/locator.ts +11 -0
  127. package/src/host/types.ts +18 -0
  128. package/src/index.ts +121 -0
  129. package/src/isolation/types.ts +8 -0
  130. package/src/presets/presets.ts +7 -0
  131. package/src/protocol/adapter.ts +3 -1
  132. package/src/protocol/mcp-apps.ts +7 -0
  133. package/src/protocol/runtime-calls.ts +138 -0
  134. package/src/protocol/shell-adapter.ts +56 -2
  135. package/src/react/dialog.tsx +33 -0
  136. package/src/react/frame.tsx +19 -0
  137. package/src/runtime/contract.ts +305 -0
  138. package/src/runtime/db.ts +530 -0
  139. package/src/runtime/declaration.ts +378 -0
  140. package/src/runtime/levels.ts +69 -0
  141. package/src/runtime/requests.ts +339 -0
  142. package/src/runtime/segments.ts +17 -0
  143. package/src/runtime/types.generated.ts +19 -0
  144. package/src/server/files.ts +425 -0
  145. package/src/server/host.ts +84 -3
  146. package/src/server/index.ts +22 -0
  147. package/src/server/keys.ts +53 -0
  148. package/src/server/pseudonym.ts +21 -0
  149. package/src/server/server.ts +565 -26
  150. package/src/server/types.ts +124 -4
  151. package/src/shell/document.ts +74 -4
  152. package/src/shell/legacy.ts +64 -0
  153. package/src/shell/plan.ts +37 -3
  154. package/src/shell/runtime.ts +114 -46
  155. package/src/shell/use.ts +235 -0
  156. package/types/runtime/v1/artifact.d.ts +50 -0
  157. package/types/runtime/v1/assets.d.ts +43 -0
  158. package/types/runtime/v1/chat.d.ts +13 -0
  159. package/types/runtime/v1/clipboard.d.ts +14 -0
  160. package/types/runtime/v1/comments.d.ts +24 -0
  161. package/types/runtime/v1/context.d.ts +16 -0
  162. package/types/runtime/v1/data.d.ts +29 -0
  163. package/types/runtime/v1/db.d.ts +110 -0
  164. package/types/runtime/v1/downloads.d.ts +22 -0
  165. package/types/runtime/v1/links.d.ts +13 -0
  166. package/types/runtime/v1/porthole.d.ts +44 -0
  167. package/types/runtime/v1/user.d.ts +19 -0
@@ -20,7 +20,8 @@
20
20
  * 6. cancels every navigation the frame starts to another document (P079), before it sends a
21
21
  * request: a navigation carries data out in its URL, and the embedding page's `frame-src`,
22
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.)
23
+ * get no navigate events: there `frame-src` is the wall.) A page that comes with files may
24
+ * open its set's other pages, under its version's own address, and nothing else (P084).
24
25
  * A whole document (an artifact page, an MCP Apps view) is never written in: it is parsed inert,
25
26
  * imported, and its scripts run in order, as a fragment's are.
26
27
  *
@@ -35,6 +36,13 @@
35
36
  export const SHELL_RUNTIME = String.raw `(() => {
36
37
  "use strict";
37
38
  const plan = __PLAN__;
39
+ // A page that came with files, answered at its ticket's address (P083): its own address first,
40
+ // before anything loads, so its relative addresses are its files' (and the ticket leaves).
41
+ if (plan.files && typeof plan.files.address === "string" && location.href !== plan.files.address) {
42
+ try {
43
+ history.replaceState(null, "", plan.files.address);
44
+ } catch (_) {}
45
+ }
38
46
  // The embedding page's nonce, where it gave one (a srcdoc frame inherits its policy): every
39
47
  // script the shell runs for the content carries it.
40
48
  const nonce = document.currentScript && document.currentScript.nonce ? document.currentScript.nonce : "";
@@ -88,6 +96,31 @@ export const SHELL_RUNTIME = String.raw `(() => {
88
96
  // frame) are none of this document's. Each one stopped is told to the host (P080), as an error
89
97
  // report: below, once the shell can speak.
90
98
  let navigationBlocked = (_url) => {};
99
+ // A page that comes with files (P084): another page of its own set, under the version's own
100
+ // address, is a page of the same content and opens in the frame (the host is told first, so it
101
+ // takes the next load for that page, not for content that left). Anything else stays stopped:
102
+ // another path of the origin, a file that isn't a page, another origin.
103
+ let navigating = (_url) => {};
104
+ let filesBase = plan.files && typeof plan.files.base === "string" ? plan.files.base : null;
105
+ // Every address the page's files had (P083: a sealed one is renewed): what reports say as "./".
106
+ const filesBases = filesBase === null ? [] : [filesBase];
107
+ // A frame's sealed files' address is its access: nothing the shell reports names it (P083).
108
+ const SEALED = /(?:https?:\/\/[^\s"'<>\/]+)?\/__porthole\/f\/[A-Za-z0-9_-]{20,}\//g;
109
+ const ownAddresses = (text) => {
110
+ let out = String(text);
111
+ for (const base of filesBases) {
112
+ out = out.split(base).join("./");
113
+ }
114
+ return out.replace(SEALED, "./");
115
+ };
116
+ const ownPage = (url) => {
117
+ if (filesBase === null || typeof url !== "string" || url.indexOf(filesBase) !== 0) {
118
+ return false;
119
+ }
120
+ const path = url.slice(filesBase.length).split("#")[0].split("?")[0];
121
+ const last = path.slice(path.lastIndexOf("/") + 1);
122
+ return last === "" || last.indexOf(".") < 0 || /\.html?$/i.test(last);
123
+ };
91
124
  const navigationApi = window.navigation;
92
125
  const getterOf = (proto, name) => {
93
126
  const descriptor = proto ? Object.getOwnPropertyDescriptor(proto, name) : undefined;
@@ -105,8 +138,13 @@ export const SHELL_RUNTIME = String.raw `(() => {
105
138
  navigationApi.addEventListener("navigate", (event) => {
106
139
  const destination = applyOf(destinationOf, event, []);
107
140
  if (!applyOf(sameDocumentOf, destination, []) && applyOf(navigationTypeOf, event, []) !== "reload") {
141
+ const url = urlOf === null ? "" : String(applyOf(urlOf, destination, []));
142
+ if (ownPage(url)) {
143
+ navigating(url);
144
+ return;
145
+ }
108
146
  applyOf(preventNavigation, event, []);
109
- navigationBlocked(urlOf === null ? "" : String(applyOf(urlOf, destination, [])));
147
+ navigationBlocked(url);
110
148
  }
111
149
  }, true);
112
150
  }
@@ -321,7 +359,7 @@ export const SHELL_RUNTIME = String.raw `(() => {
321
359
  // the person makes (their keys, their menu) copies their selection as the browser makes it: no
322
360
  // copy or cut listener of the content's runs, so none can swap what goes on the clipboard.
323
361
  const noClipboard = function () {
324
- return Promise.reject(new DOMException("Content can't use the clipboard here" + (declared("copyText") ? ": call copyText(text) from a click" : ""), "NotAllowedError"));
362
+ return Promise.reject(new DOMException("Content can't use the clipboard here" + (declared("copyText") ? (plan.runtime ? ': call (await porthole.use("clipboard")).copy(text) from a click' : ": call copyText(text) from a click") : ""), "NotAllowedError"));
325
363
  };
326
364
  if (typeof Clipboard === "function") {
327
365
  for (const name of ["write", "writeText", "read", "readText"]) {
@@ -479,7 +517,7 @@ export const SHELL_RUNTIME = String.raw `(() => {
479
517
  return;
480
518
  }
481
519
  reported += 1;
482
- send({ method: "notifications/message", params: { level: "error", logger: "porthole", data: String(message).slice(0, 2000) } });
520
+ send({ method: "notifications/message", params: { level: "error", logger: "porthole", data: ownAddresses(message).slice(0, 2000) } });
483
521
  };
484
522
  // Nothing secret is ever said from here, so any parent may hear it; what it hears is the
485
523
  // content's word, which the host gates before it acts on it.
@@ -500,8 +538,41 @@ export const SHELL_RUNTIME = String.raw `(() => {
500
538
  return;
501
539
  }
502
540
  reported += 1;
503
- post({ method: "porthole/navigation-blocked", params: { url: url.slice(0, 4096) } });
541
+ post({ method: "porthole/navigation-blocked", params: { url: ownAddresses(url).slice(0, 4096) } });
504
542
  };
543
+ // Another page of the set opening in the frame (P084): the host takes the next load for it.
544
+ navigating = (url) => {
545
+ post({ method: "porthole/navigating", params: { url: ownAddresses(url).slice(0, 4096) } });
546
+ };
547
+ // A sealed files' address opens the page's files on its own for a while (P083): renewed before
548
+ // it ends, the page moved to the new one in place (the same page, the same history entry). Its
549
+ // modules keep the address they loaded from; the server serves their own loads till the session
550
+ // ends.
551
+ if (filesBase !== null && typeof plan.files.expires === "number") {
552
+ const nativeFetch = window.fetch.bind(window);
553
+ const replace = History.prototype.replaceState;
554
+ const renewIn = (expires) => Math.max(30000, expires - Date.now() - 300000);
555
+ const renew = () => {
556
+ nativeFetch(filesBase + "__porthole/renew", { credentials: "omit", cache: "no-store" })
557
+ .then((answer) => (answer.ok ? answer.json() : null))
558
+ .then((renewed) => {
559
+ if (!renewed || typeof renewed.base !== "string" || typeof renewed.expires !== "number" || renewed.base.indexOf(location.origin + "/__porthole/f/") !== 0 || renewed.base.slice(-1) !== "/") {
560
+ return;
561
+ }
562
+ const here = location.href;
563
+ if (here.indexOf(filesBase) === 0) {
564
+ try {
565
+ applyOf(replace, history, [history.state, "", renewed.base + here.slice(filesBase.length)]);
566
+ } catch (_) {}
567
+ }
568
+ filesBase = renewed.base;
569
+ filesBases.push(renewed.base);
570
+ setTimeout(renew, renewIn(renewed.expires));
571
+ })
572
+ .catch(() => setTimeout(renew, 60000));
573
+ };
574
+ setTimeout(renew, renewIn(plan.files.expires));
575
+ }
505
576
 
506
577
  // A parsed tree's scripts are held (each replaced by a numbered marker) and run later, in order,
507
578
  // as the page's parser would run them: each made again, live, in its marker's place, and each
@@ -728,41 +799,6 @@ export const SHELL_RUNTIME = String.raw `(() => {
728
799
  return !(capability && capability.userActivation) || !activation || activation.isActive;
729
800
  };
730
801
  const refuse = (message) => Promise.reject(new Error(message));
731
- if (declared("sendPrompt")) {
732
- lock(window, "sendPrompt", (text) => {
733
- if (!gestured("sendPrompt")) {
734
- return refuse("sendPrompt needs a click: call it from a button's handler");
735
- }
736
- const words = String(text);
737
- if (words.trim() === "" || words.length > plan.maxPromptChars) {
738
- return refuse("sendPrompt takes 1 to " + plan.maxPromptChars + " characters");
739
- }
740
- return request("ui/message", { role: "user", content: [{ type: "text", text: words }] }).then(
741
- (result) => !(result && result.isError),
742
- );
743
- });
744
- }
745
- if (declared("copyText")) {
746
- lock(window, "copyText", (text) => {
747
- if (!gestured("copyText")) {
748
- return refuse("copyText needs a click: call it from a button's handler");
749
- }
750
- const words = String(text);
751
- if (words === "" || words.length > plan.maxCopyChars) {
752
- return refuse("copyText takes 1 to " + plan.maxCopyChars + " characters");
753
- }
754
- return request("porthole/copy-text", { text: words }).then((result) => !(result && result.isError));
755
- });
756
- }
757
- if (declared("openLink")) {
758
- lock(window, "openLink", (url) => {
759
- if (!gestured("openLink")) {
760
- return refuse("openLink needs a click: call it from a link's or button's handler");
761
- }
762
- return request("ui/open-link", { url: String(url) }).then((result) => !(result && result.isError));
763
- });
764
- }
765
-
766
802
  // Data (P079): readData reads a resource the host names, subscribeData follows one, through
767
803
  // MCP's resources/* requests, which the host gates (the viewer's consent, a rate). A value is the
768
804
  // first content's: JSON parsed when it says it is JSON, else its text.
@@ -786,9 +822,10 @@ export const SHELL_RUNTIME = String.raw `(() => {
786
822
  const later = (error) => setTimeout(() => {
787
823
  throw error;
788
824
  });
789
- if (declared("readData")) {
790
- lock(window, "readData", (uri) => request("resources/read", { uri: String(uri) }).then(valueOf));
791
- }
825
+ // Reads a resource (readData, the runtime's data.read).
826
+ const readValue = (uri) => request("resources/read", { uri: String(uri) }).then(valueOf);
827
+ // Follows one (subscribeData, the runtime's data.subscribe), where the config declares it.
828
+ let follow = null;
792
829
  if (declared("subscribeData")) {
793
830
  // One subscription per URI, however many follow it; a read at a time, one more if it changed
794
831
  // meanwhile; a late follower gets the last value at once.
@@ -842,7 +879,7 @@ export const SHELL_RUNTIME = String.raw `(() => {
842
879
  refresh(entry);
843
880
  }
844
881
  };
845
- lock(window, "subscribeData", (uri, onData, onError) => {
882
+ follow = (uri, onData, onError) => {
846
883
  if (typeof onData !== "function") {
847
884
  throw new TypeError("subscribeData(uri, onData, onError): onData must be a function");
848
885
  }
@@ -886,9 +923,19 @@ export const SHELL_RUNTIME = String.raw `(() => {
886
923
  request("resources/unsubscribe", { uri: key }).catch(() => {});
887
924
  }
888
925
  };
889
- });
926
+ };
890
927
  }
891
928
 
929
+
930
+ // The capability runtime's hooks (P085): the host's offer from the handshake (null: no host
931
+ // answered), and a watch's updates. The runtime, where the config has one, takes them.
932
+ let runtimeOffer = (_offer) => {};
933
+ let runtimeEvent = (_params) => {};
934
+
935
+ __LEGACY__
936
+
937
+ __RUNTIME__
938
+
892
939
  window.addEventListener("error", (event) => {
893
940
  const error = event.error;
894
941
  const where = event.lineno ? " (line " + event.lineno + ")" : "";
@@ -923,6 +970,16 @@ export const SHELL_RUNTIME = String.raw `(() => {
923
970
  try {
924
971
  url = new URL(href, document.baseURI).href;
925
972
  } catch (_) {}
973
+ // A page of the set opens in the frame, whatever its target (P084); any other file of the
974
+ // set never opens: its address carries the frame's access.
975
+ if (ownPage(url)) {
976
+ location.assign(url);
977
+ return;
978
+ }
979
+ if (filesBase !== null && url.indexOf(filesBase) === 0) {
980
+ navigationBlocked(url);
981
+ return;
982
+ }
926
983
  if (/^https?:/i.test(url) && typeof window.openLink === "function") {
927
984
  window.openLink(url).catch(() => {});
928
985
  }
@@ -1069,6 +1126,9 @@ export const SHELL_RUNTIME = String.raw `(() => {
1069
1126
  resourceUpdated(params.uri);
1070
1127
  }
1071
1128
  break;
1129
+ case "porthole/event":
1130
+ runtimeEvent(params);
1131
+ break;
1072
1132
  case "ui/resource-teardown":
1073
1133
  case "ping":
1074
1134
  if (data.id !== undefined) {
@@ -1096,7 +1156,12 @@ export const SHELL_RUNTIME = String.raw `(() => {
1096
1156
  let initialized = false;
1097
1157
  let tries = 0;
1098
1158
  const initialize = () => {
1099
- if (initialized || tries >= 40) {
1159
+ if (initialized) {
1160
+ return;
1161
+ }
1162
+ if (tries >= 40) {
1163
+ // No host answered: the runtime has nothing to offer.
1164
+ runtimeOffer(null);
1100
1165
  return;
1101
1166
  }
1102
1167
  tries += 1;
@@ -1109,6 +1174,9 @@ export const SHELL_RUNTIME = String.raw `(() => {
1109
1174
  return;
1110
1175
  }
1111
1176
  initialized = true;
1177
+ const capabilities = result && result.hostCapabilities;
1178
+ const experimental = capabilities && capabilities.experimental;
1179
+ runtimeOffer(experimental && typeof experimental === "object" ? experimental["porthole/runtime"] : null);
1112
1180
  applyTheme(result && result.hostContext);
1113
1181
  notify("ui/notifications/initialized", {});
1114
1182
  schedule();
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The capability runtime in the frame (P085), spliced into the shell's runtime (`__RUNTIME__`)
3
+ * where the config has one (`config.runtime`). Content gets one global, `porthole`, whose only
4
+ * member is `use(name)`: a promise of a frozen namespace of the capability's methods, or null when
5
+ * the capability isn't there for this page (not offered, not declared, no host): the reasons are
6
+ * indistinguishable. Permission problems come at call time, as a rejected promise whose error has
7
+ * a stable `code` (P080, P087) and a sentence to show.
8
+ *
9
+ * The host's offer comes in the handshake (MCP Apps' experimental host capabilities,
10
+ * `porthole/runtime`): which capabilities, which methods. Calls go as `porthole/call` (own-prefixed,
11
+ * P002), `data.read` and `data.subscribe` as MCP's own resource requests (the cache and the
12
+ * subscriptions of P079); a watch's updates come as `porthole/event`. The host's bridge decides
13
+ * every call: nothing here is a wall, since it shares the content's realm.
14
+ */
15
+ export declare const USE_RUNTIME: string;
@@ -0,0 +1,235 @@
1
+ /**
2
+ * The capability runtime in the frame (P085), spliced into the shell's runtime (`__RUNTIME__`)
3
+ * where the config has one (`config.runtime`). Content gets one global, `porthole`, whose only
4
+ * member is `use(name)`: a promise of a frozen namespace of the capability's methods, or null when
5
+ * the capability isn't there for this page (not offered, not declared, no host): the reasons are
6
+ * indistinguishable. Permission problems come at call time, as a rejected promise whose error has
7
+ * a stable `code` (P080, P087) and a sentence to show.
8
+ *
9
+ * The host's offer comes in the handshake (MCP Apps' experimental host capabilities,
10
+ * `porthole/runtime`): which capabilities, which methods. Calls go as `porthole/call` (own-prefixed,
11
+ * P002), `data.read` and `data.subscribe` as MCP's own resource requests (the cache and the
12
+ * subscriptions of P079); a watch's updates come as `porthole/event`. The host's bridge decides
13
+ * every call: nothing here is a wall, since it shares the content's realm.
14
+ */
15
+ export const USE_RUNTIME = String.raw `
16
+ // The capability runtime (P085): porthole.use(name) -> a frozen namespace, or null.
17
+ // The host's offer: undefined until the handshake says (or gives up: null). A late answer is
18
+ // still taken, for the calls to use after it (after the review).
19
+ let offered = undefined;
20
+ const waiting = new Set();
21
+ runtimeOffer = (given) => {
22
+ const capabilities = given !== null && typeof given === "object" && given.capabilities !== null && typeof given.capabilities === "object" ? given.capabilities : null;
23
+ if (capabilities !== null || offered === undefined) {
24
+ offered = capabilities;
25
+ }
26
+ for (const wake of Array.from(waiting)) {
27
+ wake();
28
+ }
29
+ waiting.clear();
30
+ };
31
+ // A use waits for the handshake a few seconds at most, then is null (no host is answering).
32
+ const ready = () =>
33
+ offered !== undefined
34
+ ? Promise.resolve()
35
+ : new Promise((resolve) => {
36
+ waiting.add(resolve);
37
+ setTimeout(resolve, 3000);
38
+ });
39
+ // Framed by a page that isn't one of this frame's hosts: nothing will answer (where the engine
40
+ // says who framed it).
41
+ const framedByHost = () => {
42
+ const ancestors = location.ancestorOrigins;
43
+ // "null": the engine masks it (a no-referrer frame): unknown, not a stranger.
44
+ return !ancestors || ancestors.length === 0 || ancestors[0] === "null" || plan.origins.indexOf(ancestors[0]) !== -1;
45
+ };
46
+ const NativeBlob = typeof Blob === "function" ? Blob : null;
47
+ const NativeArrayBuffer = ArrayBuffer;
48
+ const coded = (code, message) => {
49
+ const error = new Error(message);
50
+ error.code = code;
51
+ return error;
52
+ };
53
+ // A call through the host; its value, or a rejection with the refusal's code.
54
+ const call = (capability, method, args) =>
55
+ request("porthole/call", { capability, method, args }).then((result) =>
56
+ result !== null && typeof result === "object" ? result.value : undefined,
57
+ );
58
+ // What needs a click, refused here before it goes (the host checks again: P021).
59
+ const clicked = (serves, what) => (gestured(serves) ? null : Promise.reject(coded("not_allowed", what + " needs a click: call it from a button's handler")));
60
+ // Bytes as base64, for what crosses the frame as JSON.
61
+ const bytesOf = (data) => {
62
+ if (NativeBlob !== null && data instanceof NativeBlob) {
63
+ return data.arrayBuffer().then((buffer) => new Uint8Array(buffer));
64
+ }
65
+ if (data instanceof NativeArrayBuffer) {
66
+ return Promise.resolve(new Uint8Array(data));
67
+ }
68
+ if (ArrayBuffer.isView(data)) {
69
+ return Promise.resolve(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
70
+ }
71
+ return null;
72
+ };
73
+ const base64Of = (bytes) => {
74
+ let text = "";
75
+ for (let at = 0; at < bytes.length; at += 32768) {
76
+ text += String.fromCharCode.apply(null, Array.from(bytes.subarray(at, at + 32768)));
77
+ }
78
+ return btoa(text);
79
+ };
80
+ // A file's content: text as it is, bytes as base64, null as null (a removal).
81
+ const fileOf = (value) => {
82
+ if (value === null || typeof value === "string") {
83
+ return Promise.resolve(value === null ? null : { text: value });
84
+ }
85
+ const bytes = bytesOf(value);
86
+ return bytes === null ? Promise.reject(coded("not_allowed", "A file is text, a Blob, an ArrayBuffer or bytes")) : bytes.then((each) => ({ base64: base64Of(each) }));
87
+ };
88
+ const record = (value) => (value !== null && typeof value === "object" ? value : {});
89
+ // Watches (db.onSnapshot): by the id this frame gives each, its listener.
90
+ const watchers = new Map();
91
+ // A watch's id is this page's own, at random: a page that follows another on the same
92
+ // transport can't be handed its watches (after the review).
93
+ const watchId = () => {
94
+ const bytes = new Uint8Array(8);
95
+ crypto.getRandomValues(bytes);
96
+ return "w" + Array.from(bytes, (each) => each.toString(16).padStart(2, "0")).join("");
97
+ };
98
+ runtimeEvent = (params) => {
99
+ const watcher = typeof params.watch === "string" ? watchers.get(params.watch) : undefined;
100
+ if (watcher === undefined) {
101
+ return;
102
+ }
103
+ try {
104
+ watcher.onData(params.data);
105
+ } catch (error) {
106
+ later(error);
107
+ }
108
+ };
109
+ const watch = (capability, method, args, onData, onError) => {
110
+ if (typeof onData !== "function") {
111
+ throw new TypeError(capability + "." + method + ": onData must be a function");
112
+ }
113
+ const id = watchId();
114
+ watchers.set(id, { onData });
115
+ request("porthole/call", { capability, method, args, watch: id }).catch((error) => {
116
+ watchers.delete(id);
117
+ if (typeof onError === "function") {
118
+ try {
119
+ onError(error);
120
+ } catch (thrown) {
121
+ later(thrown);
122
+ }
123
+ }
124
+ });
125
+ return () => {
126
+ if (watchers.delete(id)) {
127
+ notify("porthole/unwatch", { watch: id });
128
+ }
129
+ };
130
+ };
131
+ const METHODS = {
132
+ user: { get: () => call("user", "get", {}) },
133
+ comments: {
134
+ open: (anchor) => clicked("comments", "comments.open") || call("comments", "open", { anchor: typeof anchor === "string" ? { name: anchor } : record(anchor) }),
135
+ },
136
+ clipboard: { copy: (text) => clicked("copyText", "clipboard.copy") || call("clipboard", "copy", { text: String(text) }) },
137
+ links: { open: (url) => clicked("openLink", "links.open") || call("links", "open", { url: String(url) }) },
138
+ downloads: {
139
+ save: (file) => {
140
+ const given = record(file);
141
+ const waiting = clicked("downloadFile", "downloads.save");
142
+ if (waiting !== null) {
143
+ return waiting;
144
+ }
145
+ const content = given.data !== undefined ? given.data : given.text !== undefined ? String(given.text) : null;
146
+ return fileOf(content).then((body) => call("downloads", "save", { file: Object.assign({ name: given.name, type: given.type }, record(body)) }));
147
+ },
148
+ },
149
+ chat: { send: (text) => clicked("sendPrompt", "chat.send") || call("chat", "send", { text: String(text) }) },
150
+ data: {
151
+ read: (uri) => readValue(uri),
152
+ subscribe: (uri, onData, onError) => (follow === null ? null : follow(uri, onData, onError)),
153
+ call: (name, args) => call("data", "call", { name: String(name), arguments: args === undefined ? {} : args }),
154
+ },
155
+ context: { set: (update) => call("context", "set", record(update)) },
156
+ artifact: {
157
+ get: () => call("artifact", "get", {}),
158
+ publish: (change) => {
159
+ const given = record(change);
160
+ const files = record(given.files);
161
+ const names = Object.keys(files);
162
+ return Promise.all(names.map((name) => fileOf(files[name]))).then((bodies) => {
163
+ const out = {};
164
+ names.forEach((name, index) => {
165
+ out[name] = bodies[index];
166
+ });
167
+ return call("artifact", "publish", { base: given.base, files: out, entry: given.entry, label: given.label, note: given.note });
168
+ });
169
+ },
170
+ },
171
+ assets: {
172
+ list: () => call("assets", "list", {}),
173
+ upload: (file, options) => {
174
+ const name = record(options).name !== undefined ? record(options).name : file && typeof file.name === "string" ? file.name : undefined;
175
+ const bytes = bytesOf(file);
176
+ return bytes === null ? Promise.reject(coded("not_allowed", "assets.upload takes a File, a Blob or bytes")) : bytes.then((each) => call("assets", "upload", { name, base64: base64Of(each) }));
177
+ },
178
+ delete: (id) => call("assets", "delete", { id: String(id) }),
179
+ // The address that loads an asset in this page now (P091): in a frame, under its own sealed
180
+ // files' address, which every engine sends; elsewhere /_blob/<id>. Never stored: it carries
181
+ // this page's access.
182
+ url: (id) => {
183
+ const asset = String(id);
184
+ if (!/^[0-9a-f]{32}$/.test(asset)) {
185
+ throw new TypeError("assets.url(id): an asset's id is 32 lowercase hex characters");
186
+ }
187
+ return filesBase !== null && filesBase.indexOf("/__porthole/f/") !== -1 ? filesBase + "__porthole/blob/" + asset : "/_blob/" + asset;
188
+ },
189
+ },
190
+ db: {
191
+ get: (path) => call("db", "get", { path }),
192
+ set: (path, data, options) => call("db", "set", { path, data, ifVersion: record(options).ifVersion }),
193
+ update: (path, data, options) => call("db", "update", { path, data, ifVersion: record(options).ifVersion }),
194
+ delete: (path, options) => call("db", "delete", { path, ifVersion: record(options).ifVersion }),
195
+ query: (collection, query) => call("db", "query", Object.assign({ collection }, record(query))),
196
+ batch: (writes) => call("db", "batch", { writes }),
197
+ onSnapshot: (path, onData, onError) => watch("db", "watch", { path }, onData, onError),
198
+ },
199
+ };
200
+ // A runtime method's name in the namespace, where it differs from the contract's.
201
+ const RENAMED = { db: { watch: "onSnapshot" } };
202
+ const namespaces = new Map();
203
+ const use = (name) => {
204
+ if (window.parent === window || !framedByHost() || typeof name !== "string" || !Object.prototype.hasOwnProperty.call(METHODS, name)) {
205
+ return Promise.resolve(null);
206
+ }
207
+ return ready().then(() => {
208
+ const methods = offered !== undefined && offered !== null && Array.isArray(offered[name]) ? offered[name] : null;
209
+ if (methods === null) {
210
+ return null;
211
+ }
212
+ if (!namespaces.has(name)) {
213
+ const space = {};
214
+ const renamed = RENAMED[name] || {};
215
+ for (const each of methods) {
216
+ const key = Object.prototype.hasOwnProperty.call(renamed, each) ? renamed[each] : each;
217
+ if (typeof each === "string" && Object.prototype.hasOwnProperty.call(METHODS[name], key)) {
218
+ const call = METHODS[name][key];
219
+ // A method whose own gates want a gesture (after the review): refused here without one.
220
+ const gated = Array.isArray(plan.methodActivation) && plan.methodActivation.indexOf(name + "." + each) !== -1;
221
+ space[key] = gated
222
+ ? function () {
223
+ const activation = navigator.userActivation;
224
+ return activation && !activation.isActive ? Promise.reject(coded("not_allowed", name + "." + key + " needs a click: call it from a button's handler")) : call.apply(null, arguments);
225
+ }
226
+ : call;
227
+ }
228
+ }
229
+ namespaces.set(name, Object.freeze(space));
230
+ }
231
+ return namespaces.get(name);
232
+ }, () => null);
233
+ };
234
+ lock(window, "porthole", Object.freeze({ use }));
235
+ `;