@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
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,13 @@
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 Refused } from "./refusal.ts";
5
+ import type { CapabilityHandlers, Confirm, ConfirmDisplay, Consent, DataCache, HostFunctionBridge, Refusal } from "./types.ts";
5
6
  /**
6
7
  * The host-function bridge: every capability call from a frame passes here, and nowhere else
7
8
  * 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.
9
+ * rate → a user gesture, if gated so → the viewer's consent, if gated so → a person's
10
+ * confirmation, if gated so → the handler (or, for a stale-allowed read, the host's cache).
9
11
  */
10
12
  export type BridgeEvent = {
11
13
  readonly type: "resize";
@@ -14,6 +16,11 @@ export type BridgeEvent = {
14
16
  } | {
15
17
  readonly type: "error";
16
18
  readonly message: string;
19
+ }
20
+ /** The shell cancelled a navigation of the frame to `url` (P080): the content's word. */
21
+ | {
22
+ readonly type: "navigationBlocked";
23
+ readonly url: string;
17
24
  } | {
18
25
  readonly type: "annotation";
19
26
  readonly report: AnnotationReport;
@@ -29,6 +36,14 @@ export interface BridgeOptions {
29
36
  readonly display: ConfirmDisplay;
30
37
  readonly handlers: CapabilityHandlers;
31
38
  readonly confirm?: Confirm;
39
+ /**
40
+ * Asked before a `consent`-gated call (P079). The host's, made to ask once per display by the
41
+ * caller (`createHost` keeps the answer across the display's frames). A `Refused` refuses every
42
+ * such call with it, asking nothing (P080).
43
+ */
44
+ readonly consent?: Consent | Refused;
45
+ /** The host's cache, for reads that may be answered stale (`CallOptions.stale`, P079). */
46
+ readonly cached?: DataCache;
32
47
  /** Whether the embedding page has user activation now; undefined where it can't tell. */
33
48
  readonly userActivation?: () => boolean | undefined;
34
49
  readonly onEvent: (event: BridgeEvent) => void;
@@ -37,4 +52,11 @@ export interface BridgeOptions {
37
52
  }
38
53
  /** An http(s) URL without credentials in it (`https://bank.example@evil.example` reads as a lie). */
39
54
  export declare function linkTarget(value: unknown): string | null;
55
+ /**
56
+ * The host's `consent`, asked once (P079): the first call asks, every later one gets that answer,
57
+ * for as long as the returned function is kept (`createHost` keeps one per display). A `Refused`
58
+ * it throws is an answer, kept and thrown again at every call (P080); anything else it throws is
59
+ * no answer: thrown for that call, and the next asks again.
60
+ */
61
+ export declare function onceConsent(consent: Consent): Consent;
40
62
  export declare function createBridge(options: BridgeOptions): HostFunctionBridge;
@@ -1,6 +1,8 @@
1
1
  import { MAX_COPY_CHARS, capabilitySpec, } from "../config/capabilities.js";
2
2
  import { parseReport } from "../annotate/validate.js";
3
3
  import { effectiveGates } from "../compile/policy.js";
4
+ import { blockedNavigationMessage } from "./navigation.js";
5
+ import { defaultReason, isRefused, pendingReason, reasonOf, } from "./refusal.js";
4
6
  const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
5
7
  const MAX_URL = 4_096;
6
8
  /** An http(s) URL without credentials in it (`https://bank.example@evil.example` reads as a lie). */
@@ -22,6 +24,11 @@ export function linkTarget(value) {
22
24
  }
23
25
  return url.href;
24
26
  }
27
+ /** A resource's URI, as `resources/read` and `resources/subscribe` carry it. */
28
+ function resourceUri(args) {
29
+ const uri = isRecord(args) ? args.uri : undefined;
30
+ return typeof uri === "string" && uri !== "" && uri.length <= MAX_URL ? { uri } : null;
31
+ }
25
32
  const VALIDATORS = {
26
33
  sendPrompt: (args, config) => {
27
34
  const text = isRecord(args) ? args.text : undefined;
@@ -51,10 +58,8 @@ const VALIDATORS = {
51
58
  const given = args.arguments ?? {};
52
59
  return isRecord(given) ? { name: args.name, arguments: given } : null;
53
60
  },
54
- readData: (args) => {
55
- const uri = isRecord(args) ? args.uri : undefined;
56
- return typeof uri === "string" && uri !== "" && uri.length <= MAX_URL ? { uri } : null;
57
- },
61
+ readData: (args) => resourceUri(args),
62
+ subscribeData: (args) => resourceUri(args),
58
63
  setModelContext: (args) => {
59
64
  if (!isRecord(args)) {
60
65
  return null;
@@ -69,7 +74,15 @@ const VALIDATORS = {
69
74
  ...(structuredContent === undefined ? {} : { structuredContent }),
70
75
  };
71
76
  },
72
- reportError: (args) => {
77
+ reportError: (args, config) => {
78
+ // A navigation the shell cancelled (P080): Porthole words it, naming the address without its
79
+ // query; the address itself goes to the host whole.
80
+ const blocked = isRecord(args) ? args.navigationBlocked : undefined;
81
+ if (blocked !== undefined) {
82
+ return typeof blocked === "string" && blocked !== "" && blocked.length <= MAX_URL
83
+ ? { message: blockedNavigationMessage(blocked, config), navigationBlocked: blocked }
84
+ : null;
85
+ }
73
86
  const message = isRecord(args) ? args.message : undefined;
74
87
  return typeof message === "string" && message !== ""
75
88
  ? { message: message.slice(0, 2_000) }
@@ -95,15 +108,47 @@ const VALIDATORS = {
95
108
  : { height: args.height };
96
109
  },
97
110
  };
111
+ /**
112
+ * The host's `consent`, asked once (P079): the first call asks, every later one gets that answer,
113
+ * for as long as the returned function is kept (`createHost` keeps one per display). A `Refused`
114
+ * it throws is an answer, kept and thrown again at every call (P080); anything else it throws is
115
+ * no answer: thrown for that call, and the next asks again.
116
+ */
117
+ export function onceConsent(consent) {
118
+ let answer = null;
119
+ return async (request) => {
120
+ const asked = (answer ??= Promise.resolve()
121
+ .then(() => consent(request))
122
+ .then(
123
+ // Only a real yes: anything else a host's function gives is a no (fail closed).
124
+ (allowed) => allowed === true, (error) => {
125
+ if (isRefused(error)) {
126
+ return error;
127
+ }
128
+ answer = null;
129
+ throw error;
130
+ }));
131
+ const given = await asked;
132
+ if (typeof given !== "boolean") {
133
+ throw given;
134
+ }
135
+ return given;
136
+ };
137
+ }
98
138
  export function createBridge(options) {
99
139
  const { config, display, handlers, onEvent } = options;
100
140
  const now = options.now ?? (() => Date.now());
101
141
  const calls = new Map();
102
142
  let declines = 0;
103
143
  let muted = false;
104
- const refuse = (capability, refusal, message) => {
144
+ const refuse = (capability, refusal, message, reason) => {
105
145
  onEvent({ type: "refused", capability, refusal });
106
- return { ok: false, refusal, ...(message === undefined ? {} : { message }) };
146
+ return {
147
+ ok: false,
148
+ refusal,
149
+ ...(message === undefined ? {} : { message }),
150
+ reason: reason ?? defaultReason(capability, refusal),
151
+ };
107
152
  };
108
153
  const withinRate = (capability, perMinute) => {
109
154
  const at = now();
@@ -142,10 +187,31 @@ export function createBridge(options) {
142
187
  return refuse(capability, "no-user-activation");
143
188
  }
144
189
  }
190
+ if (gates.includes("consent")) {
191
+ const consent = options.consent;
192
+ if (consent === undefined) {
193
+ return refuse(capability, "no-consent");
194
+ }
195
+ // The host's policy, known before any call: every one refused with its reason (P080).
196
+ if (isRefused(consent)) {
197
+ return refuse(capability, "denied", undefined, reasonOf(consent));
198
+ }
199
+ let answer = false;
200
+ try {
201
+ answer = await consent({ capability, args, display });
202
+ }
203
+ catch (error) {
204
+ // A Refused is the host's no, with its reason; any other failure is no answer yet.
205
+ return refuse(capability, "denied", undefined, isRefused(error) ? reasonOf(error) : pendingReason(capability));
206
+ }
207
+ if (answer !== true) {
208
+ return refuse(capability, "denied");
209
+ }
210
+ }
145
211
  // The effect, run once: when the person's "yes" calls `proceed` (inside its own click, so an
146
212
  // effect that needs a gesture gets one), or after `confirm` resolves accepted.
147
213
  let effect = null;
148
- const run = () => (effect ??= perform(capability, args));
214
+ const run = () => (effect ??= perform(capability, args, callOptions));
149
215
  if (confirms) {
150
216
  if (options.confirm === undefined) {
151
217
  return refuse(capability, "no-confirm");
@@ -174,7 +240,7 @@ export function createBridge(options) {
174
240
  return run();
175
241
  },
176
242
  };
177
- async function perform(capability, args) {
243
+ async function perform(capability, args, callOptions) {
178
244
  {
179
245
  if (capabilitySpec(capability).served === "event") {
180
246
  if (capability === "resize") {
@@ -185,7 +251,11 @@ export function createBridge(options) {
185
251
  onEvent({ type: "annotation", report: args });
186
252
  }
187
253
  else {
188
- onEvent({ type: "error", message: args.message });
254
+ const report = args;
255
+ if (report.navigationBlocked !== undefined) {
256
+ onEvent({ type: "navigationBlocked", url: report.navigationBlocked });
257
+ }
258
+ onEvent({ type: "error", message: report.message });
189
259
  }
190
260
  return { ok: true, value: undefined };
191
261
  }
@@ -193,16 +263,31 @@ export function createBridge(options) {
193
263
  if (handler === undefined) {
194
264
  return refuse(capability, "not-declared");
195
265
  }
266
+ const context = { displayId: display.id, title: display.title, capability };
267
+ // A read the content subscribes to may be answered from the host's cache, marked stale; the
268
+ // fresh one follows as an update (the adapter asks for it). A cache that fails is no answer.
269
+ if (capability === "readData" && callOptions?.stale === true && options.cached) {
270
+ try {
271
+ const cached = await options.cached(args, context);
272
+ if (cached !== undefined) {
273
+ return { ok: true, value: cached, stale: true };
274
+ }
275
+ }
276
+ catch {
277
+ // Read it fresh instead.
278
+ }
279
+ }
280
+ const subscription = callOptions?.subscription;
281
+ if (capability === "subscribeData" && subscription === undefined) {
282
+ return refuse(capability, "invalid");
283
+ }
196
284
  try {
197
- const value = await handler(args, {
198
- displayId: display.id,
199
- title: display.title,
200
- capability,
201
- });
202
- return { ok: true, value };
285
+ const value = await handler(args, capability === "subscribeData" ? { ...context, ...subscription } : context);
286
+ return { ok: true, value: value };
203
287
  }
204
288
  catch (error) {
205
- return refuse(capability, "failed", error instanceof Error ? error.message : String(error));
289
+ // A host's Refused tells content its reason (P080); any other error stays the host's.
290
+ return refuse(capability, "failed", error instanceof Error ? error.message : String(error), isRefused(error) ? reasonOf(error) : undefined);
206
291
  }
207
292
  }
208
293
  }
@@ -0,0 +1,11 @@
1
+ import type { PortholeConfig } from "../config/schema.ts";
2
+ /**
3
+ * A navigation the shell cancelled (P079), as the host is told it (P080): the address, whole, on
4
+ * the `navigationBlocked` event (the host's to keep), and a sentence for the content's errors
5
+ * (`contentError`, which a host may give the agent that wrote it) that names the address without
6
+ * its query or fragment, where a viewer's data would be.
7
+ */
8
+ /** An address without what could carry data: an http(s) one's origin and path, else its scheme. */
9
+ export declare function addressWithoutQuery(url: string): string;
10
+ /** What the content's errors say about a navigation the shell cancelled. */
11
+ export declare function blockedNavigationMessage(url: string, config: PortholeConfig): string;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * A navigation the shell cancelled (P079), as the host is told it (P080): the address, whole, on
3
+ * the `navigationBlocked` event (the host's to keep), and a sentence for the content's errors
4
+ * (`contentError`, which a host may give the agent that wrote it) that names the address without
5
+ * its query or fragment, where a viewer's data would be.
6
+ */
7
+ /** An address without what could carry data: an http(s) one's origin and path, else its scheme. */
8
+ export function addressWithoutQuery(url) {
9
+ let parsed;
10
+ try {
11
+ parsed = new URL(url);
12
+ }
13
+ catch {
14
+ return "another address";
15
+ }
16
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
17
+ return `a ${parsed.protocol} address`;
18
+ }
19
+ const rest = parsed.search !== "" || parsed.hash !== "" ? "?…" : "";
20
+ return `${parsed.origin}${parsed.pathname}${rest}`;
21
+ }
22
+ /** What the content's errors say about a navigation the shell cancelled. */
23
+ export function blockedNavigationMessage(url, config) {
24
+ const links = config.capabilities.openLink === undefined
25
+ ? ""
26
+ : config.mode === "mcp-app"
27
+ ? " Open links with ui/open-link (a new tab)."
28
+ : " Open links with openLink(url) or an <a href> (a new tab).";
29
+ return `It tried to navigate its frame to ${addressWithoutQuery(url)}, and was stopped: content never leaves its page.${links}`;
30
+ }
@@ -0,0 +1,53 @@
1
+ import type { CapabilityName } from "../config/capabilities.ts";
2
+ import type { Refusal } from "./types.ts";
3
+ /**
4
+ * Why a call was refused, as content is told (P080): a code it can branch on and a sentence it can
5
+ * show the person viewing it. Carried in a refused request's JSON-RPC error, as its `data`; the
6
+ * shell's globals reject with an error that has both (`error.code`, `error.message`).
7
+ *
8
+ * - `consent_required`: the viewer hasn't allowed it yet (their answer is still to come).
9
+ * - `denied`: the viewer (or the person asked to confirm) said no.
10
+ * - `rate_limited`: too many calls this minute.
11
+ * - `not_allowed`: the host doesn't let this content have it, here or at all (a URI it doesn't
12
+ * serve, a page where data never runs).
13
+ * - `failed`: the host tried and couldn't.
14
+ */
15
+ export declare const REFUSAL_CODES: readonly ["consent_required", "denied", "rate_limited", "not_allowed", "failed"];
16
+ export type RefusalCode = (typeof REFUSAL_CODES)[number];
17
+ /** What content is told about a refusal: the JSON-RPC error's `data`. */
18
+ export interface RefusalReason {
19
+ readonly code: RefusalCode;
20
+ /** A sentence for the person viewing the content: the host's, else Porthole's. */
21
+ readonly message: string;
22
+ }
23
+ export declare function isRefusalCode(value: unknown): value is RefusalCode;
24
+ /**
25
+ * A refusal the host gives, with the reason content is told (P080). Throw it from a handler (this
26
+ * URI isn't one you serve: `not_allowed`; the viewer didn't allow this kind of data: `denied`), or
27
+ * from a `consent` function (kept as the display's answer, as `false` is). Or pass one as
28
+ * `HostOptions.consent` itself: every `consent`-gated call is refused with it, and those
29
+ * capabilities need no handler (a page where data never runs).
30
+ *
31
+ * Any other error a handler throws is `failed` with Porthole's words: its message stays the host's.
32
+ */
33
+ export declare class Refused extends Error {
34
+ readonly code: RefusalCode;
35
+ /** `message`: a sentence for the viewer; absent, Porthole's for the code. */
36
+ constructor(code: RefusalCode, message?: string);
37
+ }
38
+ /**
39
+ * Whether `value` is a `Refused`: by class, or by shape where two copies of Porthole meet (a
40
+ * host's bundle and a library's).
41
+ */
42
+ export declare function isRefused(value: unknown): value is Refused;
43
+ /** The reason a host's `Refused` gives content. */
44
+ export declare function reasonOf(refused: Refused): RefusalReason;
45
+ /** What content is told about a refusal Porthole made (the host gave no `Refused`). */
46
+ export declare function defaultReason(capability: CapabilityName, refusal: Refusal): RefusalReason;
47
+ /** What content is told about a refused call: the bridge's reason, else Porthole's for it. */
48
+ export declare function reasonFor(capability: CapabilityName, outcome: {
49
+ readonly refusal: Refusal;
50
+ readonly reason?: RefusalReason;
51
+ }): RefusalReason;
52
+ /** A consent function that failed (threw, rejected): not an answer, so asked again at the next. */
53
+ export declare function pendingReason(capability: CapabilityName): RefusalReason;
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Why a call was refused, as content is told (P080): a code it can branch on and a sentence it can
3
+ * show the person viewing it. Carried in a refused request's JSON-RPC error, as its `data`; the
4
+ * shell's globals reject with an error that has both (`error.code`, `error.message`).
5
+ *
6
+ * - `consent_required`: the viewer hasn't allowed it yet (their answer is still to come).
7
+ * - `denied`: the viewer (or the person asked to confirm) said no.
8
+ * - `rate_limited`: too many calls this minute.
9
+ * - `not_allowed`: the host doesn't let this content have it, here or at all (a URI it doesn't
10
+ * serve, a page where data never runs).
11
+ * - `failed`: the host tried and couldn't.
12
+ */
13
+ export const REFUSAL_CODES = [
14
+ "consent_required",
15
+ "denied",
16
+ "rate_limited",
17
+ "not_allowed",
18
+ "failed",
19
+ ];
20
+ /** The most a refusal's message carries to content. */
21
+ const MAX_MESSAGE = 500;
22
+ export function isRefusalCode(value) {
23
+ return typeof value === "string" && REFUSAL_CODES.includes(value);
24
+ }
25
+ /**
26
+ * A refusal the host gives, with the reason content is told (P080). Throw it from a handler (this
27
+ * URI isn't one you serve: `not_allowed`; the viewer didn't allow this kind of data: `denied`), or
28
+ * from a `consent` function (kept as the display's answer, as `false` is). Or pass one as
29
+ * `HostOptions.consent` itself: every `consent`-gated call is refused with it, and those
30
+ * capabilities need no handler (a page where data never runs).
31
+ *
32
+ * Any other error a handler throws is `failed` with Porthole's words: its message stays the host's.
33
+ */
34
+ export class Refused extends Error {
35
+ code;
36
+ /** `message`: a sentence for the viewer; absent, Porthole's for the code. */
37
+ constructor(code, message) {
38
+ if (!isRefusalCode(code)) {
39
+ throw new TypeError(`Refused: code must be one of ${REFUSAL_CODES.join(", ")}`);
40
+ }
41
+ super(message === undefined || message.trim() === "" ? DEFAULT_MESSAGES[code] : message);
42
+ this.name = "Refused";
43
+ this.code = code;
44
+ }
45
+ }
46
+ /**
47
+ * Whether `value` is a `Refused`: by class, or by shape where two copies of Porthole meet (a
48
+ * host's bundle and a library's).
49
+ */
50
+ export function isRefused(value) {
51
+ return (value instanceof Refused ||
52
+ (value instanceof Error &&
53
+ value.name === "Refused" &&
54
+ isRefusalCode(value.code)));
55
+ }
56
+ /** The reason a host's `Refused` gives content. */
57
+ export function reasonOf(refused) {
58
+ const message = refused.message.trim();
59
+ return {
60
+ code: refused.code,
61
+ message: (message === "" ? DEFAULT_MESSAGES[refused.code] : message).slice(0, MAX_MESSAGE),
62
+ };
63
+ }
64
+ /** Porthole's sentence for each code, where the host gave none. */
65
+ const DEFAULT_MESSAGES = {
66
+ consent_required: "This needs your permission first.",
67
+ denied: "You didn't allow this.",
68
+ rate_limited: "Too many requests: try again in a minute.",
69
+ not_allowed: "This isn't available here.",
70
+ failed: "The app couldn't do this.",
71
+ };
72
+ /** Where a data capability's words differ: they name the data. */
73
+ const DATA_MESSAGES = {
74
+ consent_required: "Reading this data needs your permission first.",
75
+ denied: "You didn't allow this to read your data.",
76
+ rate_limited: "Too many data requests: try again in a minute.",
77
+ not_allowed: "This data isn't available here.",
78
+ failed: "The app couldn't get this data.",
79
+ };
80
+ /** Each refusal's code, as content is told it. */
81
+ const CODES = {
82
+ "not-declared": "not_allowed",
83
+ invalid: "not_allowed",
84
+ "no-user-activation": "not_allowed",
85
+ "no-confirm": "not_allowed",
86
+ declined: "denied",
87
+ redirected: "denied",
88
+ muted: "denied",
89
+ "no-consent": "not_allowed",
90
+ denied: "denied",
91
+ "rate-limited": "rate_limited",
92
+ failed: "failed",
93
+ };
94
+ /** Refusals whose own words say more than their code's. */
95
+ const OWN_MESSAGES = {
96
+ "no-user-activation": "This needs a click.",
97
+ invalid: "The app can't take this request.",
98
+ muted: "You declined this too often: it isn't asked again until it runs again.",
99
+ };
100
+ /** What content is told about a refusal Porthole made (the host gave no `Refused`). */
101
+ export function defaultReason(capability, refusal) {
102
+ const code = CODES[refusal];
103
+ const data = capability === "readData" || capability === "subscribeData";
104
+ return {
105
+ code,
106
+ message: OWN_MESSAGES[refusal] ?? (data ? DATA_MESSAGES : DEFAULT_MESSAGES)[code],
107
+ };
108
+ }
109
+ /** What content is told about a refused call: the bridge's reason, else Porthole's for it. */
110
+ export function reasonFor(capability, outcome) {
111
+ const reason = outcome.reason ?? defaultReason(capability, outcome.refusal);
112
+ return { code: reason.code, message: reason.message };
113
+ }
114
+ /** A consent function that failed (threw, rejected): not an answer, so asked again at the next. */
115
+ export function pendingReason(capability) {
116
+ const data = capability === "readData" || capability === "subscribeData";
117
+ return {
118
+ code: "consent_required",
119
+ message: (data ? DATA_MESSAGES : DEFAULT_MESSAGES).consent_required,
120
+ };
121
+ }
@@ -1,5 +1,6 @@
1
1
  import type { CapabilityArgs, CapabilityName, CapabilityResults, HandledCapability } from "../config/capabilities.ts";
2
2
  import type { InstanceRef } from "../isolation/types.ts";
3
+ import type { RefusalReason } from "./refusal.ts";
3
4
  /**
4
5
  * The host-function bridge (ARCHITECTURE § Framework layer): carries a capability call from the
5
6
  * frame to the host's handler and its result back, checking at the boundary that the capability
@@ -13,11 +14,39 @@ export interface CallContext {
13
14
  readonly title: string;
14
15
  readonly capability: CapabilityName;
15
16
  }
16
- export type CapabilityHandler<N extends CapabilityName> = (args: CapabilityArgs[N], context: CallContext) => CapabilityResults[N] | Promise<CapabilityResults[N]>;
17
+ export type CapabilityHandler<N extends CapabilityName> = (args: CapabilityArgs[N], context: N extends "subscribeData" ? SubscriptionContext : CallContext) => CapabilityResults[N] | Promise<CapabilityResults[N]>;
18
+ /**
19
+ * A subscription's context (`subscribeData`, P079): how the host tells the content its resource
20
+ * changed, and when to stop.
21
+ */
22
+ export interface SubscriptionContext extends CallContext {
23
+ /**
24
+ * The resource changed: the content is told (`notifications/resources/updated`) and reads it
25
+ * again. Pass the new `resources/read` result to answer that read without another call to
26
+ * `readData`.
27
+ */
28
+ readonly changed: (result?: unknown) => void;
29
+ /** Aborted when the content unsubscribes, its frame stops, or the display is destroyed. */
30
+ readonly signal: AbortSignal;
31
+ }
17
32
  /** The host's handlers: one for each declared capability served by a handler. */
18
33
  export type CapabilityHandlers = {
19
34
  readonly [N in HandledCapability]?: CapabilityHandler<N>;
20
35
  };
36
+ /**
37
+ * Asked once per display before its first call of a `consent`-gated capability (P079): may this
38
+ * content have them (read the viewer's data)? The request is that first call. A host remembers
39
+ * the answer where it likes (per viewer, per widget); Porthole keeps it for the display's life.
40
+ * `false` is a no (content is told `denied`); a thrown `Refused` is a no with its reason, kept
41
+ * the same way (P080); anything else it throws is no answer yet (`consent_required`), and the next
42
+ * call asks again.
43
+ */
44
+ export type Consent = (request: ConfirmRequest) => boolean | Promise<boolean>;
45
+ /**
46
+ * What the host last had for a resource (P079), answered at once, marked stale, to a read of a
47
+ * resource the content subscribes to; the fresh result follows as an update. Undefined: none.
48
+ */
49
+ export type DataCache = (args: CapabilityArgs["readData"], context: CallContext) => unknown;
21
50
  /**
22
51
  * The display a confirmation is for, as the host named it: its id and title, and the instance the
23
52
  * host gave it, served or opaque (P076, P077), so a host can word its dialog from its own records.
@@ -70,22 +99,38 @@ export type Refusal =
70
99
  /** The person took it elsewhere (edited it first): not sent, not counted as a decline. */
71
100
  | "redirected"
72
101
  /** The display was muted after too many declines (until it runs again). */
73
- | "muted" | "rate-limited"
102
+ | "muted"
103
+ /** It is `consent`-gated and there is no `consent` function. */
104
+ | "no-consent"
105
+ /** The host's `consent` said no (for this display's life). */
106
+ | "denied" | "rate-limited"
74
107
  /** The host's handler threw or rejected. */
75
108
  | "failed";
76
- export type CallOutcome<T> = {
109
+ export type CallOutcome<T> =
110
+ /** `stale`: a `readData` answered from the host's cache (`DataCache`). */
111
+ {
77
112
  readonly ok: true;
78
113
  readonly value: T;
114
+ readonly stale?: true;
79
115
  } | {
80
116
  readonly ok: false;
81
117
  readonly refusal: Refusal;
118
+ /** What the host's handler threw: the host's own words, never sent to content. */
82
119
  readonly message?: string;
120
+ /** What content is told (P080): the host's `Refused`, else Porthole's for the refusal. */
121
+ readonly reason?: RefusalReason;
83
122
  };
123
+ /** What an adapter adds to a call, beyond what the content sent. */
124
+ export interface CallOptions {
125
+ readonly userActivated?: boolean;
126
+ /** `subscribeData`: the subscription's channel back and its end (`SubscriptionContext`). */
127
+ readonly subscription?: Pick<SubscriptionContext, "changed" | "signal">;
128
+ /** `readData`: the host's cache may answer, marked stale (the content subscribes to it). */
129
+ readonly stale?: boolean;
130
+ }
84
131
  /** What adapters call; one per display. */
85
132
  export interface HostFunctionBridge {
86
133
  /** 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]>>;
134
+ call<N extends CapabilityName>(capability: N, args: unknown, options?: CallOptions): Promise<CallOutcome<CapabilityResults[N]>>;
90
135
  declared(capability: CapabilityName): boolean;
91
136
  }
@@ -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)) {