@botiverse/porthole 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +3 -1
  2. package/dist/bridge/bridge.d.ts +24 -2
  3. package/dist/bridge/bridge.js +102 -17
  4. package/dist/bridge/navigation.d.ts +11 -0
  5. package/dist/bridge/navigation.js +30 -0
  6. package/dist/bridge/refusal.d.ts +53 -0
  7. package/dist/bridge/refusal.js +121 -0
  8. package/dist/bridge/types.d.ts +51 -6
  9. package/dist/check/lint.js +2 -2
  10. package/dist/check/page-source.js +1 -1
  11. package/dist/check/page.js +10 -0
  12. package/dist/compile/policy.d.ts +5 -0
  13. package/dist/compile/policy.js +18 -1
  14. package/dist/config/capabilities.d.ts +30 -2
  15. package/dist/config/capabilities.js +13 -0
  16. package/dist/config/schema.d.ts +7 -0
  17. package/dist/config/validate.js +14 -3
  18. package/dist/conformance/harness/page.js +1 -0
  19. package/dist/conformance/harness-source.js +1 -1
  20. package/dist/displays/displays.d.ts +1 -1
  21. package/dist/guide/guide.js +58 -8
  22. package/dist/host/create-host.js +18 -3
  23. package/dist/host/types.d.ts +25 -1
  24. package/dist/index.d.ts +5 -3
  25. package/dist/index.js +4 -1
  26. package/dist/libraries/files.generated.d.ts +1 -0
  27. package/dist/libraries/files.generated.js +8 -0
  28. package/dist/libraries/libraries.d.ts +36 -0
  29. package/dist/libraries/libraries.js +40 -0
  30. package/dist/mcp/adapter.js +49 -5
  31. package/dist/presets/presets.d.ts +15 -0
  32. package/dist/presets/presets.js +27 -2
  33. package/dist/protocol/live-data.d.ts +27 -0
  34. package/dist/protocol/live-data.js +98 -0
  35. package/dist/protocol/mcp-apps.d.ts +15 -0
  36. package/dist/protocol/mcp-apps.js +17 -0
  37. package/dist/protocol/shell-adapter.js +49 -4
  38. package/dist/react/dialog.js +2 -0
  39. package/dist/react/frame.d.ts +30 -1
  40. package/dist/react/frame.js +63 -1
  41. package/dist/server/libraries.d.ts +7 -0
  42. package/dist/server/libraries.js +27 -0
  43. package/dist/server/server.js +2 -1
  44. package/dist/shell/runtime.d.ts +5 -1
  45. package/dist/shell/runtime.js +196 -6
  46. package/docs/ADOPTING.md +89 -3
  47. package/docs/DECISIONS.md +221 -0
  48. package/docs/DESIGN.md +28 -10
  49. package/package.json +3 -1
  50. package/src/bridge/bridge.ts +136 -16
  51. package/src/bridge/navigation.ts +34 -0
  52. package/src/bridge/refusal.ts +151 -0
  53. package/src/bridge/types.ts +57 -4
  54. package/src/check/lint.ts +2 -1
  55. package/src/check/page.ts +12 -0
  56. package/src/compile/policy.ts +19 -1
  57. package/src/config/capabilities.ts +26 -1
  58. package/src/config/schema.ts +7 -0
  59. package/src/config/validate.ts +21 -3
  60. package/src/conformance/harness/page.ts +1 -0
  61. package/src/displays/displays.ts +1 -1
  62. package/src/guide/guide.ts +71 -7
  63. package/src/host/create-host.ts +19 -3
  64. package/src/host/types.ts +23 -1
  65. package/src/index.ts +22 -0
  66. package/src/libraries/files.generated.ts +8 -0
  67. package/src/libraries/libraries.ts +64 -0
  68. package/src/mcp/adapter.ts +63 -5
  69. package/src/presets/presets.ts +46 -3
  70. package/src/protocol/live-data.ts +138 -0
  71. package/src/protocol/mcp-apps.ts +19 -0
  72. package/src/protocol/shell-adapter.ts +50 -5
  73. package/src/react/dialog.tsx +2 -0
  74. package/src/react/frame.tsx +93 -0
  75. package/src/server/libraries.ts +28 -0
  76. package/src/server/server.ts +2 -1
  77. package/src/shell/runtime.ts +196 -6
@@ -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 with code denied (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.`,
@@ -364,6 +401,20 @@ function gateWords(gates: readonly Gate[], effect: string): string {
364
401
  return sentences.join(" ");
365
402
  }
366
403
 
404
+ /**
405
+ * What a data refusal tells content (P080): the codes and the sentence, for the author to draw. With
406
+ * the shell's globals they are the error's own fields; without, the JSON-RPC error's data.
407
+ */
408
+ function refusalWords(c: Context, global: boolean): string {
409
+ const where = global
410
+ ? "The error's code says why"
411
+ : "A refusal is an error whose data is { code, message }; code says why";
412
+ return `${where}: consent_required (not allowed yet), denied (the person said no), rate_limited, not_allowed (not here: some places show the ${c.noun} without data) or failed; ${global ? "its" : ""} message is a sentence for the person. Draw the ${c.noun} without that data, with that sentence where it would be; don't retry in a loop.`.replace(
413
+ / {2,}/gu,
414
+ " ",
415
+ );
416
+ }
417
+
367
418
  const ENTRIES: { readonly [N in CapabilityName]: (c: Context, gates: readonly Gate[]) => string } =
368
419
  {
369
420
  sendPrompt: (c, gates) =>
@@ -378,8 +429,14 @@ const ENTRIES: { readonly [N in CapabilityName]: (c: Context, gates: readonly Ga
378
429
  `- Downloads: the MCP Apps request ui/download-file (with the App SDK, app.downloadFile). ${gateWords(gates, "the file")}`,
379
430
  callTool: (_c, gates) =>
380
431
  `- 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")}`,
432
+ readData: (c, gates) =>
433
+ c.global("readData")
434
+ ? `- 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. ${refusalWords(c, true)}`
435
+ : `- Data: the MCP Apps request resources/read (with the App SDK, app.readServerResource). ${gateWords(gates, "the request")} ${refusalWords(c, false)}`,
436
+ subscribeData: (c, gates) =>
437
+ c.global("subscribeData")
438
+ ? `- 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, with the same code and message as readData's. ${gateWords(gates, "the request")} Draw from onData every time; don't poll.`
439
+ : `- 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
440
  setModelContext: (_c, gates) =>
384
441
  `- Context for the agent: the MCP Apps request ui/update-model-context (with the App SDK, app.updateModelContext). ${gateWords(gates, "it")}`,
385
442
  copyText: (c, gates) =>
@@ -462,7 +519,9 @@ export function generateToolDescription(config: PortholeConfig): string {
462
519
  passive.length === 0 ? "" : `${kindsInWords(passive)} from ${ANY_HTTPS_SITE}`;
463
520
  const net =
464
521
  origins.length === 0 && fromAnywhere === ""
465
- ? "with no network (nothing loads from outside)"
522
+ ? servesLibraries(config)
523
+ ? `with no network (nothing loads from outside; ${VENDORED_LIBRARIES.map((library) => library.title).join(" and ")} load from the app)`
524
+ : "with no network (nothing loads from outside)"
466
525
  : origins.length === 0
467
526
  ? `loading only ${fromAnywhere}`
468
527
  : `loading only from ${origins.join(", ")}${fromAnywhere === "" ? "" : `, and ${fromAnywhere}`}`;
@@ -477,6 +536,11 @@ export function generateToolDescription(config: PortholeConfig): string {
477
536
  if (spec.global === "openLink") {
478
537
  return ["openLink(url) asks the person to open a link."];
479
538
  }
539
+ if (spec.global === "readData") {
540
+ return [
541
+ `readData(uri)${c.global("subscribeData") ? " and subscribeData(uri, onData)" : ""} read the app's data, as the person viewing it may see it.`,
542
+ ];
543
+ }
480
544
  return [];
481
545
  });
482
546
  const read =
@@ -5,10 +5,11 @@ 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
- import { declaredCapabilities } from "../compile/policy.ts";
11
+ import { declaredCapabilities, effectiveGates } from "../compile/policy.ts";
12
+ import { isRefused } from "../bridge/refusal.ts";
12
13
  import { capabilitySpec } from "../config/capabilities.ts";
13
14
  import type { ColorScheme, PortholeConfig } from "../config/schema.ts";
14
15
  import { locateServed } from "./locate.ts";
@@ -79,10 +80,14 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
79
80
  compiled,
80
81
  mount(container: HTMLElement, mount: MountOptions): DisplayHandle<C> {
81
82
  const handlers = { ...options.handlers, ...mount.handlers };
83
+ // A host whose consent is a Refused refuses every consent-gated call before its handler:
84
+ // those need none (P080).
85
+ const refusesAll = isRefused(options.consent);
82
86
  const missing = declaredCapabilities(config).filter(
83
87
  (name) =>
84
88
  capabilitySpec(name).served === "handler" &&
85
- (handlers as Record<string, unknown>)[name] === undefined,
89
+ (handlers as Record<string, unknown>)[name] === undefined &&
90
+ !(refusesAll && effectiveGates(config, name).includes("consent")),
86
91
  );
87
92
  if (missing.length > 0) {
88
93
  throw new TypeError(`No handler for the declared capabilities: ${missing.join(", ")}`);
@@ -117,6 +122,12 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
117
122
  let destroyed = false;
118
123
  let restarts = 0;
119
124
  let generation = 0;
125
+ // The viewer's answer for this display (P079): asked once, kept across its frames; or the
126
+ // host's refusal of them all (P080).
127
+ const consent =
128
+ options.consent === undefined || isRefused(options.consent)
129
+ ? options.consent
130
+ : onceConsent(options.consent);
120
131
  let abort: AbortController | null = null;
121
132
  let outcomeWatch: OutcomeWatch | null = null;
122
133
  let themeFrame: number | null = null;
@@ -289,6 +300,9 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
289
300
  });
290
301
  return;
291
302
  }
303
+ case "navigationBlocked":
304
+ emit("navigationBlocked", { url: event.url });
305
+ return;
292
306
  case "error":
293
307
  contentError(event.message);
294
308
  return;
@@ -360,6 +374,8 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
360
374
  },
361
375
  handlers,
362
376
  ...(options.confirm === undefined ? {} : { confirm: options.confirm }),
377
+ ...(consent === undefined ? {} : { consent }),
378
+ ...(options.cached === undefined ? {} : { cached: options.cached }),
363
379
  userActivation: () => created.userActivation(),
364
380
  onEvent: onBridge,
365
381
  });
package/src/host/types.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { AnnotateMode, AnnotationMark, AnnotationReport } from "../annotate/types.ts";
2
- import type { Confirm, CapabilityHandlers, Refusal } from "../bridge/types.ts";
2
+ import type { Refused } from "../bridge/refusal.ts";
3
+ import type { Confirm, CapabilityHandlers, Consent, DataCache, Refusal } from "../bridge/types.ts";
3
4
  import type { CompiledConfig } from "../compile/compile.ts";
4
5
  import type { CapabilityName } from "../config/capabilities.ts";
5
6
  import type { ColorScheme } from "../config/schema.ts";
@@ -19,6 +20,19 @@ export interface HostOptions<C extends AdapterConnection = ShellConnection> {
19
20
  readonly handlers?: CapabilityHandlers;
20
21
  /** Who confirms `confirm`-gated calls. Absent: those calls are refused. */
21
22
  readonly confirm?: Confirm;
23
+ /**
24
+ * Whether a display may make its `consent`-gated calls (read the viewer's data, P079): asked
25
+ * once per display, before the first, and kept for the display's life (its reloads too).
26
+ * Absent: those calls are refused. A `Refused` instead of a function refuses every one with its
27
+ * reason, asking nothing, and those capabilities need no handler (a page where live data must
28
+ * not run, P080).
29
+ */
30
+ readonly consent?: Consent | Refused;
31
+ /**
32
+ * What the host last had for a resource (P079): a read of one the content subscribes to is
33
+ * answered with it at once, marked stale, then with the handler's fresh result.
34
+ */
35
+ readonly cached?: DataCache;
22
36
  /**
23
37
  * The host's live values for the config's theme variables, for `scheme` (read from its own
24
38
  * design tokens). A name it leaves out, or answers empty, gets the config's default.
@@ -143,6 +157,14 @@ export interface DisplayEvents {
143
157
  readonly error: { readonly message: string; readonly source: "content" | "host" };
144
158
  /** The content navigated its frame away; the frame was started again from its content. */
145
159
  readonly navigated: undefined;
160
+ /**
161
+ * The shell stopped the content navigating its frame to `url` (P079, P080): the address whole,
162
+ * as the content gave it (its word: untrusted, may carry data in its query). Only where the
163
+ * config declares `reportError` (it counts as one of the run's reports), and only in frames with
164
+ * an origin of their own (served): an opaque frame's navigations get no events. A
165
+ * `contentError` follows, naming the address without its query or fragment.
166
+ */
167
+ readonly navigationBlocked: { readonly url: string };
146
168
  /** A call didn't run. */
147
169
  readonly refused: { readonly capability: CapabilityName; readonly refusal: Refusal };
148
170
  /** Too many declines: the display stops asking until it runs again. */
package/src/index.ts CHANGED
@@ -55,9 +55,17 @@ export {
55
55
  LIBRARY_CDNS,
56
56
  presets,
57
57
  type PresetName,
58
+ type LiveWidgetOptions,
58
59
  type PresetOptions,
59
60
  type UrlPresetOptions,
60
61
  } from "./presets/presets.ts";
62
+ export {
63
+ LIBRARY_PATH,
64
+ VENDORED_LIBRARIES,
65
+ libraryPath,
66
+ licensePath,
67
+ type VendoredLibrary,
68
+ } from "./libraries/libraries.ts";
61
69
 
62
70
  // The compiler.
63
71
  export { compile, type CompiledConfig } from "./compile/compile.ts";
@@ -114,11 +122,22 @@ export {
114
122
  MCP_APPS_METHODS,
115
123
  MCP_APPS_PROTOCOL_VERSION,
116
124
  MCP_APPS_STYLE_VARIABLES,
125
+ NAVIGATION_BLOCKED_METHOD,
117
126
  PORTHOLE_STYLES,
127
+ STALE_META,
118
128
  type HostContext,
119
129
  } from "./protocol/mcp-apps.ts";
130
+ // Why a call was refused, as content is told it, and the host's own refusals (P080).
131
+ export {
132
+ REFUSAL_CODES,
133
+ Refused,
134
+ isRefused,
135
+ type RefusalCode,
136
+ type RefusalReason,
137
+ } from "./bridge/refusal.ts";
120
138
  export type {
121
139
  CallContext,
140
+ CallOptions,
122
141
  CallOutcome,
123
142
  CapabilityHandler,
124
143
  CapabilityHandlers,
@@ -126,9 +145,12 @@ export type {
126
145
  ConfirmAnswer,
127
146
  ConfirmDisplay,
128
147
  ConfirmRequest,
148
+ Consent,
149
+ DataCache,
129
150
  Proceed,
130
151
  HostFunctionBridge,
131
152
  Refusal,
153
+ SubscriptionContext,
132
154
  } from "./bridge/types.ts";
133
155
  export { createHost } from "./host/create-host.ts";
134
156
  // The client half of the host kit, and the display registry (P072).