@botiverse/porthole 0.7.0 → 0.9.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 (166) hide show
  1. package/README.md +9 -2
  2. package/THIRD_PARTY_NOTICES.md +421 -0
  3. package/dist/annotate/types.d.ts +40 -4
  4. package/dist/annotate/types.js +6 -1
  5. package/dist/annotate/validate.d.ts +10 -0
  6. package/dist/annotate/validate.js +24 -1
  7. package/dist/bridge/bounded-text.d.ts +34 -0
  8. package/dist/bridge/bounded-text.js +188 -0
  9. package/dist/bridge/bridge.d.ts +25 -5
  10. package/dist/bridge/bridge.js +311 -73
  11. package/dist/bridge/json-data.d.ts +28 -0
  12. package/dist/bridge/json-data.js +86 -0
  13. package/dist/bridge/navigation.d.ts +5 -0
  14. package/dist/bridge/navigation.js +7 -0
  15. package/dist/bridge/refusal.js +1 -0
  16. package/dist/bridge/types.d.ts +32 -1
  17. package/dist/check/page-source.js +1 -1
  18. package/dist/check/page.js +2 -0
  19. package/dist/compile/compile.d.ts +6 -0
  20. package/dist/compile/compile.js +3 -1
  21. package/dist/compile/policy.d.ts +38 -2
  22. package/dist/compile/policy.js +122 -7
  23. package/dist/config/capabilities.d.ts +23 -4
  24. package/dist/config/capabilities.js +12 -2
  25. package/dist/config/schema.d.ts +11 -0
  26. package/dist/config/validate.d.ts +8 -2
  27. package/dist/config/validate.js +28 -6
  28. package/dist/config/warnings.d.ts +20 -0
  29. package/dist/config/warnings.js +25 -0
  30. package/dist/conformance/behavior.js +46 -1
  31. package/dist/conformance/cookies.d.ts +15 -0
  32. package/dist/conformance/cookies.js +80 -0
  33. package/dist/conformance/harness/page.d.ts +1 -0
  34. package/dist/conformance/harness/page.js +9 -2
  35. package/dist/conformance/harness-source.js +1 -1
  36. package/dist/conformance/host-kit.js +5 -1
  37. package/dist/conformance/index.d.ts +10 -0
  38. package/dist/conformance/limits.js +38 -1
  39. package/dist/conformance/runtime.js +10 -0
  40. package/dist/conformance/served.d.ts +2 -0
  41. package/dist/conformance/served.js +737 -4
  42. package/dist/files/paths.js +4 -0
  43. package/dist/guide/gates.d.ts +7 -1
  44. package/dist/guide/gates.js +12 -0
  45. package/dist/guide/guide.js +2 -2
  46. package/dist/guide/runtime.js +11 -3
  47. package/dist/host/create-host.js +81 -39
  48. package/dist/host/pages-of-set.d.ts +43 -0
  49. package/dist/host/pages-of-set.js +196 -0
  50. package/dist/host/types.d.ts +8 -1
  51. package/dist/index.d.ts +5 -4
  52. package/dist/index.js +3 -2
  53. package/dist/mcp/adapter.js +11 -15
  54. package/dist/node/index.d.ts +36 -4
  55. package/dist/node/index.js +402 -101
  56. package/dist/platform/types.d.ts +9 -0
  57. package/dist/platform/web.js +8 -0
  58. package/dist/presets/presets.d.ts +16 -8
  59. package/dist/presets/presets.js +39 -8
  60. package/dist/protocol/live-data.d.ts +6 -2
  61. package/dist/protocol/live-data.js +20 -1
  62. package/dist/protocol/mcp-apps.d.ts +13 -2
  63. package/dist/protocol/mcp-apps.js +10 -2
  64. package/dist/protocol/message-text.d.ts +8 -0
  65. package/dist/protocol/message-text.js +29 -0
  66. package/dist/protocol/runtime-calls.js +3 -0
  67. package/dist/protocol/shell-adapter.js +16 -22
  68. package/dist/react/context-notice.d.ts +32 -0
  69. package/dist/react/context-notice.js +28 -0
  70. package/dist/react/dialog.js +62 -18
  71. package/dist/react/frame.d.ts +18 -3
  72. package/dist/react/frame.js +79 -2
  73. package/dist/react/index.d.ts +2 -1
  74. package/dist/react/index.js +2 -1
  75. package/dist/runtime/contract.d.ts +9 -1
  76. package/dist/runtime/contract.js +31 -2
  77. package/dist/runtime/db.d.ts +41 -6
  78. package/dist/runtime/db.js +120 -16
  79. package/dist/runtime/declaration.d.ts +15 -1
  80. package/dist/runtime/declaration.js +184 -87
  81. package/dist/runtime/requests.js +27 -11
  82. package/dist/runtime/types.generated.js +1 -1
  83. package/dist/server/files.d.ts +5 -0
  84. package/dist/server/files.js +22 -7
  85. package/dist/server/host.d.ts +18 -1
  86. package/dist/server/host.js +132 -2
  87. package/dist/server/index.d.ts +1 -1
  88. package/dist/server/index.js +1 -1
  89. package/dist/server/peer.d.ts +4 -0
  90. package/dist/server/peer.js +19 -0
  91. package/dist/server/proxy.d.ts +6 -0
  92. package/dist/server/proxy.js +12 -3
  93. package/dist/server/server.js +113 -26
  94. package/dist/server/types.d.ts +6 -3
  95. package/dist/shell/annotate.d.ts +7 -2
  96. package/dist/shell/annotate.js +233 -15
  97. package/dist/shell/document.d.ts +8 -0
  98. package/dist/shell/document.js +3 -0
  99. package/dist/shell/runtime.js +361 -14
  100. package/docs/ADOPTING.md +119 -14
  101. package/docs/ARCHITECTURE.md +15 -4
  102. package/docs/DECISIONS.md +1610 -9
  103. package/docs/DESIGN.md +114 -30
  104. package/docs/THREAT_MODEL.md +652 -0
  105. package/package.json +14 -3
  106. package/src/annotate/types.ts +37 -5
  107. package/src/annotate/validate.ts +30 -1
  108. package/src/bridge/bounded-text.ts +240 -0
  109. package/src/bridge/bridge.ts +373 -84
  110. package/src/bridge/json-data.ts +95 -0
  111. package/src/bridge/navigation.ts +10 -0
  112. package/src/bridge/refusal.ts +1 -0
  113. package/src/bridge/types.ts +30 -1
  114. package/src/check/page.ts +2 -0
  115. package/src/compile/compile.ts +9 -1
  116. package/src/compile/policy.ts +130 -7
  117. package/src/config/capabilities.ts +22 -3
  118. package/src/config/schema.ts +11 -0
  119. package/src/config/validate.ts +43 -5
  120. package/src/config/warnings.ts +42 -0
  121. package/src/conformance/behavior.ts +54 -1
  122. package/src/conformance/cookies.ts +93 -0
  123. package/src/conformance/harness/page.ts +11 -2
  124. package/src/conformance/host-kit.ts +10 -1
  125. package/src/conformance/index.ts +10 -0
  126. package/src/conformance/limits.ts +39 -1
  127. package/src/conformance/runtime.ts +21 -0
  128. package/src/conformance/served.ts +888 -4
  129. package/src/files/paths.ts +4 -0
  130. package/src/guide/gates.ts +13 -1
  131. package/src/guide/guide.ts +3 -3
  132. package/src/guide/runtime.ts +12 -3
  133. package/src/host/create-host.ts +88 -38
  134. package/src/host/pages-of-set.ts +226 -0
  135. package/src/host/types.ts +15 -1
  136. package/src/index.ts +5 -0
  137. package/src/mcp/adapter.ts +16 -20
  138. package/src/node/index.ts +507 -116
  139. package/src/platform/types.ts +6 -0
  140. package/src/platform/web.ts +10 -0
  141. package/src/presets/presets.ts +60 -17
  142. package/src/protocol/live-data.ts +31 -3
  143. package/src/protocol/mcp-apps.ts +11 -2
  144. package/src/protocol/message-text.ts +36 -0
  145. package/src/protocol/runtime-calls.ts +3 -0
  146. package/src/protocol/shell-adapter.ts +27 -23
  147. package/src/react/context-notice.tsx +95 -0
  148. package/src/react/dialog.tsx +77 -17
  149. package/src/react/frame.tsx +107 -2
  150. package/src/react/index.ts +8 -1
  151. package/src/runtime/contract.ts +36 -2
  152. package/src/runtime/db.ts +140 -20
  153. package/src/runtime/declaration.ts +227 -89
  154. package/src/runtime/requests.ts +27 -11
  155. package/src/runtime/types.generated.ts +1 -1
  156. package/src/server/files.ts +29 -11
  157. package/src/server/host.ts +158 -3
  158. package/src/server/index.ts +1 -0
  159. package/src/server/peer.ts +21 -0
  160. package/src/server/proxy.ts +13 -3
  161. package/src/server/server.ts +139 -36
  162. package/src/server/types.ts +6 -3
  163. package/src/shell/annotate.ts +233 -15
  164. package/src/shell/document.ts +8 -0
  165. package/src/shell/runtime.ts +361 -14
  166. package/types/runtime/v1/context.d.ts +13 -2
@@ -38,6 +38,12 @@ export interface Surface {
38
38
  * activates its ancestors), or undefined where the platform can't tell.
39
39
  */
40
40
  userActivation(): boolean | undefined;
41
+ /**
42
+ * The frame's viewport now, CSS px (its content box): what a box the frame reports is clamped
43
+ * to (P104). Undefined, or absent, where the platform can't tell: every reported box is then
44
+ * clamped to nothing, at the frame's corner.
45
+ */
46
+ viewport?(): { readonly width: number; readonly height: number } | undefined;
41
47
  /**
42
48
  * The frame loaded a document other than the one it was given: the content navigated it. The
43
49
  * framework starts it again from its content and reports it.
@@ -84,6 +84,16 @@ export const webPlatform: PlatformHost = {
84
84
  setColorScheme(scheme: ColorScheme) {
85
85
  frame.style.colorScheme = scheme;
86
86
  },
87
+ viewport() {
88
+ const style = view.getComputedStyle(frame);
89
+ const width =
90
+ frame.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
91
+ const height =
92
+ frame.clientHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom);
93
+ return Number.isFinite(width) && Number.isFinite(height)
94
+ ? { width: Math.max(0, width), height: Math.max(0, height) }
95
+ : undefined;
96
+ },
87
97
  userActivation() {
88
98
  const activation = (
89
99
  view.navigator as Navigator & { userActivation?: { isActive: boolean } }
@@ -58,11 +58,17 @@ export interface PresetOptions {
58
58
  readonly runtime?: RuntimeVersion;
59
59
  }
60
60
 
61
+ /** What a live widget may say about a capability (P103): anything but origins of its own. */
62
+ export type LiveCapabilityConfig = Omit<CapabilityConfig, "connect" | "resource">;
63
+
61
64
  /**
62
65
  * The live widget's options (P079): a widget's, less egress, which stays closed (Porthole's own
63
- * libraries come with domain isolation). A host adds capabilities, or changes the data ones' gates.
66
+ * libraries come with domain isolation), and less a capability's own origins, which are egress
67
+ * too (P103). A host adds capabilities, or changes the data ones' gates.
64
68
  */
65
- export type LiveWidgetOptions = Omit<PresetOptions, "egress">;
69
+ export type LiveWidgetOptions = Omit<PresetOptions, "egress" | "capabilities"> & {
70
+ readonly capabilities?: { readonly [N in CapabilityName]?: LiveCapabilityConfig | false };
71
+ };
66
72
 
67
73
  /** The url preset's options: where the app is served, and the embedding page's extra frames. */
68
74
  export interface UrlPresetOptions {
@@ -155,6 +161,27 @@ const mergeEgress = (base: EgressConfig, extra: EgressConfig | undefined): Egres
155
161
  return merged;
156
162
  };
157
163
 
164
+ /**
165
+ * A frozen copy of a config's data, all the way down (P103): what a host passed in stays its own
166
+ * and mutable; the copy can't be written into (a capability's `connect`, an egress origin).
167
+ */
168
+ function frozenCopy<T>(value: T): T {
169
+ if (Array.isArray(value)) {
170
+ return Object.freeze(value.map((each: unknown) => frozenCopy(each))) as T;
171
+ }
172
+ if (value !== null && typeof value === "object") {
173
+ const prototype: unknown = Object.getPrototypeOf(value);
174
+ if (prototype === Object.prototype || prototype === null) {
175
+ const copy: Record<string, unknown> = {};
176
+ for (const [key, each] of Object.entries(value)) {
177
+ copy[key] = frozenCopy(each);
178
+ }
179
+ return Object.freeze(copy) as T;
180
+ }
181
+ }
182
+ return value;
183
+ }
184
+
158
185
  /** The default variables, with the host's changes and additions, less those it dropped (null). */
159
186
  function themeVariables(
160
187
  changes: Readonly<Record<string, ThemeValue | null>> | undefined,
@@ -226,12 +253,13 @@ export const presets = {
226
253
 
227
254
  /**
228
255
  * A widget that shows its host's data, live, and has no network of its own (P079): an inline
229
- * widget whose egress stays closed (no option opens it). It reads the host's data (`readData`,
230
- * MCP `resources/read`) and subscribes to it (`subscribeData`, `resources/subscribe`), each
231
- * behind the viewer's consent (the host's `consent`, asked once per display) and a rate. In
232
- * domain isolation its scripts load from Porthole's own libraries on its origin
233
- * (`egress.libraries`: Chart.js, D3), and nowhere else. A host adds what any widget may have (a
234
- * link, a copy button), or changes the data capabilities' gates.
256
+ * widget whose egress stays closed (no option opens it: neither `egress` nor a capability's own
257
+ * `connect` or `resource`, P103). It reads the host's data (`readData`, MCP `resources/read`)
258
+ * and subscribes to it (`subscribeData`, `resources/subscribe`), each behind the viewer's
259
+ * consent (the host's `consent`, asked once per display) and a rate. In domain isolation its
260
+ * scripts load from Porthole's own libraries on its origin (`egress.libraries`: Chart.js, D3),
261
+ * and nowhere else. A host adds what any widget may have (a link, a copy button), or changes the
262
+ * data capabilities' gates.
235
263
  */
236
264
  liveWidget: (options: LiveWidgetOptions = {}): PortholeConfig => {
237
265
  if ((options as PresetOptions).egress !== undefined) {
@@ -240,16 +268,31 @@ export const presets = {
240
268
  "a live widget has no network of its own: its egress stays closed (P079)",
241
269
  );
242
270
  }
243
- return build(
244
- "inline",
245
- {
246
- capabilities: {
247
- readData: { gates: ["consent", { rateLimit: { perMinute: 120 } }] },
248
- subscribeData: { gates: ["consent", { rateLimit: { perMinute: 60 } }] },
271
+ // A capability's own origins join the CSP as egress does (P103): none for a live widget.
272
+ for (const [name, value] of Object.entries((options as PresetOptions).capabilities ?? {})) {
273
+ for (const field of ["connect", "resource"] as const) {
274
+ if (typeof value === "object" && value !== null && value[field] !== undefined) {
275
+ throw new ConfigError(
276
+ `options.capabilities.${name}.${field}`,
277
+ "a live widget has no network of its own: no capability opens origins for it (P079, P103)",
278
+ );
279
+ }
280
+ }
281
+ }
282
+ // Frozen, all the way down (P103): nothing writes an origin into the preset's config after it
283
+ // is made. A config a host builds from it (a spread) is the host's own, not this preset.
284
+ return frozenCopy(
285
+ build(
286
+ "inline",
287
+ {
288
+ capabilities: {
289
+ readData: { gates: ["consent", { rateLimit: { perMinute: 120 } }] },
290
+ subscribeData: { gates: ["consent", { rateLimit: { perMinute: 60 } }] },
291
+ },
292
+ egress: options.isolation === "domain" ? { libraries: true } : {},
249
293
  },
250
- egress: options.isolation === "domain" ? { libraries: true } : {},
251
- },
252
- options,
294
+ options,
295
+ ),
253
296
  );
254
297
  },
255
298
 
@@ -6,10 +6,14 @@ import { STALE_META } from "./mcp-apps.ts";
6
6
  * `resources/subscribe`, `resources/unsubscribe`, `notifications/resources/updated`): the frame's
7
7
  * subscriptions by URI, each ended by its controller, and a fresh result the host gave for one
8
8
  * (pushed through `changed(result)`, or read after a stale answer), kept for the frame's next read
9
- * of it. Every call goes through the bridge, which gates it; the adapter only says what to send.
9
+ * of it. Every call goes through the bridge, which gates it, a read answered by a kept result too
10
+ * (P094); the adapter only says what to send.
10
11
  */
11
12
  export interface LiveData {
12
- /** A read: a fresh result kept for it, else the host's (its cache first, when subscribed). */
13
+ /**
14
+ * A read, past the read's gates whatever answers it: a fresh result kept for it, else the
15
+ * host's (its cache first, when subscribed).
16
+ */
13
17
  read(uri: unknown): Promise<CallOutcome<unknown>>;
14
18
  /** Starts the host's subscription; a second for a URI is a no-op. */
15
19
  subscribe(uri: unknown): Promise<CallOutcome<undefined>>;
@@ -19,6 +23,12 @@ export interface LiveData {
19
23
  close(): void;
20
24
  }
21
25
 
26
+ /**
27
+ * The most resources one frame follows at once (P095), as the runtime's watches (50): past it a
28
+ * subscription is refused as too large, and the host isn't asked.
29
+ */
30
+ const MAX_SUBSCRIPTIONS = 50;
31
+
22
32
  /** Where MCP results carry their metadata. */
23
33
  const META = "_meta";
24
34
 
@@ -62,9 +72,20 @@ export function liveData(
62
72
  return {
63
73
  async read(uri) {
64
74
  if (typeof uri === "string" && fresh.has(uri)) {
75
+ // A kept result is the host's answer to a read: it goes through the read's gates as any
76
+ // read does (level, names, rate, gesture, consent, confirm), with no new upstream call
77
+ // (P094). Used once; kept again if the gates refused it and nothing newer came.
65
78
  const value = fresh.get(uri);
66
79
  fresh.delete(uri);
67
- return { ok: true, value };
80
+ const outcome = await bridge.call(
81
+ "readData",
82
+ { uri },
83
+ { ...activation(), held: { uri, value } },
84
+ );
85
+ if (!outcome.ok && !closed && subscriptions.has(uri) && !fresh.has(uri)) {
86
+ fresh.set(uri, value);
87
+ }
88
+ return outcome;
68
89
  }
69
90
  const subscribed = typeof uri === "string" && subscriptions.has(uri);
70
91
  const outcome = await bridge.call(
@@ -90,6 +111,13 @@ export function liveData(
90
111
  if (typeof uri === "string" && subscriptions.has(uri)) {
91
112
  return { ok: true, value: undefined };
92
113
  }
114
+ if (subscriptions.size >= MAX_SUBSCRIPTIONS) {
115
+ return {
116
+ ok: false,
117
+ refusal: "too-large",
118
+ reason: { code: "too_large", message: "Too many things followed at once." },
119
+ };
120
+ }
93
121
  const controller = new AbortController();
94
122
  if (typeof uri === "string") {
95
123
  subscriptions.set(uri, controller);
@@ -42,6 +42,13 @@ export const MCP_APPS_METHODS = {
42
42
 
43
43
  export type McpAppsMethod = (typeof MCP_APPS_METHODS)[keyof typeof MCP_APPS_METHODS];
44
44
 
45
+ /**
46
+ * What a host that declares `setModelContext` says it takes (`hostCapabilities.updateModelContext`),
47
+ * in both adapters: text blocks and structured content, exactly what the bridge accepts and the
48
+ * person is shown (P100). Images and other blocks aren't offered, and are refused.
49
+ */
50
+ export const MODEL_CONTEXT_OFFERED = { text: {}, structuredContent: {} } as const;
51
+
45
52
  /**
46
53
  * What the shell's `tool-input(-partial)` carries: the content to draw. Porthole's own argument
47
54
  * names, since the shell is the only view that reads them.
@@ -142,8 +149,10 @@ export const NAVIGATION_BLOCKED_METHOD = "porthole/navigation-blocked";
142
149
 
143
150
  /**
144
151
  * Porthole's own notification from the shell (P084): a page that came with files is opening
145
- * another page of its set, `{ url }`, in the frame. The host takes the frame's next load for that
146
- * page rather than for content that left (P031). The content's word: it only spares a restart.
152
+ * another page of its set, `{ url }`, in the frame; and, as it arrives, the page a navigation
153
+ * opened says so, `{ url, arrived: true }` (P098). The host takes the frame's next load (or the
154
+ * load it came after, within `LATE_NOTICE_MS`) for that page rather than for content that left
155
+ * (P031). The content's word: it only spares a restart.
147
156
  */
148
157
  export const NAVIGATING_METHOD = "porthole/navigating";
149
158
 
@@ -0,0 +1,36 @@
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
+ /**
5
+ * The text of a `ui/message`'s content blocks, the adapters' one reading of it: its text blocks'
6
+ * text, in order, joined by `separator`; null where there is none, or more blocks than a message
7
+ * holds. Read before any gate, so only as far as `max` characters (S05's class, P095: structured
8
+ * clone delivers a sparse array of any length, or one block shared a million times, for the cost
9
+ * of one): past it, `max + 1` characters, which the bridge refuses as too long.
10
+ */
11
+ export function messageText(
12
+ blocks: readonly unknown[],
13
+ separator: string,
14
+ max: number,
15
+ ): string | null {
16
+ if (blocks.length > MAX_BLOCKS) {
17
+ return null;
18
+ }
19
+ let text: string | null = null;
20
+ for (let index = 0; index < blocks.length; index += 1) {
21
+ const block = blocks[index] as { type?: unknown; text?: unknown } | null | undefined;
22
+ if (
23
+ block !== null &&
24
+ typeof block === "object" &&
25
+ !Array.isArray(block) &&
26
+ block.type === "text" &&
27
+ typeof block.text === "string"
28
+ ) {
29
+ text = text === null ? block.text : `${text}${separator}${block.text}`;
30
+ if (text.length > max) {
31
+ return text.slice(0, max + 1);
32
+ }
33
+ }
34
+ }
35
+ return text;
36
+ }
@@ -106,6 +106,9 @@ export function runtimeCalls(
106
106
  watches.set(id, controller);
107
107
  const outcome = await bridge.call(mapped.serves, mapped.args, {
108
108
  subscription: {
109
+ // Each update is the watch's answer, gated as its read when it started (P091, P094):
110
+ // nothing that check read changes while it lives (the frame's viewer and declaration,
111
+ // the display's kept consent), and a new page or frame ends it. So no gate per update.
109
112
  changed: (data?: unknown) => {
110
113
  if (!controller.signal.aborted) {
111
114
  notify(RUNTIME_EVENT_METHOD, { watch: id, data: data ?? null });
@@ -1,4 +1,5 @@
1
1
  import type { CapabilityName } from "../config/capabilities.ts";
2
+ import type { PortholeConfig } from "../config/schema.ts";
2
3
  import type { CallOutcome } from "../bridge/types.ts";
3
4
  import type { AdapterSession, ProtocolAdapter, ShellConnection } from "./adapter.ts";
4
5
  import {
@@ -15,9 +16,11 @@ import {
15
16
  NAVIGATION_BLOCKED_METHOD,
16
17
  MCP_APPS_METHODS as M,
17
18
  MCP_APPS_PROTOCOL_VERSION,
19
+ MODEL_CONTEXT_OFFERED,
18
20
  type HostContext,
19
21
  } from "./mcp-apps.ts";
20
22
  import { liveData } from "./live-data.ts";
23
+ import { messageText } from "./message-text.ts";
21
24
  import { runtimeCalls } from "./runtime-calls.ts";
22
25
  import {
23
26
  RUNTIME_CALL_METHOD,
@@ -34,25 +37,24 @@ import {
34
37
 
35
38
  const LOG_ERRORS = new Set(["error", "critical", "alert", "emergency"]);
36
39
 
37
- /** Requests that are capability calls, and how their params become the capability's args. */
40
+ /**
41
+ * Requests that are capability calls, and how their params become the capability's args: shallow,
42
+ * or bounded (`messageText`), since they run before any gate (S05's class, P095).
43
+ */
38
44
  const REQUESTS: Readonly<
39
- Record<string, { capability: CapabilityName; args: (params: Record<string, unknown>) => unknown }>
45
+ Record<
46
+ string,
47
+ {
48
+ capability: CapabilityName;
49
+ args: (params: Record<string, unknown>, config: PortholeConfig) => unknown;
50
+ }
51
+ >
40
52
  > = {
41
53
  [M.message]: {
42
54
  capability: "sendPrompt",
43
- args: (params) => ({
55
+ args: (params, config) => ({
44
56
  text: Array.isArray(params.content)
45
- ? params.content
46
- .map((part: unknown) => {
47
- const block = part as { type?: unknown; text?: unknown } | null;
48
- return block !== null &&
49
- typeof block === "object" &&
50
- block.type === "text" &&
51
- typeof block.text === "string"
52
- ? block.text
53
- : "";
54
- })
55
- .join("")
57
+ ? (messageText(params.content, "", config.limits.maxPromptChars) ?? "")
56
58
  : undefined,
57
59
  }),
58
60
  },
@@ -122,7 +124,7 @@ export function hostCapabilities(
122
124
  offered.serverResources = declared("subscribeData") ? { subscribe: true } : {};
123
125
  }
124
126
  if (declared("setModelContext")) {
125
- offered.updateModelContext = { text: {} };
127
+ offered.updateModelContext = MODEL_CONTEXT_OFFERED;
126
128
  }
127
129
  if (declared("reportError")) {
128
130
  offered.logging = {};
@@ -252,7 +254,8 @@ export const shellAdapter: ProtocolAdapter<ShellConnection> = {
252
254
  }
253
255
  return;
254
256
  }
255
- const mapped = REQUESTS[request.method];
257
+ // Its own entries only: `constructor` or `toString` is no request (S05's class, P095).
258
+ const mapped = Object.hasOwn(REQUESTS, request.method) ? REQUESTS[request.method] : undefined;
256
259
  if (mapped === undefined) {
257
260
  respond(request.id, {
258
261
  error: {
@@ -262,7 +265,10 @@ export const shellAdapter: ProtocolAdapter<ShellConnection> = {
262
265
  });
263
266
  return;
264
267
  }
265
- const outcome = await bridge.call(mapped.capability, mapped.args(params));
268
+ const outcome = await bridge.call(
269
+ mapped.capability,
270
+ mapped.args(params, session.compiled.config),
271
+ );
266
272
  if (!closed) {
267
273
  respond(request.id, answer(mapped.capability, outcome));
268
274
  }
@@ -281,12 +287,10 @@ export const shellAdapter: ProtocolAdapter<ShellConnection> = {
281
287
  void bridge.call("resize", { height: params.height, width: params.width });
282
288
  return;
283
289
  case M.log:
284
- if (LOG_ERRORS.has(String(params.level))) {
285
- const data = params.data;
286
- void bridge.call("reportError", {
287
- message:
288
- typeof data === "string" ? data : JSON.stringify(data ?? null).slice(0, 2_000),
289
- });
290
+ // What content said, as it came (S05, P095): the bridge reads it only within
291
+ // reportError's declaration and rate, into bounded text, and nothing in it throws here.
292
+ if (typeof params.level === "string" && LOG_ERRORS.has(params.level)) {
293
+ void bridge.call("reportError", { message: params.data });
290
294
  }
291
295
  return;
292
296
  case NAVIGATION_BLOCKED_METHOD:
@@ -0,0 +1,95 @@
1
+ import type { ReactElement } from "react";
2
+ import type { CapabilityArgs } from "../config/capabilities.ts";
3
+
4
+ /**
5
+ * The default model context notice (P100): when content tells the agent something
6
+ * (`setModelContext`, MCP Apps' `ui/update-model-context`), the host's page shows the person all
7
+ * of it, outside every frame, before the host's handler has it: the text the agent reads at its
8
+ * next turn, in the content's words. One per display, the latest (an update replaces the last, as
9
+ * it does for the agent); it stays until the person hides it. Nothing in it is a question: the
10
+ * update has gone. All of it shows (after the review: the text box grows, never hiding a payload
11
+ * below blank lines, and says how many characters and lines it holds); the stack of displays
12
+ * 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
13
+ * styles it through the `porthole-context` class and data attributes.
14
+ */
15
+
16
+ export interface ContextUpdate {
17
+ /** The display's id and title, as the host named it. */
18
+ readonly displayId: string;
19
+ readonly title: string;
20
+ /** The update, whole: text blocks and structured content, as the bridge took them. */
21
+ readonly update: CapabilityArgs["setModelContext"];
22
+ }
23
+
24
+ export interface ContextNoticeProps {
25
+ /** The latest update of each display that sent one, in the order they came. */
26
+ readonly updates: readonly ContextUpdate[];
27
+ /** The person hid one display's notice (the agent still has its update). */
28
+ readonly onHide: (displayId: string) => void;
29
+ readonly className?: string;
30
+ }
31
+
32
+ /** How long an update is, in words: "412 characters, 3 lines". */
33
+ export function contextSize(text: string): string {
34
+ const lines = text === "" ? 0 : text.split("\n").length;
35
+ return `${text.length.toLocaleString("en-US")} characters, ${lines.toLocaleString("en-US")} ${lines === 1 ? "line" : "lines"}`;
36
+ }
37
+
38
+ /** What the person is shown of an update: its text blocks, then its structured content's JSON. */
39
+ export function contextText(update: CapabilityArgs["setModelContext"]): string {
40
+ const text = (update.content ?? []).map((block) => block.text).join("\n\n");
41
+ const structured =
42
+ update.structuredContent === undefined ? "" : JSON.stringify(update.structuredContent, null, 2);
43
+ return [text, structured].filter((part) => part !== "").join("\n\n");
44
+ }
45
+
46
+ 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}
47
+ .porthole-context[hidden]{display:none}
48
+ .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)}
49
+ .porthole-context p{margin:0 0 6px}
50
+ .porthole-context [data-porthole-source],.porthole-context [data-porthole-note],.porthole-context [data-porthole-context-size]{opacity:.72}
51
+ .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)}
52
+ .porthole-context [data-porthole-context-size]{margin:6px 0 0}
53
+ .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}
54
+ .porthole-context menu{display:flex;justify-content:flex-end;margin:8px 0 0;padding:0}
55
+ .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}`;
56
+
57
+ export function ContextNotice({ updates, onHide, className }: ContextNoticeProps): ReactElement {
58
+ return (
59
+ <div
60
+ role="status"
61
+ aria-live="polite"
62
+ className={className === undefined ? "porthole-context" : `porthole-context ${className}`}
63
+ data-porthole-context=""
64
+ hidden={updates.length === 0}
65
+ >
66
+ <style>{STYLE}</style>
67
+ {updates.length > 1 ? (
68
+ <p data-porthole-context-count="">{`${updates.length} displays told the agent something: scroll to read them all.`}</p>
69
+ ) : null}
70
+ {updates.map((each) => {
71
+ const text = contextText(each.update);
72
+ return (
73
+ <section key={each.displayId} data-porthole-context-display={each.displayId}>
74
+ <p>
75
+ <strong>Context for the agent</strong>{" "}
76
+ <span data-porthole-source="">{`from “${each.title}”`}</span>
77
+ </p>
78
+ <p data-porthole-note="">
79
+ The agent reads this at its next turn. It is the content’s text, not yours.
80
+ </p>
81
+ <pre data-porthole-context-text="" tabIndex={0}>
82
+ {text}
83
+ </pre>
84
+ <p data-porthole-context-size="">{contextSize(text)}</p>
85
+ <menu>
86
+ <button type="button" data-porthole-hide="" onClick={() => onHide(each.displayId)}>
87
+ Hide
88
+ </button>
89
+ </menu>
90
+ </section>
91
+ );
92
+ })}
93
+ </div>
94
+ );
95
+ }
@@ -1,4 +1,5 @@
1
- import { useEffect, useId, useRef, useState, type ReactElement } from "react";
1
+ import { useEffect, useId, useMemo, useRef, useState, type ReactElement } from "react";
2
+ import { formatBounded, type TextLimits } from "../bridge/bounded-text.ts";
2
3
  import type { ConfirmRequest } from "../bridge/types.ts";
3
4
 
4
5
  /**
@@ -24,13 +25,62 @@ export interface ConfirmDialogProps {
24
25
  interface Words {
25
26
  readonly heading: string;
26
27
  readonly accept: string;
28
+ /**
29
+ * What asked for the yes, above the detail (which scrolls): a db batch's writes whose gates
30
+ * asked, however late in the batch they come (P094).
31
+ */
32
+ readonly summary?: string;
27
33
  /** What the person is shown in full. */
28
34
  readonly detail: string;
29
35
  /** A line under it (the link's host). */
30
36
  readonly note?: string;
31
37
  }
32
38
 
33
- const json = (value: unknown): string => JSON.stringify(value, null, 2) ?? "";
39
+ /**
40
+ * What a call carries, as JSON laid out, within bounds (P095): a frame's arguments come
41
+ * structured-cloned, so a cycle, a BigInt, or a graph billions of nodes long as a tree. Past the
42
+ * bounds the dialog says it shows only part.
43
+ */
44
+ const DIALOG_TEXT_LIMITS: TextLimits = { chars: 20_000, nodes: 2_000, depth: 24 };
45
+
46
+ function carried(heading: string, accept: string, value: unknown, before = ""): Words {
47
+ const { text, whole } = formatBounded(value, DIALOG_TEXT_LIMITS, 2);
48
+ return {
49
+ heading,
50
+ accept,
51
+ detail: `${before}${text}`,
52
+ ...(whole ? {} : { note: "Only part of it is shown: it is more than this dialog shows." }),
53
+ };
54
+ }
55
+
56
+ /** How many of one kind of write the summary names before it counts the rest. */
57
+ const MOST_PATHS = 10;
58
+
59
+ /**
60
+ * A db change in a line (P094): the writes whose own gates asked for the yes, by kind ("Delete
61
+ * n/x, n/y; and 48 other writes."), or every write by kind where none of them asked (the host
62
+ * function's own confirmation); at most `MOST_PATHS` paths a kind, then a count.
63
+ */
64
+ function writesSummary(
65
+ writes: readonly { readonly op: string; readonly path: string }[],
66
+ askedBy: readonly string[],
67
+ ): string {
68
+ const asked = writes.filter((each) => askedBy.includes(each.op));
69
+ const lead = asked.length === 0 ? writes : asked;
70
+ const kinds = new Map<string, string[]>();
71
+ for (const each of lead) {
72
+ kinds.set(each.op, [...(kinds.get(each.op) ?? []), each.path]);
73
+ }
74
+ const said = [...kinds]
75
+ .map(
76
+ ([op, paths]) =>
77
+ `${op} ${paths.slice(0, MOST_PATHS).join(", ")}${paths.length > MOST_PATHS ? ` and ${paths.length - MOST_PATHS} more` : ""}`,
78
+ )
79
+ .join("; ");
80
+ const others = writes.length - lead.length;
81
+ const text = `${said}${others === 0 ? "" : `; and ${others} other write${others === 1 ? "" : "s"}`}.`;
82
+ return text.charAt(0).toUpperCase() + text.slice(1);
83
+ }
34
84
 
35
85
  function words(request: ConfirmRequest): Words {
36
86
  switch (request.capability) {
@@ -51,19 +101,11 @@ function words(request: ConfirmRequest): Words {
51
101
  };
52
102
  }
53
103
  case "downloadFile":
54
- return {
55
- heading: "Download this file?",
56
- accept: "Download",
57
- detail: json(request.args.contents),
58
- };
104
+ return carried("Download this file?", "Download", request.args.contents);
59
105
  case "callTool":
60
- return {
61
- heading: "Run this tool?",
62
- accept: "Run",
63
- detail: `${request.args.name}\n${json(request.args.arguments)}`,
64
- };
106
+ return carried("Run this tool?", "Run", request.args.arguments, `${request.args.name}\n`);
65
107
  case "setModelContext":
66
- return { heading: "Share this with the agent?", accept: "Share", detail: json(request.args) };
108
+ return carried("Share this with the agent?", "Share", request.args);
67
109
  case "readData":
68
110
  return { heading: "Let it read this?", accept: "Allow", detail: request.args.uri };
69
111
  case "subscribeData":
@@ -87,7 +129,7 @@ function words(request: ConfirmRequest): Words {
87
129
  .join("\n"),
88
130
  note: `From version ${request.args.base}${request.args.label === undefined ? "" : `: ${request.args.label}`}.`,
89
131
  }
90
- : { heading: "Allow this?", accept: "Allow", detail: json(request.args) };
132
+ : carried("Allow this?", "Allow", request.args);
91
133
  case "assets":
92
134
  return request.args.op === "upload"
93
135
  ? {
@@ -102,9 +144,25 @@ function words(request: ConfirmRequest): Words {
102
144
  accept: "Remove",
103
145
  detail: request.args.id,
104
146
  }
105
- : { heading: "Allow this?", accept: "Allow", detail: json(request.args) };
147
+ : carried("Allow this?", "Allow", request.args);
148
+ // The page's shared data (P088): a change leads with what asked for the yes (P094).
149
+ case "db": {
150
+ const args = request.args;
151
+ const writes =
152
+ args.op === "batch"
153
+ ? args.writes
154
+ : args.op === "set" || args.op === "update" || args.op === "delete"
155
+ ? [args]
156
+ : null;
157
+ return writes === null
158
+ ? carried("Allow this?", "Allow", args)
159
+ : {
160
+ ...carried("Change this page's shared data?", "Change", args),
161
+ summary: writesSummary(writes, request.askedBy ?? []),
162
+ };
163
+ }
106
164
  default:
107
- return { heading: "Allow this?", accept: "Allow", detail: json(request.args) };
165
+ return carried("Allow this?", "Allow", request.args);
108
166
  }
109
167
  }
110
168
 
@@ -112,6 +170,7 @@ const STYLE = `.porthole-confirm{color-scheme:light dark;color:CanvasText;backgr
112
170
  .porthole-confirm::backdrop{background:rgb(0 0 0 / .4)}
113
171
  .porthole-confirm h2{font-size:1.05em;margin:0 0 4px}
114
172
  .porthole-confirm [data-porthole-source],.porthole-confirm [data-porthole-note]{opacity:.72;font-size:.9em;margin:0 0 12px}
173
+ .porthole-confirm [data-porthole-summary]{font-weight:600;overflow-wrap:anywhere;max-height:20vh;overflow:auto;margin:0 0 12px}
115
174
  .porthole-confirm [data-porthole-detail]{white-space:pre-wrap;overflow-wrap:anywhere;max-height:40vh;overflow:auto;padding:10px 12px;border-radius:8px;background:color-mix(in srgb,CanvasText 7%,transparent);margin:0 0 12px;font:inherit}
116
175
  .porthole-confirm menu{display:flex;justify-content:flex-end;gap:8px;margin:16px 0 0;padding:0}
117
176
  .porthole-confirm button{font:inherit;min-height:36px;padding:0 14px;border-radius:8px;border:1px solid color-mix(in srgb,CanvasText 25%,transparent);background:transparent;color:inherit;cursor:pointer}
@@ -144,7 +203,7 @@ export function ConfirmDialog({ request, onAnswer, className }: ConfirmDialogPro
144
203
  return () => clearTimeout(timer);
145
204
  }, [request]);
146
205
 
147
- const said = request === null ? null : words(request);
206
+ const said = useMemo(() => (request === null ? null : words(request)), [request]);
148
207
  return (
149
208
  <dialog
150
209
  ref={dialog}
@@ -163,6 +222,7 @@ export function ConfirmDialog({ request, onAnswer, className }: ConfirmDialogPro
163
222
  <>
164
223
  <h2 id={heading}>{said.heading}</h2>
165
224
  <p data-porthole-source="">{`From “${request.display.title}”`}</p>
225
+ {said.summary === undefined ? null : <p data-porthole-summary="">{said.summary}</p>}
166
226
  <div data-porthole-detail="">{said.detail}</div>
167
227
  {said.note === undefined ? null : <p data-porthole-note="">{said.note}</p>}
168
228
  <menu>