@botiverse/porthole 0.4.0 → 0.5.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 (73) hide show
  1. package/README.md +3 -1
  2. package/dist/bridge/bridge.d.ts +16 -2
  3. package/dist/bridge/bridge.js +65 -12
  4. package/dist/bridge/types.d.ts +44 -6
  5. package/dist/check/lint.js +2 -2
  6. package/dist/check/page-source.js +1 -1
  7. package/dist/check/page.js +5 -0
  8. package/dist/compile/policy.d.ts +5 -0
  9. package/dist/compile/policy.js +18 -1
  10. package/dist/config/capabilities.d.ts +25 -2
  11. package/dist/config/capabilities.js +13 -0
  12. package/dist/config/schema.d.ts +7 -0
  13. package/dist/config/validate.js +14 -3
  14. package/dist/conformance/harness/page.js +1 -0
  15. package/dist/conformance/harness-source.js +1 -1
  16. package/dist/displays/displays.d.ts +1 -1
  17. package/dist/guide/guide.js +48 -8
  18. package/dist/host/create-host.js +5 -1
  19. package/dist/host/types.d.ts +12 -1
  20. package/dist/index.d.ts +4 -3
  21. package/dist/index.js +2 -1
  22. package/dist/libraries/files.generated.d.ts +1 -0
  23. package/dist/libraries/files.generated.js +8 -0
  24. package/dist/libraries/libraries.d.ts +36 -0
  25. package/dist/libraries/libraries.js +40 -0
  26. package/dist/mcp/adapter.js +31 -2
  27. package/dist/presets/presets.d.ts +15 -0
  28. package/dist/presets/presets.js +27 -2
  29. package/dist/protocol/live-data.d.ts +27 -0
  30. package/dist/protocol/live-data.js +98 -0
  31. package/dist/protocol/mcp-apps.d.ts +9 -0
  32. package/dist/protocol/mcp-apps.js +11 -0
  33. package/dist/protocol/shell-adapter.js +35 -2
  34. package/dist/react/dialog.js +2 -0
  35. package/dist/react/frame.d.ts +15 -1
  36. package/dist/react/frame.js +35 -1
  37. package/dist/server/libraries.d.ts +7 -0
  38. package/dist/server/libraries.js +27 -0
  39. package/dist/server/server.js +2 -1
  40. package/dist/shell/annotate.js +4 -1
  41. package/dist/shell/runtime.d.ts +5 -1
  42. package/dist/shell/runtime.js +165 -1
  43. package/docs/ADOPTING.md +57 -1
  44. package/docs/DECISIONS.md +129 -0
  45. package/docs/DESIGN.md +19 -6
  46. package/package.json +3 -1
  47. package/src/bridge/bridge.ts +85 -13
  48. package/src/bridge/types.ts +45 -3
  49. package/src/check/lint.ts +2 -1
  50. package/src/check/page.ts +5 -0
  51. package/src/compile/policy.ts +19 -1
  52. package/src/config/capabilities.ts +21 -0
  53. package/src/config/schema.ts +7 -0
  54. package/src/config/validate.ts +21 -3
  55. package/src/conformance/harness/page.ts +1 -0
  56. package/src/displays/displays.ts +1 -1
  57. package/src/guide/guide.ts +57 -7
  58. package/src/host/create-host.ts +5 -1
  59. package/src/host/types.ts +12 -1
  60. package/src/index.ts +13 -0
  61. package/src/libraries/files.generated.ts +8 -0
  62. package/src/libraries/libraries.ts +64 -0
  63. package/src/mcp/adapter.ts +40 -2
  64. package/src/presets/presets.ts +46 -3
  65. package/src/protocol/live-data.ts +138 -0
  66. package/src/protocol/mcp-apps.ts +12 -0
  67. package/src/protocol/shell-adapter.ts +35 -3
  68. package/src/react/dialog.tsx +2 -0
  69. package/src/react/frame.tsx +54 -0
  70. package/src/server/libraries.ts +28 -0
  71. package/src/server/server.ts +2 -1
  72. package/src/shell/annotate.ts +4 -1
  73. package/src/shell/runtime.ts +165 -1
@@ -10,6 +10,7 @@ import { parseReport } from "../annotate/validate.ts";
10
10
  import type { PortholeConfig } from "../config/schema.ts";
11
11
  import { effectiveGates } from "../compile/policy.ts";
12
12
  import type {
13
+ CallOptions,
13
14
  CallOutcome,
14
15
  CapabilityHandler,
15
16
  CapabilityHandlers,
@@ -17,6 +18,8 @@ import type {
17
18
  ConfirmAnswer,
18
19
  ConfirmDisplay,
19
20
  ConfirmRequest,
21
+ Consent,
22
+ DataCache,
20
23
  HostFunctionBridge,
21
24
  Refusal,
22
25
  } from "./types.ts";
@@ -24,7 +27,8 @@ import type {
24
27
  /**
25
28
  * The host-function bridge: every capability call from a frame passes here, and nowhere else
26
29
  * reaches a host handler. In order: declared → arguments well formed → not muted → within its
27
- * rate → a user gesture, if gated so → a person's confirmation, if gated so → the handler.
30
+ * rate → a user gesture, if gated so → the viewer's consent, if gated so → a person's
31
+ * confirmation, if gated so → the handler (or, for a stale-allowed read, the host's cache).
28
32
  */
29
33
 
30
34
  export type BridgeEvent =
@@ -39,6 +43,13 @@ export interface BridgeOptions {
39
43
  readonly display: ConfirmDisplay;
40
44
  readonly handlers: CapabilityHandlers;
41
45
  readonly confirm?: Confirm;
46
+ /**
47
+ * Asked before a `consent`-gated call (P079). The host's, made to ask once per display by the
48
+ * caller (`createHost` keeps the answer across the display's frames).
49
+ */
50
+ readonly consent?: Consent;
51
+ /** The host's cache, for reads that may be answered stale (`CallOptions.stale`, P079). */
52
+ readonly cached?: DataCache;
42
53
  /** Whether the embedding page has user activation now; undefined where it can't tell. */
43
54
  readonly userActivation?: () => boolean | undefined;
44
55
  readonly onEvent: (event: BridgeEvent) => void;
@@ -72,6 +83,12 @@ export function linkTarget(value: unknown): string | null {
72
83
  return url.href;
73
84
  }
74
85
 
86
+ /** A resource's URI, as `resources/read` and `resources/subscribe` carry it. */
87
+ function resourceUri(args: unknown): { uri: string } | null {
88
+ const uri = isRecord(args) ? args.uri : undefined;
89
+ return typeof uri === "string" && uri !== "" && uri.length <= MAX_URL ? { uri } : null;
90
+ }
91
+
75
92
  type Validator<N extends CapabilityName> = (
76
93
  args: unknown,
77
94
  config: PortholeConfig,
@@ -108,10 +125,8 @@ const VALIDATORS: { readonly [N in CapabilityName]: Validator<N> } = {
108
125
  const given = args.arguments ?? {};
109
126
  return isRecord(given) ? { name: args.name, arguments: given } : null;
110
127
  },
111
- readData: (args) => {
112
- const uri = isRecord(args) ? args.uri : undefined;
113
- return typeof uri === "string" && uri !== "" && uri.length <= MAX_URL ? { uri } : null;
114
- },
128
+ readData: (args) => resourceUri(args),
129
+ subscribeData: (args) => resourceUri(args),
115
130
  setModelContext: (args) => {
116
131
  if (!isRecord(args)) {
117
132
  return null;
@@ -157,6 +172,26 @@ const VALIDATORS: { readonly [N in CapabilityName]: Validator<N> } = {
157
172
  },
158
173
  };
159
174
 
175
+ /**
176
+ * The host's `consent`, asked once (P079): the first call asks, every later one gets that answer,
177
+ * for as long as the returned function is kept (`createHost` keeps one per display). A consent
178
+ * function that fails is a no for that call, and is asked again at the next.
179
+ */
180
+ export function onceConsent(consent: Consent): Consent {
181
+ let answer: Promise<boolean> | null = null;
182
+ return (request) =>
183
+ (answer ??= Promise.resolve()
184
+ .then(() => consent(request))
185
+ .then(
186
+ // Only a real yes: anything else a host's function gives is a no (fail closed).
187
+ (allowed: unknown) => allowed === true,
188
+ () => {
189
+ answer = null;
190
+ return false;
191
+ },
192
+ ));
193
+ }
194
+
160
195
  export function createBridge(options: BridgeOptions): HostFunctionBridge {
161
196
  const { config, display, handlers, onEvent } = options;
162
197
  const now = options.now ?? (() => Date.now());
@@ -191,7 +226,7 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
191
226
  async call<N extends CapabilityName>(
192
227
  capability: N,
193
228
  raw: unknown,
194
- callOptions?: { readonly userActivated?: boolean },
229
+ callOptions?: CallOptions,
195
230
  ): Promise<CallOutcome<CapabilityResults[N]>> {
196
231
  type Result = CapabilityResults[N];
197
232
  if (config.capabilities[capability] === undefined) {
@@ -217,10 +252,30 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
217
252
  return refuse<Result>(capability, "no-user-activation");
218
253
  }
219
254
  }
255
+ if (gates.includes("consent")) {
256
+ if (options.consent === undefined) {
257
+ return refuse<Result>(capability, "no-consent");
258
+ }
259
+ let allowed = false;
260
+ try {
261
+ const answer: unknown = await options.consent({
262
+ capability,
263
+ args,
264
+ display,
265
+ } as ConfirmRequest);
266
+ allowed = answer === true;
267
+ } catch {
268
+ allowed = false;
269
+ }
270
+ if (!allowed) {
271
+ return refuse<Result>(capability, "denied");
272
+ }
273
+ }
220
274
  // The effect, run once: when the person's "yes" calls `proceed` (inside its own click, so an
221
275
  // effect that needs a gesture gets one), or after `confirm` resolves accepted.
222
276
  let effect: Promise<CallOutcome<Result>> | null = null;
223
- const run = (): Promise<CallOutcome<Result>> => (effect ??= perform(capability, args));
277
+ const run = (): Promise<CallOutcome<Result>> =>
278
+ (effect ??= perform(capability, args, callOptions));
224
279
  if (confirms) {
225
280
  if (options.confirm === undefined) {
226
281
  return refuse<Result>(capability, "no-confirm");
@@ -255,6 +310,7 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
255
310
  async function perform<N extends CapabilityName>(
256
311
  capability: N,
257
312
  args: CapabilityArgs[N],
313
+ callOptions: CallOptions | undefined,
258
314
  ): Promise<CallOutcome<CapabilityResults[N]>> {
259
315
  type Result = CapabilityResults[N];
260
316
  {
@@ -273,13 +329,29 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
273
329
  if (handler === undefined) {
274
330
  return refuse<Result>(capability, "not-declared");
275
331
  }
332
+ const context = { displayId: display.id, title: display.title, capability };
333
+ // A read the content subscribes to may be answered from the host's cache, marked stale; the
334
+ // fresh one follows as an update (the adapter asks for it). A cache that fails is no answer.
335
+ if (capability === "readData" && callOptions?.stale === true && options.cached) {
336
+ try {
337
+ const cached = await options.cached(args as CapabilityArgs["readData"], context);
338
+ if (cached !== undefined) {
339
+ return { ok: true, value: cached as Result, stale: true };
340
+ }
341
+ } catch {
342
+ // Read it fresh instead.
343
+ }
344
+ }
345
+ const subscription = callOptions?.subscription;
346
+ if (capability === "subscribeData" && subscription === undefined) {
347
+ return refuse<Result>(capability, "invalid");
348
+ }
276
349
  try {
277
- const value = await handler(args, {
278
- displayId: display.id,
279
- title: display.title,
280
- capability,
281
- });
282
- return { ok: true, value };
350
+ const value = await (handler as (args: unknown, context: unknown) => unknown)(
351
+ args,
352
+ capability === "subscribeData" ? { ...context, ...subscription } : context,
353
+ );
354
+ return { ok: true, value: value as Result };
283
355
  } catch (error) {
284
356
  return refuse<Result>(
285
357
  capability,
@@ -23,12 +23,40 @@ export interface CallContext {
23
23
 
24
24
  export type CapabilityHandler<N extends CapabilityName> = (
25
25
  args: CapabilityArgs[N],
26
- context: CallContext,
26
+ context: N extends "subscribeData" ? SubscriptionContext : CallContext,
27
27
  ) => CapabilityResults[N] | Promise<CapabilityResults[N]>;
28
28
 
29
+ /**
30
+ * A subscription's context (`subscribeData`, P079): how the host tells the content its resource
31
+ * changed, and when to stop.
32
+ */
33
+ export interface SubscriptionContext extends CallContext {
34
+ /**
35
+ * The resource changed: the content is told (`notifications/resources/updated`) and reads it
36
+ * again. Pass the new `resources/read` result to answer that read without another call to
37
+ * `readData`.
38
+ */
39
+ readonly changed: (result?: unknown) => void;
40
+ /** Aborted when the content unsubscribes, its frame stops, or the display is destroyed. */
41
+ readonly signal: AbortSignal;
42
+ }
43
+
29
44
  /** The host's handlers: one for each declared capability served by a handler. */
30
45
  export type CapabilityHandlers = { readonly [N in HandledCapability]?: CapabilityHandler<N> };
31
46
 
47
+ /**
48
+ * Asked once per display before its first call of a `consent`-gated capability (P079): may this
49
+ * content have them (read the viewer's data)? The request is that first call. A host remembers
50
+ * the answer where it likes (per viewer, per widget); Porthole keeps it for the display's life.
51
+ */
52
+ export type Consent = (request: ConfirmRequest) => boolean | Promise<boolean>;
53
+
54
+ /**
55
+ * What the host last had for a resource (P079), answered at once, marked stale, to a read of a
56
+ * resource the content subscribes to; the fresh result follows as an update. Undefined: none.
57
+ */
58
+ export type DataCache = (args: CapabilityArgs["readData"], context: CallContext) => unknown;
59
+
32
60
  /**
33
61
  * The display a confirmation is for, as the host named it: its id and title, and the instance the
34
62
  * host gave it, served or opaque (P076, P077), so a host can word its dialog from its own records.
@@ -87,21 +115,35 @@ export type Refusal =
87
115
  | "redirected"
88
116
  /** The display was muted after too many declines (until it runs again). */
89
117
  | "muted"
118
+ /** It is `consent`-gated and there is no `consent` function. */
119
+ | "no-consent"
120
+ /** The host's `consent` said no (for this display's life). */
121
+ | "denied"
90
122
  | "rate-limited"
91
123
  /** The host's handler threw or rejected. */
92
124
  | "failed";
93
125
 
94
126
  export type CallOutcome<T> =
95
- | { readonly ok: true; readonly value: T }
127
+ /** `stale`: a `readData` answered from the host's cache (`DataCache`). */
128
+ | { readonly ok: true; readonly value: T; readonly stale?: true }
96
129
  | { readonly ok: false; readonly refusal: Refusal; readonly message?: string };
97
130
 
131
+ /** What an adapter adds to a call, beyond what the content sent. */
132
+ export interface CallOptions {
133
+ readonly userActivated?: boolean;
134
+ /** `subscribeData`: the subscription's channel back and its end (`SubscriptionContext`). */
135
+ readonly subscription?: Pick<SubscriptionContext, "changed" | "signal">;
136
+ /** `readData`: the host's cache may answer, marked stale (the content subscribes to it). */
137
+ readonly stale?: boolean;
138
+ }
139
+
98
140
  /** What adapters call; one per display. */
99
141
  export interface HostFunctionBridge {
100
142
  /** Validates `args` for `capability`, applies its gates, then runs the host's handler. */
101
143
  call<N extends CapabilityName>(
102
144
  capability: N,
103
145
  args: unknown,
104
- options?: { readonly userActivated?: boolean },
146
+ options?: CallOptions,
105
147
  ): Promise<CallOutcome<CapabilityResults[N]>>;
106
148
  declared(capability: CapabilityName): boolean;
107
149
  }
package/src/check/lint.ts CHANGED
@@ -3,6 +3,7 @@ import {
3
3
  declaredCapabilities,
4
4
  egressOrigins,
5
5
  type EgressKind,
6
+ librarySources,
6
7
  } from "../compile/policy.ts";
7
8
  import type { PortholeConfig } from "../config/schema.ts";
8
9
  import { sizeWords } from "../guide/limits.ts";
@@ -217,7 +218,7 @@ export function lintContent(config: PortholeConfig, content: string): Finding[]
217
218
  add(
218
219
  "egress",
219
220
  "warning",
220
- `Nothing loads from ${origin} here (${kind}): ${kind === "script" || kind === "style" ? "write it inline, or use a library from an allowed CDN" : kind === "connect" ? "the content can't call it; work from data in the content" : "put it inline as a data: URL"}.`,
221
+ `Nothing loads from ${origin} here (${kind}): ${kind === "script" && librarySources(config).length > 0 ? "write it inline, or use one of the libraries served here (the manual's Libraries)" : kind === "script" || kind === "style" ? "write it inline, or use a library from an allowed CDN" : kind === "connect" && config.capabilities.readData !== undefined ? "the content can't call it; read the app's data with readData" : kind === "connect" ? "the content can't call it; work from data in the content" : "put it inline as a data: URL"}.`,
221
222
  match.index,
222
223
  );
223
224
  }
package/src/check/page.ts CHANGED
@@ -35,6 +35,9 @@ const DECLINED: { readonly [N in HandledCapability]: () => unknown } = {
35
35
  readData: () => {
36
36
  throw new Error("The host declined the read");
37
37
  },
38
+ subscribeData: () => {
39
+ throw new Error("The host declined the subscription");
40
+ },
38
41
  };
39
42
 
40
43
  /**
@@ -166,6 +169,8 @@ const check = {
166
169
  handlers: declining(Object.keys(spec.config.capabilities), calls),
167
170
  platform: NOBODY,
168
171
  confirm: () => Promise.resolve("declined"),
172
+ // A viewer who doesn't allow a live widget their data (P079): its calls are refused.
173
+ consent: () => false,
169
174
  // A served config's instance, issued by the check's own server on this page's origin.
170
175
  locator: {
171
176
  locate: async (instance) =>
@@ -1,5 +1,6 @@
1
1
  import { CAPABILITIES, type CapabilityName, type Gate } from "../config/capabilities.ts";
2
2
  import type { PortholeConfig } from "../config/schema.ts";
3
+ import { LIBRARY_PATH } from "../libraries/libraries.ts";
3
4
 
4
5
  /**
5
6
  * The frame's policies, derived from the config: its CSP (in the shell's `<meta>` for opaque
@@ -46,6 +47,16 @@ export function allEgressOrigins(config: PortholeConfig): string[] {
46
47
  return unique(kinds.flatMap((kind) => egressOrigins(config, kind)));
47
48
  }
48
49
 
50
+ /**
51
+ * Where Porthole's vendored libraries load from (`egress.libraries`, P079): their path on the
52
+ * content origins, so the frame's own, path-limited (nothing else served there runs as a script).
53
+ */
54
+ export function librarySources(config: PortholeConfig): string[] {
55
+ return config.egress.libraries === true && config.isolation === "domain"
56
+ ? config.contentOrigins.map((origin) => `${origin}${LIBRARY_PATH}`)
57
+ : [];
58
+ }
59
+
49
60
  const list = (sources: readonly string[]): string[] =>
50
61
  sources.length === 0 ? ["'none'"] : [...sources];
51
62
 
@@ -65,7 +76,14 @@ export function frameCspDirectives(config: PortholeConfig): CspDirective[] {
65
76
  const https = (kind: "img" | "media" | "font") => (anyHttps(config, kind) ? ["https:"] : []);
66
77
  return [
67
78
  ["default-src", "'none'"],
68
- ["script-src", "'unsafe-inline'", "'unsafe-eval'", "blob:", ...origins("script")],
79
+ [
80
+ "script-src",
81
+ "'unsafe-inline'",
82
+ "'unsafe-eval'",
83
+ "blob:",
84
+ ...origins("script"),
85
+ ...librarySources(config),
86
+ ],
69
87
  ["style-src", "'unsafe-inline'", ...origins("style")],
70
88
  ["font-src", "data:", ...https("font"), ...origins("font")],
71
89
  ["img-src", "data:", "blob:", ...https("img"), ...origins("img")],
@@ -16,6 +16,7 @@ export const CAPABILITY_NAMES = [
16
16
  "downloadFile",
17
17
  "callTool",
18
18
  "readData",
19
+ "subscribeData",
19
20
  "setModelContext",
20
21
  "reportError",
21
22
  "resize",
@@ -34,10 +35,15 @@ export type CapabilityName = (typeof CAPABILITY_NAMES)[number];
34
35
  * - `confirm`: the host's `confirm` function shows a person the call's whole effect, and the call
35
36
  * goes only if they accept. No `confirm` function means the call is refused (fail closed).
36
37
  * - `rateLimit`: at most `perMinute` calls per display per minute; the rest are refused.
38
+ * - `consent` (P079): the host's `consent` function is asked once per display, before the first
39
+ * call of any of its consent-gated capabilities, whether this content may have them (a viewer
40
+ * allowing a widget to read their data). A no refuses every such call for the display's life;
41
+ * no `consent` function refuses them all (fail closed).
37
42
  */
38
43
  export type Gate =
39
44
  | "user-activation"
40
45
  | "confirm"
46
+ | "consent"
41
47
  | { readonly rateLimit: { readonly perMinute: number } };
42
48
 
43
49
  export interface CapabilitySpec {
@@ -86,8 +92,20 @@ export const CAPABILITIES = {
86
92
  readData: {
87
93
  defaultGates: [rate(120)],
88
94
  served: "handler",
95
+ global: "readData",
89
96
  request: { method: "resources/read", sdk: "app.readServerResource" },
90
97
  },
98
+ /**
99
+ * Live data (P079): content subscribes to a resource and the host tells it when it changed
100
+ * (MCP `resources/subscribe`, `resources/unsubscribe`, `notifications/resources/updated`);
101
+ * it then reads it again (`readData`, which it needs). The App SDK has no method for it.
102
+ */
103
+ subscribeData: {
104
+ defaultGates: [rate(60)],
105
+ served: "handler",
106
+ global: "subscribeData",
107
+ request: { method: "resources/subscribe" },
108
+ },
91
109
  setModelContext: {
92
110
  defaultGates: [rate(30)],
93
111
  served: "handler",
@@ -124,6 +142,7 @@ export interface CapabilityArgs {
124
142
  readonly arguments: Readonly<Record<string, unknown>>;
125
143
  };
126
144
  readonly readData: { readonly uri: string };
145
+ readonly subscribeData: { readonly uri: string };
127
146
  readonly setModelContext: {
128
147
  readonly content?: readonly unknown[];
129
148
  readonly structuredContent?: Readonly<Record<string, unknown>>;
@@ -144,7 +163,9 @@ export interface CapabilityResults {
144
163
  /** Whether the download started. */
145
164
  readonly downloadFile: boolean;
146
165
  readonly callTool: unknown;
166
+ /** An MCP `resources/read` result (`{ contents }`), as the host answers it. */
147
167
  readonly readData: unknown;
168
+ readonly subscribeData: undefined;
148
169
  readonly setModelContext: undefined;
149
170
  readonly reportError: undefined;
150
171
  readonly resize: undefined;
@@ -67,6 +67,13 @@ export interface EgressConfig {
67
67
  * address and a visit signal reach any site, and data can leave in the URL.
68
68
  */
69
69
  readonly anyHttps?: readonly PassiveKind[];
70
+ /**
71
+ * Porthole's own copies of a few libraries (`VENDORED_LIBRARIES`: Chart.js, D3), served from the
72
+ * frame's own origin under `/__porthole/lib/` (P079): domain isolation only. They open no
73
+ * channel out: the requests reach the content server, which serves fixed files, so a display
74
+ * with no network of its own (`presets.liveWidget`) still draws charts.
75
+ */
76
+ readonly libraries?: boolean;
70
77
  }
71
78
 
72
79
  /** What `EgressConfig.anyHttps` may open: content that runs nothing (P059). */
@@ -258,12 +258,12 @@ function positive(value: unknown, path: string, max = Number.MAX_SAFE_INTEGER):
258
258
  }
259
259
 
260
260
  function gate(value: unknown, path: string): asserts value is Gate {
261
- if (value === "user-activation" || value === "confirm") {
261
+ if (value === "user-activation" || value === "confirm" || value === "consent") {
262
262
  return;
263
263
  }
264
264
  const limit = isObject(value) && isObject(value.rateLimit) ? value.rateLimit : null;
265
265
  if (limit === null || Object.keys(value as object).length !== 1) {
266
- fail(path, 'must be "user-activation", "confirm" or { rateLimit: { perMinute } }');
266
+ fail(path, 'must be "user-activation", "confirm", "consent" or { rateLimit: { perMinute } }');
267
267
  return;
268
268
  }
269
269
  only(limit, ["perMinute"], `${path}.rateLimit`);
@@ -335,7 +335,7 @@ export function validateConfig(input: unknown): PortholeConfig {
335
335
 
336
336
  const egress = object(config.egress, "config.egress");
337
337
  const kinds = ["connect", "script", "style", "img", "font", "media"];
338
- only(egress, [...kinds, "anyHttps"], "config.egress");
338
+ only(egress, [...kinds, "anyHttps", "libraries"], "config.egress");
339
339
  for (const kind of kinds) {
340
340
  sources(egress[kind], `config.egress.${kind}`);
341
341
  }
@@ -356,6 +356,24 @@ export function validateConfig(input: unknown): PortholeConfig {
356
356
  }
357
357
  }
358
358
 
359
+ if (egress.libraries !== undefined) {
360
+ if (typeof egress.libraries !== "boolean") {
361
+ fail("config.egress.libraries", "must be true or false");
362
+ }
363
+ if (egress.libraries && config.isolation !== "domain") {
364
+ fail(
365
+ "config.egress.libraries",
366
+ "Porthole's libraries are served from the frame's own origin: domain isolation only",
367
+ );
368
+ }
369
+ }
370
+ if (capabilities.subscribeData !== undefined && capabilities.readData === undefined) {
371
+ fail(
372
+ "config.capabilities.subscribeData",
373
+ "needs readData: content reads a resource again when it is told it changed",
374
+ );
375
+ }
376
+
359
377
  const theme = object(config.theme, "config.theme");
360
378
  only(theme, ["variables", "event", "documents"], "config.theme");
361
379
  if (
@@ -84,6 +84,7 @@ function recorder(calls: RecordedCall[]): CapabilityHandlers {
84
84
  downloadFile: record("downloadFile", true),
85
85
  callTool: record("callTool", { content: [] }),
86
86
  readData: record("readData", { contents: [] }),
87
+ subscribeData: record("subscribeData", undefined),
87
88
  setModelContext: record("setModelContext", undefined),
88
89
  copyText: record("copyText", true),
89
90
  };
@@ -22,7 +22,7 @@ import { presets, type PresetOptions, type UrlPresetOptions } from "../presets/p
22
22
 
23
23
  export type DisplayKind =
24
24
  | {
25
- readonly preset: "inlineWidget" | "artifact" | "mcpApp";
25
+ readonly preset: "inlineWidget" | "liveWidget" | "artifact" | "mcpApp";
26
26
  readonly options?: PresetOptions;
27
27
  /** Options added when served on content origins (domain isolation): storage, egress. */
28
28
  readonly served?: Omit<PresetOptions, "isolation" | "contentOrigins">;
@@ -11,8 +11,10 @@ import {
11
11
  declaredCapabilities,
12
12
  effectiveGates,
13
13
  egressOrigins,
14
+ librarySources,
14
15
  type EgressKind,
15
16
  } from "../compile/policy.ts";
17
+ import { VENDORED_LIBRARIES, libraryPath } from "../libraries/libraries.ts";
16
18
  import { shellPlan } from "../shell/plan.ts";
17
19
  import { themeDefault } from "../theme/variables.ts";
18
20
  import { GUIDE_EXAMPLES } from "./examples.ts";
@@ -103,6 +105,9 @@ const sourcesFor = (config: PortholeConfig, kind: EgressKind): string[] => [
103
105
  ...egressOrigins(config, kind),
104
106
  ];
105
107
 
108
+ /** Whether Porthole's own libraries load in the frame (`egress.libraries`, served, P079). */
109
+ const servesLibraries = (config: PortholeConfig): boolean => librarySources(config).length > 0;
110
+
106
111
  /** What content may load, in prose, from the same origins the CSP lists. */
107
112
  function network(config: PortholeConfig): string {
108
113
  const kinds: EgressKind[] = ["script", "style", "font", "img", "media", "connect"];
@@ -110,7 +115,13 @@ function network(config: PortholeConfig): string {
110
115
  .map((kind) => [kind, sourcesFor(config, kind)] as const)
111
116
  .filter(([, origins]) => origins.length > 0);
112
117
  if (open.length === 0) {
113
- return "Network: none. Nothing loads from outside (no scripts, styles, fonts, images or data from any server) and any fetch fails, so write everything inline: SVG and CSS draw charts well.";
118
+ // A live widget's data comes from the app alone (P079), and its scripts from Porthole's copies.
119
+ const data = declaredCapabilities(config).includes("readData")
120
+ ? " Your data comes only from the app (readData)."
121
+ : "";
122
+ return servesLibraries(config)
123
+ ? `Network: none. Nothing loads from outside (no scripts, styles, fonts, images or data from any server) and any fetch fails, so write everything inline; the only scripts that load are the libraries below, from this frame's own address.${data}`
124
+ : `Network: none. Nothing loads from outside (no scripts, styles, fonts, images or data from any server) and any fetch fails, so write everything inline: SVG and CSS draw charts well.${data}`;
114
125
  }
115
126
  // Origins that serve the same kinds go together: "scripts, styles and data from a, b; fonts from c".
116
127
  const byOrigin = new Map<string, EgressKind[]>();
@@ -168,6 +179,24 @@ function ownCdns(config: PortholeConfig): string[] {
168
179
  return said;
169
180
  }
170
181
 
182
+ /**
183
+ * Porthole's own libraries (`egress.libraries`, P079): a script line for each, at its path on the
184
+ * frame's own origin, the only scripts that load where egress is otherwise closed.
185
+ */
186
+ function ownLibraries(config: PortholeConfig): string[] {
187
+ if (!servesLibraries(config)) {
188
+ return [];
189
+ }
190
+ return [
191
+ "",
192
+ "Libraries, served from this frame's own address (pinned; nothing else loads):",
193
+ ...VENDORED_LIBRARIES.map(
194
+ (library) =>
195
+ `- ${library.title} ${library.version} (${library.use}): <script src="${libraryPath(library)}"></script>, then window.${library.global}.`,
196
+ ),
197
+ ];
198
+ }
199
+
171
200
  function widget(c: Context): string {
172
201
  const { config, noun } = c;
173
202
  const { layout, limits } = config;
@@ -217,6 +246,7 @@ function widget(c: Context): string {
217
246
  ? "\nLibraries: pin an exact version at least two weeks old (chart.js@4.4.1 in its URL), never @latest or a range, so the code can't be swapped under you and draws the same every time."
218
247
  : null,
219
248
  ...ownCdns(config),
249
+ ...ownLibraries(config),
220
250
  "",
221
251
  themeless
222
252
  ? `Colors: these variables hold the app's palette; use them, or colors of your own. Give the ${noun} its own background.`
@@ -297,9 +327,11 @@ function chart(c: Context): string {
297
327
  const sequential = Object.keys(config.theme.variables).filter((name) =>
298
328
  /^--color-chart-seq-\d+$/u.test(name),
299
329
  );
300
- const libraries = loadsScripts(config)
301
- ? `Libraries (Chart.js, ECharts, d3) draw in px too, in a box with a set height (Chart.js responsive: true, maintainAspectRatio: false). They don't read CSS variables: pass in getComputedStyle(document.documentElement).getPropertyValue("${categorical[0] ?? "--color-text-primary"}").trim()${config.theme.documents === "never" ? "" : `, redraw on window "${config.theme.event}"`}, and override their palette and white background.`
302
- : "No chart library loads here: draw the SVG yourself, from a script, as below.";
330
+ const libraries = servesLibraries(config)
331
+ ? `${VENDORED_LIBRARIES.map((library) => library.title).join(" and ")} load from this frame's own address (topic widget, Libraries) and draw in px too, in a box with a set height (Chart.js responsive: true, maintainAspectRatio: false). They don't read CSS variables: pass in getComputedStyle(document.documentElement).getPropertyValue("${categorical[0] ?? "--color-text-primary"}").trim()${config.theme.documents === "never" ? "" : `, redraw on window "${config.theme.event}"`}, and override their palette and white background. Or draw the SVG yourself, from a script, as below.`
332
+ : loadsScripts(config)
333
+ ? `Libraries (Chart.js, ECharts, d3) draw in px too, in a box with a set height (Chart.js responsive: true, maintainAspectRatio: false). They don't read CSS variables: pass in getComputedStyle(document.documentElement).getPropertyValue("${categorical[0] ?? "--color-text-primary"}").trim()${config.theme.documents === "never" ? "" : `, redraw on window "${config.theme.event}"`}, and override their palette and white background.`
334
+ : "No chart library loads here: draw the SVG yourself, from a script, as below.";
303
335
  return lines(
304
336
  `# Charts (a chart is a ${c.noun})`,
305
337
  "",
@@ -348,6 +380,11 @@ function chart(c: Context): string {
348
380
  /** How a capability's gates read to the author: one sentence each. */
349
381
  function gateWords(gates: readonly Gate[], effect: string): string {
350
382
  const sentences: string[] = [];
383
+ if (gates.includes("consent")) {
384
+ sentences.push(
385
+ "The first data call asks the person to allow it; if they don't, every one fails (show that the data isn't allowed, not an error).",
386
+ );
387
+ }
351
388
  if (gates.includes("confirm")) {
352
389
  sentences.push(
353
390
  `The app shows the person ${effect} first, and nothing happens unless they confirm.`,
@@ -378,8 +415,14 @@ const ENTRIES: { readonly [N in CapabilityName]: (c: Context, gates: readonly Ga
378
415
  `- Downloads: the MCP Apps request ui/download-file (with the App SDK, app.downloadFile). ${gateWords(gates, "the file")}`,
379
416
  callTool: (_c, gates) =>
380
417
  `- Tools: the MCP Apps request tools/call (with the App SDK, app.callServerTool). ${gateWords(gates, "the call")}`,
381
- readData: (_c, gates) =>
382
- `- Data: the MCP Apps request resources/read (with the App SDK, app.readServerResource). ${gateWords(gates, "the request")}`,
418
+ readData: (c, gates) =>
419
+ c.global("readData")
420
+ ? `- readData(uri): reads the app's data at uri (a resource the app names), as the person viewing the ${c.noun} may see it, and returns a promise of it: JSON parsed, else text. ${gateWords(gates, "the request")} It rejects when the app refuses or fails: draw the ${c.noun} without that data, saying why.`
421
+ : `- Data: the MCP Apps request resources/read (with the App SDK, app.readServerResource). ${gateWords(gates, "the request")}`,
422
+ subscribeData: (c, gates) =>
423
+ c.global("subscribeData")
424
+ ? `- subscribeData(uri, onData, onError): keeps the ${c.noun} current. It calls onData(value, { stale }) with the data at uri now, and again each time it changes; the first value may be the app's last copy (stale: true), with the current one right after. It returns a function that stops it. onError(error) hears a refusal. ${gateWords(gates, "the request")} Draw from onData every time; don't poll.`
425
+ : `- Live data: the MCP request resources/subscribe with { uri }; the app then sends notifications/resources/updated with { uri } each time it changes: read it again (resources/read). resources/unsubscribe stops it. ${gateWords(gates, "the request")}`,
383
426
  setModelContext: (_c, gates) =>
384
427
  `- Context for the agent: the MCP Apps request ui/update-model-context (with the App SDK, app.updateModelContext). ${gateWords(gates, "it")}`,
385
428
  copyText: (c, gates) =>
@@ -462,7 +505,9 @@ export function generateToolDescription(config: PortholeConfig): string {
462
505
  passive.length === 0 ? "" : `${kindsInWords(passive)} from ${ANY_HTTPS_SITE}`;
463
506
  const net =
464
507
  origins.length === 0 && fromAnywhere === ""
465
- ? "with no network (nothing loads from outside)"
508
+ ? servesLibraries(config)
509
+ ? `with no network (nothing loads from outside; ${VENDORED_LIBRARIES.map((library) => library.title).join(" and ")} load from the app)`
510
+ : "with no network (nothing loads from outside)"
466
511
  : origins.length === 0
467
512
  ? `loading only ${fromAnywhere}`
468
513
  : `loading only from ${origins.join(", ")}${fromAnywhere === "" ? "" : `, and ${fromAnywhere}`}`;
@@ -477,6 +522,11 @@ export function generateToolDescription(config: PortholeConfig): string {
477
522
  if (spec.global === "openLink") {
478
523
  return ["openLink(url) asks the person to open a link."];
479
524
  }
525
+ if (spec.global === "readData") {
526
+ return [
527
+ `readData(uri)${c.global("subscribeData") ? " and subscribeData(uri, onData)" : ""} read the app's data, as the person viewing it may see it.`,
528
+ ];
529
+ }
480
530
  return [];
481
531
  });
482
532
  const read =
@@ -5,7 +5,7 @@ import {
5
5
  type AnnotationReport,
6
6
  } from "../annotate/types.ts";
7
7
  import { annotateMode, checkMarks, parseReport } from "../annotate/validate.ts";
8
- import { createBridge, type BridgeEvent } from "../bridge/bridge.ts";
8
+ import { createBridge, onceConsent, type BridgeEvent } from "../bridge/bridge.ts";
9
9
  import type { HostFunctionBridge } from "../bridge/types.ts";
10
10
  import { compile } from "../compile/compile.ts";
11
11
  import { declaredCapabilities } from "../compile/policy.ts";
@@ -117,6 +117,8 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
117
117
  let destroyed = false;
118
118
  let restarts = 0;
119
119
  let generation = 0;
120
+ // The viewer's answer for this display (P079): asked once, kept across its frames.
121
+ const consent = options.consent === undefined ? undefined : onceConsent(options.consent);
120
122
  let abort: AbortController | null = null;
121
123
  let outcomeWatch: OutcomeWatch | null = null;
122
124
  let themeFrame: number | null = null;
@@ -360,6 +362,8 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
360
362
  },
361
363
  handlers,
362
364
  ...(options.confirm === undefined ? {} : { confirm: options.confirm }),
365
+ ...(consent === undefined ? {} : { consent }),
366
+ ...(options.cached === undefined ? {} : { cached: options.cached }),
363
367
  userActivation: () => created.userActivation(),
364
368
  onEvent: onBridge,
365
369
  });