@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
package/README.md CHANGED
@@ -88,4 +88,6 @@ width, light and dark, before anyone sees it, and tells the agent what broke in
88
88
 
89
89
  `npx porthole secret` makes a secret; `npx porthole d1-schema` prints the D1 migration.
90
90
 
91
- Apache-2.0.
91
+ Apache-2.0. `/server` also serves copies of [Chart.js](https://www.chartjs.org) 4.5.1 (MIT) and
92
+ [D3](https://d3js.org) 7.9.0 (ISC) to live widgets (P079), each with its license beside it
93
+ (`/__porthole/lib/<name>@<version>/`), from `src/libraries/files.generated.ts`.
@@ -1,11 +1,12 @@
1
1
  import { type CapabilityName } from "../config/capabilities.ts";
2
2
  import type { AnnotationReport } from "../annotate/types.ts";
3
3
  import type { PortholeConfig } from "../config/schema.ts";
4
- import type { CapabilityHandlers, Confirm, ConfirmDisplay, HostFunctionBridge, Refusal } from "./types.ts";
4
+ import type { CapabilityHandlers, Confirm, ConfirmDisplay, Consent, DataCache, HostFunctionBridge, Refusal } from "./types.ts";
5
5
  /**
6
6
  * The host-function bridge: every capability call from a frame passes here, and nowhere else
7
7
  * reaches a host handler. In order: declared → arguments well formed → not muted → within its
8
- * rate → a user gesture, if gated so → a person's confirmation, if gated so → the handler.
8
+ * rate → a user gesture, if gated so → the viewer's consent, if gated so → a person's
9
+ * confirmation, if gated so → the handler (or, for a stale-allowed read, the host's cache).
9
10
  */
10
11
  export type BridgeEvent = {
11
12
  readonly type: "resize";
@@ -29,6 +30,13 @@ export interface BridgeOptions {
29
30
  readonly display: ConfirmDisplay;
30
31
  readonly handlers: CapabilityHandlers;
31
32
  readonly confirm?: Confirm;
33
+ /**
34
+ * Asked before a `consent`-gated call (P079). The host's, made to ask once per display by the
35
+ * caller (`createHost` keeps the answer across the display's frames).
36
+ */
37
+ readonly consent?: Consent;
38
+ /** The host's cache, for reads that may be answered stale (`CallOptions.stale`, P079). */
39
+ readonly cached?: DataCache;
32
40
  /** Whether the embedding page has user activation now; undefined where it can't tell. */
33
41
  readonly userActivation?: () => boolean | undefined;
34
42
  readonly onEvent: (event: BridgeEvent) => void;
@@ -37,4 +45,10 @@ export interface BridgeOptions {
37
45
  }
38
46
  /** An http(s) URL without credentials in it (`https://bank.example@evil.example` reads as a lie). */
39
47
  export declare function linkTarget(value: unknown): string | null;
48
+ /**
49
+ * The host's `consent`, asked once (P079): the first call asks, every later one gets that answer,
50
+ * for as long as the returned function is kept (`createHost` keeps one per display). A consent
51
+ * function that fails is a no for that call, and is asked again at the next.
52
+ */
53
+ export declare function onceConsent(consent: Consent): Consent;
40
54
  export declare function createBridge(options: BridgeOptions): HostFunctionBridge;
@@ -22,6 +22,11 @@ export function linkTarget(value) {
22
22
  }
23
23
  return url.href;
24
24
  }
25
+ /** A resource's URI, as `resources/read` and `resources/subscribe` carry it. */
26
+ function resourceUri(args) {
27
+ const uri = isRecord(args) ? args.uri : undefined;
28
+ return typeof uri === "string" && uri !== "" && uri.length <= MAX_URL ? { uri } : null;
29
+ }
25
30
  const VALIDATORS = {
26
31
  sendPrompt: (args, config) => {
27
32
  const text = isRecord(args) ? args.text : undefined;
@@ -51,10 +56,8 @@ const VALIDATORS = {
51
56
  const given = args.arguments ?? {};
52
57
  return isRecord(given) ? { name: args.name, arguments: given } : null;
53
58
  },
54
- readData: (args) => {
55
- const uri = isRecord(args) ? args.uri : undefined;
56
- return typeof uri === "string" && uri !== "" && uri.length <= MAX_URL ? { uri } : null;
57
- },
59
+ readData: (args) => resourceUri(args),
60
+ subscribeData: (args) => resourceUri(args),
58
61
  setModelContext: (args) => {
59
62
  if (!isRecord(args)) {
60
63
  return null;
@@ -95,6 +98,22 @@ const VALIDATORS = {
95
98
  : { height: args.height };
96
99
  },
97
100
  };
101
+ /**
102
+ * The host's `consent`, asked once (P079): the first call asks, every later one gets that answer,
103
+ * for as long as the returned function is kept (`createHost` keeps one per display). A consent
104
+ * function that fails is a no for that call, and is asked again at the next.
105
+ */
106
+ export function onceConsent(consent) {
107
+ let answer = null;
108
+ return (request) => (answer ??= Promise.resolve()
109
+ .then(() => consent(request))
110
+ .then(
111
+ // Only a real yes: anything else a host's function gives is a no (fail closed).
112
+ (allowed) => allowed === true, () => {
113
+ answer = null;
114
+ return false;
115
+ }));
116
+ }
98
117
  export function createBridge(options) {
99
118
  const { config, display, handlers, onEvent } = options;
100
119
  const now = options.now ?? (() => Date.now());
@@ -142,10 +161,30 @@ export function createBridge(options) {
142
161
  return refuse(capability, "no-user-activation");
143
162
  }
144
163
  }
164
+ if (gates.includes("consent")) {
165
+ if (options.consent === undefined) {
166
+ return refuse(capability, "no-consent");
167
+ }
168
+ let allowed = false;
169
+ try {
170
+ const answer = await options.consent({
171
+ capability,
172
+ args,
173
+ display,
174
+ });
175
+ allowed = answer === true;
176
+ }
177
+ catch {
178
+ allowed = false;
179
+ }
180
+ if (!allowed) {
181
+ return refuse(capability, "denied");
182
+ }
183
+ }
145
184
  // The effect, run once: when the person's "yes" calls `proceed` (inside its own click, so an
146
185
  // effect that needs a gesture gets one), or after `confirm` resolves accepted.
147
186
  let effect = null;
148
- const run = () => (effect ??= perform(capability, args));
187
+ const run = () => (effect ??= perform(capability, args, callOptions));
149
188
  if (confirms) {
150
189
  if (options.confirm === undefined) {
151
190
  return refuse(capability, "no-confirm");
@@ -174,7 +213,7 @@ export function createBridge(options) {
174
213
  return run();
175
214
  },
176
215
  };
177
- async function perform(capability, args) {
216
+ async function perform(capability, args, callOptions) {
178
217
  {
179
218
  if (capabilitySpec(capability).served === "event") {
180
219
  if (capability === "resize") {
@@ -193,13 +232,27 @@ export function createBridge(options) {
193
232
  if (handler === undefined) {
194
233
  return refuse(capability, "not-declared");
195
234
  }
235
+ const context = { displayId: display.id, title: display.title, capability };
236
+ // A read the content subscribes to may be answered from the host's cache, marked stale; the
237
+ // fresh one follows as an update (the adapter asks for it). A cache that fails is no answer.
238
+ if (capability === "readData" && callOptions?.stale === true && options.cached) {
239
+ try {
240
+ const cached = await options.cached(args, context);
241
+ if (cached !== undefined) {
242
+ return { ok: true, value: cached, stale: true };
243
+ }
244
+ }
245
+ catch {
246
+ // Read it fresh instead.
247
+ }
248
+ }
249
+ const subscription = callOptions?.subscription;
250
+ if (capability === "subscribeData" && subscription === undefined) {
251
+ return refuse(capability, "invalid");
252
+ }
196
253
  try {
197
- const value = await handler(args, {
198
- displayId: display.id,
199
- title: display.title,
200
- capability,
201
- });
202
- return { ok: true, value };
254
+ const value = await handler(args, capability === "subscribeData" ? { ...context, ...subscription } : context);
255
+ return { ok: true, value: value };
203
256
  }
204
257
  catch (error) {
205
258
  return refuse(capability, "failed", error instanceof Error ? error.message : String(error));
@@ -13,11 +13,36 @@ export interface CallContext {
13
13
  readonly title: string;
14
14
  readonly capability: CapabilityName;
15
15
  }
16
- export type CapabilityHandler<N extends CapabilityName> = (args: CapabilityArgs[N], context: CallContext) => CapabilityResults[N] | Promise<CapabilityResults[N]>;
16
+ export type CapabilityHandler<N extends CapabilityName> = (args: CapabilityArgs[N], context: N extends "subscribeData" ? SubscriptionContext : CallContext) => CapabilityResults[N] | Promise<CapabilityResults[N]>;
17
+ /**
18
+ * A subscription's context (`subscribeData`, P079): how the host tells the content its resource
19
+ * changed, and when to stop.
20
+ */
21
+ export interface SubscriptionContext extends CallContext {
22
+ /**
23
+ * The resource changed: the content is told (`notifications/resources/updated`) and reads it
24
+ * again. Pass the new `resources/read` result to answer that read without another call to
25
+ * `readData`.
26
+ */
27
+ readonly changed: (result?: unknown) => void;
28
+ /** Aborted when the content unsubscribes, its frame stops, or the display is destroyed. */
29
+ readonly signal: AbortSignal;
30
+ }
17
31
  /** The host's handlers: one for each declared capability served by a handler. */
18
32
  export type CapabilityHandlers = {
19
33
  readonly [N in HandledCapability]?: CapabilityHandler<N>;
20
34
  };
35
+ /**
36
+ * Asked once per display before its first call of a `consent`-gated capability (P079): may this
37
+ * content have them (read the viewer's data)? The request is that first call. A host remembers
38
+ * the answer where it likes (per viewer, per widget); Porthole keeps it for the display's life.
39
+ */
40
+ export type Consent = (request: ConfirmRequest) => boolean | Promise<boolean>;
41
+ /**
42
+ * What the host last had for a resource (P079), answered at once, marked stale, to a read of a
43
+ * resource the content subscribes to; the fresh result follows as an update. Undefined: none.
44
+ */
45
+ export type DataCache = (args: CapabilityArgs["readData"], context: CallContext) => unknown;
21
46
  /**
22
47
  * The display a confirmation is for, as the host named it: its id and title, and the instance the
23
48
  * host gave it, served or opaque (P076, P077), so a host can word its dialog from its own records.
@@ -70,22 +95,35 @@ export type Refusal =
70
95
  /** The person took it elsewhere (edited it first): not sent, not counted as a decline. */
71
96
  | "redirected"
72
97
  /** The display was muted after too many declines (until it runs again). */
73
- | "muted" | "rate-limited"
98
+ | "muted"
99
+ /** It is `consent`-gated and there is no `consent` function. */
100
+ | "no-consent"
101
+ /** The host's `consent` said no (for this display's life). */
102
+ | "denied" | "rate-limited"
74
103
  /** The host's handler threw or rejected. */
75
104
  | "failed";
76
- export type CallOutcome<T> = {
105
+ export type CallOutcome<T> =
106
+ /** `stale`: a `readData` answered from the host's cache (`DataCache`). */
107
+ {
77
108
  readonly ok: true;
78
109
  readonly value: T;
110
+ readonly stale?: true;
79
111
  } | {
80
112
  readonly ok: false;
81
113
  readonly refusal: Refusal;
82
114
  readonly message?: string;
83
115
  };
116
+ /** What an adapter adds to a call, beyond what the content sent. */
117
+ export interface CallOptions {
118
+ readonly userActivated?: boolean;
119
+ /** `subscribeData`: the subscription's channel back and its end (`SubscriptionContext`). */
120
+ readonly subscription?: Pick<SubscriptionContext, "changed" | "signal">;
121
+ /** `readData`: the host's cache may answer, marked stale (the content subscribes to it). */
122
+ readonly stale?: boolean;
123
+ }
84
124
  /** What adapters call; one per display. */
85
125
  export interface HostFunctionBridge {
86
126
  /** Validates `args` for `capability`, applies its gates, then runs the host's handler. */
87
- call<N extends CapabilityName>(capability: N, args: unknown, options?: {
88
- readonly userActivated?: boolean;
89
- }): Promise<CallOutcome<CapabilityResults[N]>>;
127
+ call<N extends CapabilityName>(capability: N, args: unknown, options?: CallOptions): Promise<CallOutcome<CapabilityResults[N]>>;
90
128
  declared(capability: CapabilityName): boolean;
91
129
  }
@@ -1,4 +1,4 @@
1
- import { anyHttps, declaredCapabilities, egressOrigins, } from "../compile/policy.js";
1
+ import { anyHttps, declaredCapabilities, egressOrigins, librarySources, } from "../compile/policy.js";
2
2
  import { sizeWords } from "../guide/limits.js";
3
3
  import { originMatchesSource } from "../isolation/served.js";
4
4
  const lineOf = (text, index) => text.slice(0, index).split("\n").length;
@@ -122,7 +122,7 @@ export function lintContent(config, content) {
122
122
  egressOrigins(config, kind).some((source) => source === origin || originMatchesSource(origin, source));
123
123
  if (!open && !reported.has(`${kind} ${origin}`)) {
124
124
  reported.add(`${kind} ${origin}`);
125
- add("egress", "warning", `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"}.`, match.index);
125
+ add("egress", "warning", `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"}.`, match.index);
126
126
  }
127
127
  const own = OWN_CDN.find((each) => each.host.test(address));
128
128
  if (own !== undefined && kind === "script" && !own.pinned.test(new URL(address).pathname)) {