@botiverse/porthole 0.6.0 → 0.8.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 (208) hide show
  1. package/README.md +25 -2
  2. package/THIRD_PARTY_NOTICES.md +421 -0
  3. package/dist/bridge/bounded-text.d.ts +34 -0
  4. package/dist/bridge/bounded-text.js +188 -0
  5. package/dist/bridge/bridge.d.ts +38 -5
  6. package/dist/bridge/bridge.js +469 -39
  7. package/dist/bridge/json-data.d.ts +28 -0
  8. package/dist/bridge/json-data.js +86 -0
  9. package/dist/bridge/navigation.d.ts +5 -0
  10. package/dist/bridge/navigation.js +7 -0
  11. package/dist/bridge/refusal.d.ts +5 -1
  12. package/dist/bridge/refusal.js +17 -0
  13. package/dist/bridge/types.d.ts +73 -5
  14. package/dist/check/check.d.ts +7 -0
  15. package/dist/check/check.js +1 -0
  16. package/dist/check/instrument.d.ts +3 -0
  17. package/dist/check/lint.js +4 -2
  18. package/dist/check/page-source.js +1 -1
  19. package/dist/check/page.js +16 -0
  20. package/dist/check/tools.js +2 -3
  21. package/dist/compile/compile.d.ts +6 -0
  22. package/dist/compile/compile.js +3 -1
  23. package/dist/compile/policy.d.ts +55 -0
  24. package/dist/compile/policy.js +157 -0
  25. package/dist/config/capabilities.d.ts +85 -7
  26. package/dist/config/capabilities.js +32 -2
  27. package/dist/config/schema.d.ts +35 -0
  28. package/dist/config/validate.d.ts +9 -3
  29. package/dist/config/validate.js +92 -8
  30. package/dist/config/warnings.d.ts +20 -0
  31. package/dist/config/warnings.js +25 -0
  32. package/dist/conformance/behavior.js +46 -1
  33. package/dist/conformance/cookies.d.ts +15 -0
  34. package/dist/conformance/cookies.js +80 -0
  35. package/dist/conformance/harness/page.d.ts +1 -0
  36. package/dist/conformance/harness/page.js +9 -2
  37. package/dist/conformance/harness-source.js +1 -1
  38. package/dist/conformance/host-kit.js +5 -1
  39. package/dist/conformance/index.d.ts +11 -0
  40. package/dist/conformance/index.js +2 -0
  41. package/dist/conformance/limits.js +38 -1
  42. package/dist/conformance/runtime.d.ts +58 -0
  43. package/dist/conformance/runtime.js +324 -0
  44. package/dist/conformance/served.d.ts +2 -0
  45. package/dist/conformance/served.js +737 -4
  46. package/dist/files/paths.js +4 -0
  47. package/dist/guide/gates.d.ts +9 -0
  48. package/dist/guide/gates.js +31 -0
  49. package/dist/guide/guide.d.ts +2 -0
  50. package/dist/guide/guide.js +35 -33
  51. package/dist/guide/limits.js +4 -4
  52. package/dist/guide/runtime.d.ts +13 -0
  53. package/dist/guide/runtime.js +210 -0
  54. package/dist/host/create-host.js +73 -37
  55. package/dist/host/locate.js +8 -0
  56. package/dist/host/locator.js +7 -0
  57. package/dist/host/pages-of-set.d.ts +43 -0
  58. package/dist/host/pages-of-set.js +196 -0
  59. package/dist/host/types.d.ts +26 -1
  60. package/dist/index.d.ts +11 -4
  61. package/dist/index.js +11 -2
  62. package/dist/isolation/types.d.ts +8 -0
  63. package/dist/mcp/adapter.js +11 -15
  64. package/dist/node/index.d.ts +36 -4
  65. package/dist/node/index.js +402 -101
  66. package/dist/presets/presets.d.ts +22 -8
  67. package/dist/presets/presets.js +40 -8
  68. package/dist/protocol/live-data.d.ts +6 -2
  69. package/dist/protocol/live-data.js +20 -1
  70. package/dist/protocol/mcp-apps.d.ts +13 -2
  71. package/dist/protocol/mcp-apps.js +10 -2
  72. package/dist/protocol/message-text.d.ts +8 -0
  73. package/dist/protocol/message-text.js +29 -0
  74. package/dist/protocol/runtime-calls.d.ts +28 -0
  75. package/dist/protocol/runtime-calls.js +116 -0
  76. package/dist/protocol/shell-adapter.js +64 -25
  77. package/dist/react/context-notice.d.ts +32 -0
  78. package/dist/react/context-notice.js +28 -0
  79. package/dist/react/dialog.js +91 -16
  80. package/dist/react/frame.d.ts +25 -1
  81. package/dist/react/frame.js +85 -2
  82. package/dist/react/index.d.ts +2 -1
  83. package/dist/react/index.js +2 -1
  84. package/dist/runtime/contract.d.ts +201 -0
  85. package/dist/runtime/contract.js +245 -0
  86. package/dist/runtime/db.d.ts +188 -0
  87. package/dist/runtime/db.js +502 -0
  88. package/dist/runtime/declaration.d.ts +100 -0
  89. package/dist/runtime/declaration.js +363 -0
  90. package/dist/runtime/levels.d.ts +33 -0
  91. package/dist/runtime/levels.js +41 -0
  92. package/dist/runtime/requests.d.ts +125 -0
  93. package/dist/runtime/requests.js +215 -0
  94. package/dist/runtime/segments.d.ts +8 -0
  95. package/dist/runtime/segments.js +14 -0
  96. package/dist/runtime/types.generated.d.ts +1 -0
  97. package/dist/runtime/types.generated.js +19 -0
  98. package/dist/server/files.d.ts +19 -1
  99. package/dist/server/files.js +115 -6
  100. package/dist/server/host.d.ts +24 -2
  101. package/dist/server/host.js +137 -2
  102. package/dist/server/index.d.ts +3 -2
  103. package/dist/server/index.js +2 -1
  104. package/dist/server/peer.d.ts +4 -0
  105. package/dist/server/peer.js +19 -0
  106. package/dist/server/proxy.d.ts +6 -0
  107. package/dist/server/proxy.js +12 -3
  108. package/dist/server/pseudonym.d.ts +9 -0
  109. package/dist/server/pseudonym.js +20 -0
  110. package/dist/server/server.d.ts +0 -5
  111. package/dist/server/server.js +318 -52
  112. package/dist/server/types.d.ts +74 -2
  113. package/dist/shell/document.d.ts +16 -0
  114. package/dist/shell/document.js +19 -2
  115. package/dist/shell/legacy.d.ts +21 -0
  116. package/dist/shell/legacy.js +63 -0
  117. package/dist/shell/plan.d.ts +17 -1
  118. package/dist/shell/plan.js +13 -2
  119. package/dist/shell/runtime.js +390 -56
  120. package/dist/shell/use.d.ts +15 -0
  121. package/dist/shell/use.js +235 -0
  122. package/docs/ADOPTING.md +205 -15
  123. package/docs/ARCHITECTURE.md +34 -5
  124. package/docs/DECISIONS.md +1867 -11
  125. package/docs/DESIGN.md +137 -17
  126. package/docs/THREAT_MODEL.md +616 -0
  127. package/package.json +16 -3
  128. package/src/bridge/bounded-text.ts +240 -0
  129. package/src/bridge/bridge.ts +601 -51
  130. package/src/bridge/json-data.ts +95 -0
  131. package/src/bridge/navigation.ts +10 -0
  132. package/src/bridge/refusal.ts +17 -0
  133. package/src/bridge/types.ts +76 -5
  134. package/src/check/check.ts +8 -0
  135. package/src/check/instrument.ts +3 -0
  136. package/src/check/lint.ts +4 -2
  137. package/src/check/page.ts +16 -0
  138. package/src/check/tools.ts +2 -3
  139. package/src/compile/compile.ts +9 -1
  140. package/src/compile/policy.ts +177 -0
  141. package/src/config/capabilities.ts +71 -5
  142. package/src/config/schema.ts +35 -0
  143. package/src/config/validate.ts +141 -8
  144. package/src/config/warnings.ts +42 -0
  145. package/src/conformance/behavior.ts +54 -1
  146. package/src/conformance/cookies.ts +93 -0
  147. package/src/conformance/harness/page.ts +11 -2
  148. package/src/conformance/host-kit.ts +10 -1
  149. package/src/conformance/index.ts +17 -0
  150. package/src/conformance/limits.ts +39 -1
  151. package/src/conformance/runtime.ts +594 -0
  152. package/src/conformance/served.ts +888 -4
  153. package/src/files/paths.ts +4 -0
  154. package/src/guide/gates.ts +37 -0
  155. package/src/guide/guide.ts +61 -55
  156. package/src/guide/limits.ts +4 -4
  157. package/src/guide/runtime.ts +253 -0
  158. package/src/host/create-host.ts +88 -36
  159. package/src/host/locate.ts +10 -0
  160. package/src/host/locator.ts +11 -0
  161. package/src/host/pages-of-set.ts +226 -0
  162. package/src/host/types.ts +33 -1
  163. package/src/index.ts +94 -0
  164. package/src/isolation/types.ts +8 -0
  165. package/src/mcp/adapter.ts +16 -20
  166. package/src/node/index.ts +507 -116
  167. package/src/presets/presets.ts +67 -17
  168. package/src/protocol/live-data.ts +31 -3
  169. package/src/protocol/mcp-apps.ts +11 -2
  170. package/src/protocol/message-text.ts +36 -0
  171. package/src/protocol/runtime-calls.ts +141 -0
  172. package/src/protocol/shell-adapter.ts +79 -26
  173. package/src/react/context-notice.tsx +95 -0
  174. package/src/react/dialog.tsx +108 -15
  175. package/src/react/frame.tsx +120 -0
  176. package/src/react/index.ts +8 -1
  177. package/src/runtime/contract.ts +339 -0
  178. package/src/runtime/db.ts +650 -0
  179. package/src/runtime/declaration.ts +516 -0
  180. package/src/runtime/levels.ts +69 -0
  181. package/src/runtime/requests.ts +355 -0
  182. package/src/runtime/segments.ts +17 -0
  183. package/src/runtime/types.generated.ts +19 -0
  184. package/src/server/files.ts +138 -7
  185. package/src/server/host.ts +170 -3
  186. package/src/server/index.ts +4 -0
  187. package/src/server/peer.ts +21 -0
  188. package/src/server/proxy.ts +13 -3
  189. package/src/server/pseudonym.ts +21 -0
  190. package/src/server/server.ts +370 -57
  191. package/src/server/types.ts +73 -2
  192. package/src/shell/document.ts +29 -4
  193. package/src/shell/legacy.ts +64 -0
  194. package/src/shell/plan.ts +37 -3
  195. package/src/shell/runtime.ts +390 -56
  196. package/src/shell/use.ts +235 -0
  197. package/types/runtime/v1/artifact.d.ts +50 -0
  198. package/types/runtime/v1/assets.d.ts +43 -0
  199. package/types/runtime/v1/chat.d.ts +13 -0
  200. package/types/runtime/v1/clipboard.d.ts +14 -0
  201. package/types/runtime/v1/comments.d.ts +24 -0
  202. package/types/runtime/v1/context.d.ts +27 -0
  203. package/types/runtime/v1/data.d.ts +29 -0
  204. package/types/runtime/v1/db.d.ts +110 -0
  205. package/types/runtime/v1/downloads.d.ts +22 -0
  206. package/types/runtime/v1/links.d.ts +13 -0
  207. package/types/runtime/v1/porthole.d.ts +44 -0
  208. package/types/runtime/v1/user.d.ts +19 -0
@@ -74,6 +74,26 @@ const mergeEgress = (base, extra) => {
74
74
  }
75
75
  return merged;
76
76
  };
77
+ /**
78
+ * A frozen copy of a config's data, all the way down (P103): what a host passed in stays its own
79
+ * and mutable; the copy can't be written into (a capability's `connect`, an egress origin).
80
+ */
81
+ function frozenCopy(value) {
82
+ if (Array.isArray(value)) {
83
+ return Object.freeze(value.map((each) => frozenCopy(each)));
84
+ }
85
+ if (value !== null && typeof value === "object") {
86
+ const prototype = Object.getPrototypeOf(value);
87
+ if (prototype === Object.prototype || prototype === null) {
88
+ const copy = {};
89
+ for (const [key, each] of Object.entries(value)) {
90
+ copy[key] = frozenCopy(each);
91
+ }
92
+ return Object.freeze(copy);
93
+ }
94
+ }
95
+ return value;
96
+ }
77
97
  /** The default variables, with the host's changes and additions, less those it dropped (null). */
78
98
  function themeVariables(changes) {
79
99
  const variables = { ...DEFAULT_THEME_VARIABLES };
@@ -120,6 +140,7 @@ function build(mode, defaults, options) {
120
140
  embedder: options.embedder ?? {},
121
141
  ...(options.storage === undefined ? {} : { storage: options.storage }),
122
142
  ...(options.errors === undefined ? {} : { errors: options.errors }),
143
+ ...(options.runtime === undefined ? {} : { runtime: options.runtime }),
123
144
  });
124
145
  }
125
146
  export const presets = {
@@ -130,24 +151,35 @@ export const presets = {
130
151
  inlineWidget: (options = {}) => build("inline", {}, options),
131
152
  /**
132
153
  * A widget that shows its host's data, live, and has no network of its own (P079): an inline
133
- * widget whose egress stays closed (no option opens it). It reads the host's data (`readData`,
134
- * MCP `resources/read`) and subscribes to it (`subscribeData`, `resources/subscribe`), each
135
- * behind the viewer's consent (the host's `consent`, asked once per display) and a rate. In
136
- * domain isolation its scripts load from Porthole's own libraries on its origin
137
- * (`egress.libraries`: Chart.js, D3), and nowhere else. A host adds what any widget may have (a
138
- * link, a copy button), or changes the data capabilities' gates.
154
+ * widget whose egress stays closed (no option opens it: neither `egress` nor a capability's own
155
+ * `connect` or `resource`, P103). It reads the host's data (`readData`, MCP `resources/read`)
156
+ * and subscribes to it (`subscribeData`, `resources/subscribe`), each behind the viewer's
157
+ * consent (the host's `consent`, asked once per display) and a rate. In domain isolation its
158
+ * scripts load from Porthole's own libraries on its origin (`egress.libraries`: Chart.js, D3),
159
+ * and nowhere else. A host adds what any widget may have (a link, a copy button), or changes the
160
+ * data capabilities' gates.
139
161
  */
140
162
  liveWidget: (options = {}) => {
141
163
  if (options.egress !== undefined) {
142
164
  throw new ConfigError("options.egress", "a live widget has no network of its own: its egress stays closed (P079)");
143
165
  }
144
- return build("inline", {
166
+ // A capability's own origins join the CSP as egress does (P103): none for a live widget.
167
+ for (const [name, value] of Object.entries(options.capabilities ?? {})) {
168
+ for (const field of ["connect", "resource"]) {
169
+ if (typeof value === "object" && value !== null && value[field] !== undefined) {
170
+ throw new ConfigError(`options.capabilities.${name}.${field}`, "a live widget has no network of its own: no capability opens origins for it (P079, P103)");
171
+ }
172
+ }
173
+ }
174
+ // Frozen, all the way down (P103): nothing writes an origin into the preset's config after it
175
+ // is made. A config a host builds from it (a spread) is the host's own, not this preset.
176
+ return frozenCopy(build("inline", {
145
177
  capabilities: {
146
178
  readData: { gates: ["consent", { rateLimit: { perMinute: 120 } }] },
147
179
  subscribeData: { gates: ["consent", { rateLimit: { perMinute: 60 } }] },
148
180
  },
149
181
  egress: options.isolation === "domain" ? { libraries: true } : {},
150
- }, options);
182
+ }, options));
151
183
  },
152
184
  /**
153
185
  * A whole HTML page: written into an opaque frame by the shell where the host has the page, or
@@ -4,10 +4,14 @@ import type { CallOutcome, HostFunctionBridge } from "../bridge/types.ts";
4
4
  * `resources/subscribe`, `resources/unsubscribe`, `notifications/resources/updated`): the frame's
5
5
  * subscriptions by URI, each ended by its controller, and a fresh result the host gave for one
6
6
  * (pushed through `changed(result)`, or read after a stale answer), kept for the frame's next read
7
- * of it. Every call goes through the bridge, which gates it; the adapter only says what to send.
7
+ * of it. Every call goes through the bridge, which gates it, a read answered by a kept result too
8
+ * (P094); the adapter only says what to send.
8
9
  */
9
10
  export interface LiveData {
10
- /** A read: a fresh result kept for it, else the host's (its cache first, when subscribed). */
11
+ /**
12
+ * A read, past the read's gates whatever answers it: a fresh result kept for it, else the
13
+ * host's (its cache first, when subscribed).
14
+ */
11
15
  read(uri: unknown): Promise<CallOutcome<unknown>>;
12
16
  /** Starts the host's subscription; a second for a URI is a no-op. */
13
17
  subscribe(uri: unknown): Promise<CallOutcome<undefined>>;
@@ -1,4 +1,9 @@
1
1
  import { STALE_META } from "./mcp-apps.js";
2
+ /**
3
+ * The most resources one frame follows at once (P095), as the runtime's watches (50): past it a
4
+ * subscription is refused as too large, and the host isn't asked.
5
+ */
6
+ const MAX_SUBSCRIPTIONS = 50;
2
7
  /** Where MCP results carry their metadata. */
3
8
  const META = "_meta";
4
9
  /** A `resources/read` result marked as the host's cached copy (`STALE_META`). */
@@ -33,9 +38,16 @@ export function liveData(bridge, updated, options = {}) {
33
38
  return {
34
39
  async read(uri) {
35
40
  if (typeof uri === "string" && fresh.has(uri)) {
41
+ // A kept result is the host's answer to a read: it goes through the read's gates as any
42
+ // read does (level, names, rate, gesture, consent, confirm), with no new upstream call
43
+ // (P094). Used once; kept again if the gates refused it and nothing newer came.
36
44
  const value = fresh.get(uri);
37
45
  fresh.delete(uri);
38
- return { ok: true, value };
46
+ const outcome = await bridge.call("readData", { uri }, { ...activation(), held: { uri, value } });
47
+ if (!outcome.ok && !closed && subscriptions.has(uri) && !fresh.has(uri)) {
48
+ fresh.set(uri, value);
49
+ }
50
+ return outcome;
39
51
  }
40
52
  const subscribed = typeof uri === "string" && subscriptions.has(uri);
41
53
  const outcome = await bridge.call("readData", { uri }, { ...activation(), stale: subscribed });
@@ -56,6 +68,13 @@ export function liveData(bridge, updated, options = {}) {
56
68
  if (typeof uri === "string" && subscriptions.has(uri)) {
57
69
  return { ok: true, value: undefined };
58
70
  }
71
+ if (subscriptions.size >= MAX_SUBSCRIPTIONS) {
72
+ return {
73
+ ok: false,
74
+ refusal: "too-large",
75
+ reason: { code: "too_large", message: "Too many things followed at once." },
76
+ };
77
+ }
59
78
  const controller = new AbortController();
60
79
  if (typeof uri === "string") {
61
80
  subscriptions.set(uri, controller);
@@ -31,6 +31,15 @@ export declare const MCP_APPS_METHODS: {
31
31
  readonly sandboxResourceReady: "ui/notifications/sandbox-resource-ready";
32
32
  };
33
33
  export type McpAppsMethod = (typeof MCP_APPS_METHODS)[keyof typeof MCP_APPS_METHODS];
34
+ /**
35
+ * What a host that declares `setModelContext` says it takes (`hostCapabilities.updateModelContext`),
36
+ * in both adapters: text blocks and structured content, exactly what the bridge accepts and the
37
+ * person is shown (P100). Images and other blocks aren't offered, and are refused.
38
+ */
39
+ export declare const MODEL_CONTEXT_OFFERED: {
40
+ readonly text: {};
41
+ readonly structuredContent: {};
42
+ };
34
43
  /**
35
44
  * What the shell's `tool-input(-partial)` carries: the content to draw. Porthole's own argument
36
45
  * names, since the shell is the only view that reads them.
@@ -69,8 +78,10 @@ export declare const STALE_META = "porthole/stale";
69
78
  export declare const NAVIGATION_BLOCKED_METHOD = "porthole/navigation-blocked";
70
79
  /**
71
80
  * Porthole's own notification from the shell (P084): a page that came with files is opening
72
- * another page of its set, `{ url }`, in the frame. The host takes the frame's next load for that
73
- * page rather than for content that left (P031). The content's word: it only spares a restart.
81
+ * another page of its set, `{ url }`, in the frame; and, as it arrives, the page a navigation
82
+ * opened says so, `{ url, arrived: true }` (P098). The host takes the frame's next load (or the
83
+ * load it came after, within `LATE_NOTICE_MS`) for that page rather than for content that left
84
+ * (P031). The content's word: it only spares a restart.
74
85
  */
75
86
  export declare const NAVIGATING_METHOD = "porthole/navigating";
76
87
  /** The logger name the shell's error reports (`notifications/message`, level `error`) carry. */
@@ -37,6 +37,12 @@ export const MCP_APPS_METHODS = {
37
37
  sandboxProxyReady: "ui/notifications/sandbox-proxy-ready",
38
38
  sandboxResourceReady: "ui/notifications/sandbox-resource-ready",
39
39
  };
40
+ /**
41
+ * What a host that declares `setModelContext` says it takes (`hostCapabilities.updateModelContext`),
42
+ * in both adapters: text blocks and structured content, exactly what the bridge accepts and the
43
+ * person is shown (P100). Images and other blocks aren't offered, and are refused.
44
+ */
45
+ export const MODEL_CONTEXT_OFFERED = { text: {}, structuredContent: {} };
40
46
  /**
41
47
  * The style variables MCP Apps defines (`McpUiStyleVariableKey`, 2026-01-26). The official App SDK
42
48
  * refuses a host context whose `styles.variables` holds any other name ("Unrecognized key"), so a
@@ -119,8 +125,10 @@ export const STALE_META = "porthole/stale";
119
125
  export const NAVIGATION_BLOCKED_METHOD = "porthole/navigation-blocked";
120
126
  /**
121
127
  * Porthole's own notification from the shell (P084): a page that came with files is opening
122
- * another page of its set, `{ url }`, in the frame. The host takes the frame's next load for that
123
- * page rather than for content that left (P031). The content's word: it only spares a restart.
128
+ * another page of its set, `{ url }`, in the frame; and, as it arrives, the page a navigation
129
+ * opened says so, `{ url, arrived: true }` (P098). The host takes the frame's next load (or the
130
+ * load it came after, within `LATE_NOTICE_MS`) for that page rather than for content that left
131
+ * (P031). The content's word: it only spares a restart.
124
132
  */
125
133
  export const NAVIGATING_METHOD = "porthole/navigating";
126
134
  /** The logger name the shell's error reports (`notifications/message`, level `error`) carry. */
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The text of a `ui/message`'s content blocks, the adapters' one reading of it: its text blocks'
3
+ * text, in order, joined by `separator`; null where there is none, or more blocks than a message
4
+ * holds. Read before any gate, so only as far as `max` characters (S05's class, P095: structured
5
+ * clone delivers a sparse array of any length, or one block shared a million times, for the cost
6
+ * of one): past it, `max + 1` characters, which the bridge refuses as too long.
7
+ */
8
+ export declare function messageText(blocks: readonly unknown[], separator: string, max: number): string | null;
@@ -0,0 +1,29 @@
1
+ /** The most content blocks a message's text is read from: more is no message a person sends. */
2
+ const MAX_BLOCKS = 1_000;
3
+ /**
4
+ * The text of a `ui/message`'s content blocks, the adapters' one reading of it: its text blocks'
5
+ * text, in order, joined by `separator`; null where there is none, or more blocks than a message
6
+ * holds. Read before any gate, so only as far as `max` characters (S05's class, P095: structured
7
+ * clone delivers a sparse array of any length, or one block shared a million times, for the cost
8
+ * of one): past it, `max + 1` characters, which the bridge refuses as too long.
9
+ */
10
+ export function messageText(blocks, separator, max) {
11
+ if (blocks.length > MAX_BLOCKS) {
12
+ return null;
13
+ }
14
+ let text = null;
15
+ for (let index = 0; index < blocks.length; index += 1) {
16
+ const block = blocks[index];
17
+ if (block !== null &&
18
+ typeof block === "object" &&
19
+ !Array.isArray(block) &&
20
+ block.type === "text" &&
21
+ typeof block.text === "string") {
22
+ text = text === null ? block.text : `${text}${separator}${block.text}`;
23
+ if (text.length > max) {
24
+ return text.slice(0, max + 1);
25
+ }
26
+ }
27
+ }
28
+ return text;
29
+ }
@@ -0,0 +1,28 @@
1
+ import type { CallOutcome, HostFunctionBridge } from "../bridge/types.ts";
2
+ import { type RefusalReason } from "../bridge/refusal.ts";
3
+ import type { CapabilityName } from "../config/capabilities.ts";
4
+ /** A runtime call as the host function that serves it gets it, or null for none. */
5
+ export declare function runtimeCall(capability: unknown, method: unknown, args: unknown): {
6
+ readonly serves: CapabilityName;
7
+ readonly args: unknown;
8
+ readonly watch: boolean;
9
+ } | null;
10
+ type Answer = {
11
+ readonly result: unknown;
12
+ } | {
13
+ readonly error: {
14
+ code: number;
15
+ message: string;
16
+ data?: RefusalReason;
17
+ };
18
+ };
19
+ /** A runtime call's outcome, as the frame hears it: its value, or why it was refused (P080). */
20
+ export declare function runtimeAnswer(serves: CapabilityName, outcome: CallOutcome<unknown>): Answer;
21
+ /** One frame's runtime calls: its watches, and their end. */
22
+ export declare function runtimeCalls(bridge: HostFunctionBridge, notify: (method: string, params: Record<string, unknown>) => void): {
23
+ call(params: Record<string, unknown>): Promise<Answer>;
24
+ /** The frame stopped following (never gated). */
25
+ unwatch(params: Record<string, unknown>): void;
26
+ close(): void;
27
+ };
28
+ export {};
@@ -0,0 +1,116 @@
1
+ import { reasonFor } from "../bridge/refusal.js";
2
+ import { RUNTIME_CAPABILITIES, RUNTIME_EVENT_METHOD, isRuntimeCapabilityName, } from "../runtime/contract.js";
3
+ import { DB_LIMITS } from "../runtime/db.js";
4
+ import { downloadContents } from "../runtime/requests.js";
5
+ /**
6
+ * The host side of the capability runtime's calls (P085): `porthole/call` with `{ capability,
7
+ * method, args }` (and `watch`, a frame-chosen id, for a subscription), each turned into the host
8
+ * function that serves it and passed through the bridge, which alone decides; `porthole/unwatch`
9
+ * ends a watch. A watch's updates go to the frame as `porthole/event` with `{ watch, data }`.
10
+ */
11
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
12
+ /** A runtime call as the host function that serves it gets it, or null for none. */
13
+ export function runtimeCall(capability, method, args) {
14
+ if (!isRuntimeCapabilityName(capability) || typeof method !== "string") {
15
+ return null;
16
+ }
17
+ const methods = RUNTIME_CAPABILITIES[capability].methods;
18
+ const spec = Object.hasOwn(methods, method) ? methods[method] : undefined;
19
+ // `data.subscribe` is MCP's own subscription (resources/subscribe, P079), not a runtime call.
20
+ if (spec === undefined || spec.serves === "subscribeData") {
21
+ return null;
22
+ }
23
+ const given = isRecord(args) ? args : {};
24
+ const watch = spec.watch === true;
25
+ switch (spec.serves) {
26
+ case "downloadFile":
27
+ return {
28
+ serves: spec.serves,
29
+ args: { contents: downloadContents(given.file) ?? undefined },
30
+ watch,
31
+ };
32
+ case "callTool":
33
+ return { serves: spec.serves, args: { name: given.name, arguments: given.arguments }, watch };
34
+ case "readData":
35
+ return { serves: spec.serves, args: { uri: given.uri }, watch };
36
+ case "artifact":
37
+ case "assets":
38
+ case "db":
39
+ // One host function serves several methods: the method is its `op`.
40
+ return { serves: spec.serves, args: { ...given, op: method }, watch };
41
+ default:
42
+ return { serves: spec.serves, args: given, watch };
43
+ }
44
+ }
45
+ /** A runtime call's outcome, as the frame hears it: its value, or why it was refused (P080). */
46
+ export function runtimeAnswer(serves, outcome) {
47
+ if (!outcome.ok) {
48
+ return {
49
+ error: {
50
+ code: -32000,
51
+ message: `Refused (${outcome.refusal})`,
52
+ data: reasonFor(serves, outcome),
53
+ },
54
+ };
55
+ }
56
+ return { result: { value: outcome.value ?? null } };
57
+ }
58
+ const refused = (reason) => ({
59
+ error: { code: -32000, message: `Refused (${reason.code})`, data: reason },
60
+ });
61
+ /** One frame's runtime calls: its watches, and their end. */
62
+ export function runtimeCalls(bridge, notify) {
63
+ const watches = new Map();
64
+ return {
65
+ async call(params) {
66
+ const mapped = runtimeCall(params.capability, params.method, params.args);
67
+ if (mapped === null) {
68
+ return refused({ code: "not_allowed", message: "This isn't available here." });
69
+ }
70
+ if (!mapped.watch) {
71
+ return runtimeAnswer(mapped.serves, await bridge.call(mapped.serves, mapped.args));
72
+ }
73
+ const id = params.watch;
74
+ if (typeof id !== "string" || !/^[\w-]{1,64}$/u.test(id) || watches.has(id)) {
75
+ return refused({ code: "not_allowed", message: "The app can't take this request." });
76
+ }
77
+ if (watches.size >= DB_LIMITS.maxWatches) {
78
+ return refused({ code: "too_large", message: "Too many things followed at once." });
79
+ }
80
+ const controller = new AbortController();
81
+ watches.set(id, controller);
82
+ const outcome = await bridge.call(mapped.serves, mapped.args, {
83
+ subscription: {
84
+ // Each update is the watch's answer, gated as its read when it started (P091, P094):
85
+ // nothing that check read changes while it lives (the frame's viewer and declaration,
86
+ // the display's kept consent), and a new page or frame ends it. So no gate per update.
87
+ changed: (data) => {
88
+ if (!controller.signal.aborted) {
89
+ notify(RUNTIME_EVENT_METHOD, { watch: id, data: data ?? null });
90
+ }
91
+ },
92
+ signal: controller.signal,
93
+ },
94
+ });
95
+ if (!outcome.ok) {
96
+ controller.abort();
97
+ watches.delete(id);
98
+ }
99
+ return outcome.ok ? { result: { value: null } } : runtimeAnswer(mapped.serves, outcome);
100
+ },
101
+ /** The frame stopped following (never gated). */
102
+ unwatch(params) {
103
+ const id = params.watch;
104
+ if (typeof id === "string") {
105
+ watches.get(id)?.abort();
106
+ watches.delete(id);
107
+ }
108
+ },
109
+ close() {
110
+ for (const controller of watches.values()) {
111
+ controller.abort();
112
+ }
113
+ watches.clear();
114
+ },
115
+ };
116
+ }
@@ -1,7 +1,10 @@
1
1
  import { JSON_RPC_ERRORS, parseJsonRpc, } from "./jsonrpc.js";
2
2
  import { reasonFor } from "../bridge/refusal.js";
3
- import { COPY_TEXT_METHOD, NAVIGATING_METHOD, NAVIGATION_BLOCKED_METHOD, MCP_APPS_METHODS as M, MCP_APPS_PROTOCOL_VERSION, } from "./mcp-apps.js";
3
+ import { COPY_TEXT_METHOD, NAVIGATING_METHOD, NAVIGATION_BLOCKED_METHOD, MCP_APPS_METHODS as M, MCP_APPS_PROTOCOL_VERSION, MODEL_CONTEXT_OFFERED, } from "./mcp-apps.js";
4
4
  import { liveData } from "./live-data.js";
5
+ import { messageText } from "./message-text.js";
6
+ import { runtimeCalls } from "./runtime-calls.js";
7
+ import { RUNTIME_CALL_METHOD, RUNTIME_EXPERIMENTAL_KEY, RUNTIME_UNWATCH_METHOD, } from "../runtime/contract.js";
5
8
  /**
6
9
  * The core's adapter: the host side of the MCP Apps subset the shell speaks, which content using
7
10
  * the official App SDK speaks too. Every message is checked before use; every power goes through
@@ -9,23 +12,16 @@ import { liveData } from "./live-data.js";
9
12
  * after the view has initialized.
10
13
  */
11
14
  const LOG_ERRORS = new Set(["error", "critical", "alert", "emergency"]);
12
- /** Requests that are capability calls, and how their params become the capability's args. */
15
+ /**
16
+ * Requests that are capability calls, and how their params become the capability's args: shallow,
17
+ * or bounded (`messageText`), since they run before any gate (S05's class, P095).
18
+ */
13
19
  const REQUESTS = {
14
20
  [M.message]: {
15
21
  capability: "sendPrompt",
16
- args: (params) => ({
22
+ args: (params, config) => ({
17
23
  text: Array.isArray(params.content)
18
- ? params.content
19
- .map((part) => {
20
- const block = part;
21
- return block !== null &&
22
- typeof block === "object" &&
23
- block.type === "text" &&
24
- typeof block.text === "string"
25
- ? block.text
26
- : "";
27
- })
28
- .join("")
24
+ ? (messageText(params.content, "", config.limits.maxPromptChars) ?? "")
29
25
  : undefined,
30
26
  }),
31
27
  },
@@ -87,7 +83,7 @@ export function hostCapabilities(declared) {
87
83
  offered.serverResources = declared("subscribeData") ? { subscribe: true } : {};
88
84
  }
89
85
  if (declared("setModelContext")) {
90
- offered.updateModelContext = { text: {} };
86
+ offered.updateModelContext = MODEL_CONTEXT_OFFERED;
91
87
  }
92
88
  if (declared("reportError")) {
93
89
  offered.logging = {};
@@ -108,7 +104,20 @@ export const shellAdapter = {
108
104
  const respond = (id, body) => transport.send({ jsonrpc: "2.0", id, ...body });
109
105
  const notify = (method, params) => transport.send({ jsonrpc: "2.0", method, params });
110
106
  // Live data (P079): reads, subscriptions and the host's updates, through the bridge.
111
- const live = liveData(bridge, (uri) => notify(M.resourceUpdated, { uri }));
107
+ let live = liveData(bridge, (uri) => notify(M.resourceUpdated, { uri }));
108
+ // The capability runtime (P085), where the config has one: its calls and watches.
109
+ const runtime = session.compiled.config.runtime;
110
+ let calls = runtimeCalls(bridge, notify);
111
+ // A new page on the same transport (another of the set's pages, P084; or a reload that says
112
+ // hello again) starts with nothing followed: the last page's watches and subscriptions end,
113
+ // so it never hears their updates or their refusals (after the review).
114
+ let greeted = false;
115
+ const forget = () => {
116
+ calls.close();
117
+ calls = runtimeCalls(bridge, notify);
118
+ live.close();
119
+ live = liveData(bridge, (uri) => notify(M.resourceUpdated, { uri }));
120
+ };
112
121
  const flush = () => {
113
122
  if (!initialized || closed || content === null || sentWhole) {
114
123
  return;
@@ -126,11 +135,28 @@ export const shellAdapter = {
126
135
  const onRequest = async (request) => {
127
136
  const params = request.params ?? {};
128
137
  if (request.method === M.initialize) {
138
+ if (greeted) {
139
+ forget();
140
+ }
141
+ greeted = true;
129
142
  respond(request.id, {
130
143
  result: {
131
144
  protocolVersion: MCP_APPS_PROTOCOL_VERSION,
132
145
  hostInfo: session.hostInfo,
133
- hostCapabilities: hostCapabilities((name) => bridge.declared(name)),
146
+ hostCapabilities: {
147
+ ...hostCapabilities((name) => bridge.declared(name)),
148
+ // What this display's page may `use`, in MCP Apps' extension point (P085).
149
+ ...(runtime === undefined
150
+ ? {}
151
+ : {
152
+ experimental: {
153
+ [RUNTIME_EXPERIMENTAL_KEY]: {
154
+ version: runtime,
155
+ capabilities: bridge.roster(),
156
+ },
157
+ },
158
+ }),
159
+ },
134
160
  hostContext: session.hostContext(),
135
161
  },
136
162
  });
@@ -173,7 +199,15 @@ export const shellAdapter = {
173
199
  }
174
200
  return;
175
201
  }
176
- const mapped = REQUESTS[request.method];
202
+ if (request.method === RUNTIME_CALL_METHOD && runtime !== undefined) {
203
+ const answered = await calls.call(params);
204
+ if (!closed) {
205
+ respond(request.id, answered);
206
+ }
207
+ return;
208
+ }
209
+ // Its own entries only: `constructor` or `toString` is no request (S05's class, P095).
210
+ const mapped = Object.hasOwn(REQUESTS, request.method) ? REQUESTS[request.method] : undefined;
177
211
  if (mapped === undefined) {
178
212
  respond(request.id, {
179
213
  error: {
@@ -183,7 +217,7 @@ export const shellAdapter = {
183
217
  });
184
218
  return;
185
219
  }
186
- const outcome = await bridge.call(mapped.capability, mapped.args(params));
220
+ const outcome = await bridge.call(mapped.capability, mapped.args(params, session.compiled.config));
187
221
  if (!closed) {
188
222
  respond(request.id, answer(mapped.capability, outcome));
189
223
  }
@@ -201,19 +235,23 @@ export const shellAdapter = {
201
235
  void bridge.call("resize", { height: params.height, width: params.width });
202
236
  return;
203
237
  case M.log:
204
- if (LOG_ERRORS.has(String(params.level))) {
205
- const data = params.data;
206
- void bridge.call("reportError", {
207
- message: typeof data === "string" ? data : JSON.stringify(data ?? null).slice(0, 2_000),
208
- });
238
+ // What content said, as it came (S05, P095): the bridge reads it only within
239
+ // reportError's declaration and rate, into bounded text, and nothing in it throws here.
240
+ if (typeof params.level === "string" && LOG_ERRORS.has(params.level)) {
241
+ void bridge.call("reportError", { message: params.data });
209
242
  }
210
243
  return;
211
244
  case NAVIGATION_BLOCKED_METHOD:
212
245
  // The shell stopped a navigation (P080): an error report, with its address.
213
246
  void bridge.call("reportError", { navigationBlocked: params.url });
214
247
  return;
248
+ case RUNTIME_UNWATCH_METHOD:
249
+ calls.unwatch(params);
250
+ return;
215
251
  case NAVIGATING_METHOD:
216
- // Another page of the set opens in the frame (P084): its next load is that page.
252
+ // Another page of the set opens in the frame (P084): its next load is that page, which
253
+ // follows nothing yet.
254
+ forget();
217
255
  session.emit({ type: "navigating" });
218
256
  return;
219
257
  case M.requestTeardown:
@@ -275,6 +313,7 @@ export const shellAdapter = {
275
313
  stop();
276
314
  pending.clear();
277
315
  live.close();
316
+ calls.close();
278
317
  },
279
318
  };
280
319
  },
@@ -0,0 +1,32 @@
1
+ import type { ReactElement } from "react";
2
+ import type { CapabilityArgs } from "../config/capabilities.ts";
3
+ /**
4
+ * The default model context notice (P100): when content tells the agent something
5
+ * (`setModelContext`, MCP Apps' `ui/update-model-context`), the host's page shows the person all
6
+ * of it, outside every frame, before the host's handler has it: the text the agent reads at its
7
+ * next turn, in the content's words. One per display, the latest (an update replaces the last, as
8
+ * it does for the agent); it stays until the person hides it. Nothing in it is a question: the
9
+ * update has gone. All of it shows (after the review: the text box grows, never hiding a payload
10
+ * below blank lines, and says how many characters and lines it holds); the stack of displays
11
+ * scrolls within the window, so a later display never pushes an earlier one out of reach. A host replaces it by passing its own `show` (a chip by its composer, say); it
12
+ * styles it through the `porthole-context` class and data attributes.
13
+ */
14
+ export interface ContextUpdate {
15
+ /** The display's id and title, as the host named it. */
16
+ readonly displayId: string;
17
+ readonly title: string;
18
+ /** The update, whole: text blocks and structured content, as the bridge took them. */
19
+ readonly update: CapabilityArgs["setModelContext"];
20
+ }
21
+ export interface ContextNoticeProps {
22
+ /** The latest update of each display that sent one, in the order they came. */
23
+ readonly updates: readonly ContextUpdate[];
24
+ /** The person hid one display's notice (the agent still has its update). */
25
+ readonly onHide: (displayId: string) => void;
26
+ readonly className?: string;
27
+ }
28
+ /** How long an update is, in words: "412 characters, 3 lines". */
29
+ export declare function contextSize(text: string): string;
30
+ /** What the person is shown of an update: its text blocks, then its structured content's JSON. */
31
+ export declare function contextText(update: CapabilityArgs["setModelContext"]): string;
32
+ export declare function ContextNotice({ updates, onHide, className }: ContextNoticeProps): ReactElement;
@@ -0,0 +1,28 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /** How long an update is, in words: "412 characters, 3 lines". */
3
+ export function contextSize(text) {
4
+ const lines = text === "" ? 0 : text.split("\n").length;
5
+ return `${text.length.toLocaleString("en-US")} characters, ${lines.toLocaleString("en-US")} ${lines === 1 ? "line" : "lines"}`;
6
+ }
7
+ /** What the person is shown of an update: its text blocks, then its structured content's JSON. */
8
+ export function contextText(update) {
9
+ const text = (update.content ?? []).map((block) => block.text).join("\n\n");
10
+ const structured = update.structuredContent === undefined ? "" : JSON.stringify(update.structuredContent, null, 2);
11
+ return [text, structured].filter((part) => part !== "").join("\n\n");
12
+ }
13
+ const STYLE = `.porthole-context{position:fixed;right:16px;bottom:24px;z-index:2147483646;display:flex;flex-direction:column;gap:8px;width:min(380px,calc(100vw - 32px));max-height:calc(100vh - 48px);overflow-y:auto;overscroll-behavior:contain;font:inherit;font-size:.9em}
14
+ .porthole-context[hidden]{display:none}
15
+ .porthole-context>section{flex:none;color-scheme:light dark;color:CanvasText;background:Canvas;border:1px solid color-mix(in srgb,CanvasText 18%,transparent);border-radius:12px;padding:12px 14px;box-shadow:0 8px 28px rgb(0 0 0 / .25)}
16
+ .porthole-context p{margin:0 0 6px}
17
+ .porthole-context [data-porthole-source],.porthole-context [data-porthole-note],.porthole-context [data-porthole-context-size]{opacity:.72}
18
+ .porthole-context>[data-porthole-context-count]{flex:none;margin:0;padding:6px 12px;border-radius:8px;color-scheme:light dark;color:CanvasText;background:Canvas;border:1px solid color-mix(in srgb,CanvasText 18%,transparent)}
19
+ .porthole-context [data-porthole-context-size]{margin:6px 0 0}
20
+ .porthole-context pre{margin:0;white-space:pre-wrap;overflow-wrap:anywhere;padding:8px 10px;border-radius:8px;background:color-mix(in srgb,CanvasText 7%,transparent);font:12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace}
21
+ .porthole-context menu{display:flex;justify-content:flex-end;margin:8px 0 0;padding:0}
22
+ .porthole-context button{font:inherit;min-height:32px;padding:0 12px;border-radius:8px;border:1px solid color-mix(in srgb,CanvasText 25%,transparent);background:transparent;color:inherit;cursor:pointer}`;
23
+ export function ContextNotice({ updates, onHide, className }) {
24
+ return (_jsxs("div", { role: "status", "aria-live": "polite", className: className === undefined ? "porthole-context" : `porthole-context ${className}`, "data-porthole-context": "", hidden: updates.length === 0, children: [_jsx("style", { children: STYLE }), updates.length > 1 ? (_jsx("p", { "data-porthole-context-count": "", children: `${updates.length} displays told the agent something: scroll to read them all.` })) : null, updates.map((each) => {
25
+ const text = contextText(each.update);
26
+ return (_jsxs("section", { "data-porthole-context-display": each.displayId, children: [_jsxs("p", { children: [_jsx("strong", { children: "Context for the agent" }), " ", _jsx("span", { "data-porthole-source": "", children: `from “${each.title}”` })] }), _jsx("p", { "data-porthole-note": "", children: "The agent reads this at its next turn. It is the content\u2019s text, not yours." }), _jsx("pre", { "data-porthole-context-text": "", tabIndex: 0, children: text }), _jsx("p", { "data-porthole-context-size": "", children: contextSize(text) }), _jsx("menu", { children: _jsx("button", { type: "button", "data-porthole-hide": "", onClick: () => onHide(each.displayId), children: "Hide" }) })] }, each.displayId));
27
+ })] }));
28
+ }